# API

diceware code is geared towards commandline usage. You can, however, use it from Python. The API docs are here to assist you with that.

For using diceware in your own, setuptools-based Python project, you can add it as an install requirement in `setup.py` of your project:

    from setuptools import setup
    # ...
    setup(
        name="myproject",
        # ...
        install_requires=[
            #  packages we depend on...
            'setuptools',
            'diceware',
            # ...
        ],
        # ...
    )

Of course there are other ways to make diceware available.

## diceware main module

diceware – rememberable passphrases

diceware.SPECIAL_CHARS = '~!#$%^&*()-=+[]\\{}:;"\'<>?/0123456789'

  Special chars inserted on demand

diceware.get_passphrase(options=None)

  Get a diceware passphrase.

  options is a set of arguments as provided by argparse.OptionParser.parse_args().

  The passphrase returned will contain options.num words delimited by options.delimiter and options.specials special chars.

  For the passphrase generation we will use the random source registered under the name options.randomsource (something like “system” or “dice”).

  If options.caps is `True`, all words will be caps.

  If options.infile, a file descriptor, is given, it will be used instead of a ‘built-in’ wordlist. options.infile must be open for reading.

diceware.get_random_sources()

  Get a dictionary of all entry points called diceware_random_source.

  Returns a dictionary with names mapped to callables registered as entry_point`s for the ``diceware_randomsource` group.

  Callables should accept options when called and return something that provides a choice(sequence) method that works like the respective method in the standard Python lib random module.

diceware.handle_options(args)

  Handle commandline options.

diceware.insert_special_char(word, specials='~!#$%^&*()-=+[]\\{}:;"\'<>?/0123456789', rnd=None)

  Insert a char out of specials into word.

  rnd, if passed in, will be used as a (pseudo) random number generator. We use .choice() only.

  Returns the modified word.

diceware.main(args=None)

  Main programme.

  Called when diceware script is called.

  args is a list of command line arguments to process. If no such args are given, we use sys.argv.

diceware.print_version()

  Output current version and other infos.

diceware.print_wordlist_dirs()

  Output all dirs we look up for wordlists.

## diceware.logger

logging – output status and other data.

The logger provided in this module is meant to be used by other components for messages to users.

It is named “ulif.openoffice” and can, as a singleton, be retrieved by calling standard lib logging.getLogger(“ulif.diceware”).

By default it provides a logging.NullHandler as libraries normally do. Other components might add other handlers.

diceware.logger.configure(verbosity=None)

  Configure global diceware logger.

  verbosity sets the diceware logger verbosity. `0` enables info mode, while all numbers > 2 enable debug mode.

  If no verbosity is given, we leave the logging level untouched.

diceware.logger.logger = <Logger ulif.diceware (WARNING)>

  Logger that can be used for all diceware related messages.

## diceware.config

config – diceware configuration

diceware is configurable via commandline, configuration files and direct API calls.

diceware.config.RE_WLIST_NAME = re.compile('(?![\\w\\-]+).')

  valid wordlist names

diceware.config.get_config_dict(path_list=None, defaults_dict={'caps': True, 'delimiter': '', 'dice_sides': 6, 'num': 6, 'randomsource': 'system', 'specials': 0, 'verbose': 0, 'wordlist': ['en_eff']}, section='diceware')

  Get config values found in files from path_list.

  Read files in path_list config files and return option values from section section as regular dictionary.

  We only accept values for which a default exists in defaults_dict. If defaults_dict is `None` we use `OPTIONS_DEFAULTS`.

  Values are interpolated to have same value type as same-named values from defaults_dict if they are integers or boolean.

  String/text values are stripped from preceding/trailing quotes (single and double).

diceware.config.get_configparser(path_list=None)

  Parse path_list for config values.

  If no list is given we use valid_locations().

  Return a list of paths read and a config parser instance.

diceware.config.string_to_wlist_list(text)

  Split string into list of valid wordlist names.

diceware.config.valid_locations()

  The list of valid paths we look up for config files.

  We search for config files in the following locations (in that order):

  1a) dirs in colon-separated var $XDG_CONFIG_DIRS 1b) /etc/xdg/diceware/diceware.ini # if $XDG_CONFIG_DIRS is undefined 2a) $XDG_CONFIG_HOME/diceware/diceware.ini # if $XDG_CONFIG_HOME is defined 2b) $HOME/.config/diceware/diceware.ini # if $HOME is defined but not $XDG_CONFIG_HOME

  Finally we look also for:

  3. ~/.diceware.ini

  Later read configs override prior ones. Therefore an existing ~/.diceware.ini contains values that cannot be overridden, except on commandline.

## diceware.wordlist

wordlist.py – special handling of wordlists.

diceware.wordlist.MAX_IN_MEM_SIZE = 20971520

  Maximum in-memory file size in bytes (20 MB).

  This value is used when creating temporary files replacing unseekable input streams. If an input file is larger, we write to disk.

diceware.wordlist.RE_NUMBERED_WORDLIST_ENTRY = re.compile('^[0-9]+(\\-[0-9]+)*\\s+([^\\s]+)$')

  A regular expression matching numbered entries in wordlists.

diceware.wordlist.RE_VALID_WORDLIST_FILENAME = re.compile('^wordlist_([\\w-]+)\\.[\\w][\\w\\.]+[\\w]+$')

  A regular expression describing valid wordlist file names.

diceware.wordlist.RE_WORDLIST_NAME = re.compile('^[\\w-]+$')

  A regular expression matching allowed wordlist names. We allow names that cannot easily mess up filesystems.

class diceware.wordlist.WordList(path)

  A word list contains words for building passphrases.

  path is the path of the wordlist file. With single dash (`-`) as path, we read from sys.stdin.

  In case input comes from stdin, we write the input stream into a file if the content length is larger than MAX_IN_MEM_SIZE. Otherwise, the wordlist is kept in memory.

  Wordlist files are expected to contain words, one word per line. Empty lines are ignored, also whitespaces before or trailing a line are stripped. If a “word” contains inner whitespaces, then these are preserved.

  The input file can be a signed wordlist. Signed wordlists are expected to be ordinary lists of words but with ASCII armored signatures (as described in RFC 4880).

  In case of signed wordlists the signature headers/footers are stripped and the contained list of words is read.

  WordList are generators. That means, that you can retrieve the words of a wordlist by iterating over an instance of WordList.

  is_signed()

    check, whether this file is cryptographically signed.

    This operation is expensive and resets the file descriptor to the beginning of file.

  refine_entry(entry)

    Apply modifications to form a proper wordlist entry.

    Refining means: strip() entry remove escape-dashes (if this is a signed wordlist) and extract the term if it is preceded by numbers.

diceware.wordlist.get_wordlist_dirs()

  Get the directories in which wordlists can be stored.

  We look into the following dirs (in that order): (1) Local wordlists dir (part of install) (2a) ${XDG_DATA_HOME}/diceware/ (if $XDG_DATA_HOME is defined) (2b) ${HOME}/.local/share/diceware/ (else) if ${XDG_DATA_DIRS} is defined (3a) <DIR>/diceware/ for each <DIR> in ${XDG_DATA_DIRS} else (3b) /usr/local/share/diceware/, /usr/share/diceware/

diceware.wordlist.get_wordlist_names()

  Get a all names of wordlists stored locally.

diceware.wordlist.get_wordlist_path(name)

  Get path to a wordlist file for a wordlist named name.

  The name string must not contain special chars beside `-`, `_`, regular chars `A-Z` (upper or lower case) or numbers. Invalid names raise a ValueError.

  If a path with the given name (names are not filenames here) does not exist, None is returned.

diceware.wordlist.get_wordlists_dir()

  Get the directory in which word lists are stored.

## diceware.random_sources

Sources of randomness.

Please register all sources as entry point in `__about__.py`. Look out for “SystemRandomSource” for an example.

For developers of interfaces to other sources of randomness: Currently, you can extend diceware random sources by registering a class, that provides a suitable __init__(self, options) and a choice(self, sequence) method. Optionally, you can also provide a classmethod called `update_arparse` that will get the possibility to update the argparser.ArgumentParser used by diceware.

The __init__ method of your class will be called with options, a set of options as parsed from the commandline. The initialization code can use the options to determine further actions or ignore it. The __init__ method is also the right place to ask users for one-time infos you need. This includes infos like the number of sides of a dice, an API key for random.org or other infos that should not change between generating different words (but might change from one diceware call to the next).

The choice method then, will get a sequence of chars, strings, or numbers and should pick one of them based on the source of randomness intended to be utilized by your code. If further user interaction is required, choice might also ask users for input or similar. Typically, choice is called once for each word and once for each special char to generate.

If you want to manage own commandline options with your plugin, you can implement a classmethod called `update_argparser(parser)` which gets an argparse.ArgumentParser instance as argument (no pun intended).

Finally, to register the source, add some stanza in __about__.py that looks like:

    # ...
    random_sources' = {
         # ...
        'myrandom': 'mypkg.mymodule:MyRandomSource',
        'myothersrc': 'mypkg.mymodule:MyOtherSource',
    }
    # ...

Here the myrandom and myothersrc lines register random sources that (if installed) diceware will find on startup and offer to users under the name given. In the described case, users could do for instance:

    diceware -r myrandom

and the random source defined in the given class would be used for generating a passphrase.

class diceware.random_sources.RealDiceRandomSource(options)

  A source of randomness working with real dice.

  choice(sequence)

    Pick one item out of sequence.

  get_num_rolls(seq_len)

    Compute how many dice rolls we need to pick a value from a sequence

  pre_check(num_rolls, sequence)

    Checks performed before picking an item of a sequence.

    We make sure that num_rolls, the number of rolls, is in an acceptable range and issue an hint about the procedure.

class diceware.random_sources.SystemRandomSource(options)

  A Random Source utilizing the standard Python SystemRandom call.

  As time of writing, SystemRandom makes use of `/dev/urandom` to get fairly useable random numbers.

  This source is registered as entry_point in setup.py under the name ‘system’ in the `diceware_random_sources` group.

  The constructor will be called with options at beginning of a programme run if the user has chosen the respective source of random.

  The SystemRandomSource is the default source.

  choice(sequence)

    Pick one item out of sequence.

    The sequence will normally be a sequence of strings (wordlist), special chars, or numbers.

    Sequences can be (at least) lists, tuples and other types that have a len. Generators do not have to be supported (and are in fact not supported by this source).

    This method should return one item of the sequence picked based on the underlying source of randomness.

    In the long run, the choice should return each sequence item (i.e.: no items should be ‘unreachable’).

    It should also cope with any length > 0 of sequence and not break if a sequence is “too short” or “too long”. Empty sequences, however, might raise exceptions.