Skip to content
Snippets Groups Projects
__init__.py 6.57 KiB
Newer Older
  • Learn to ignore specific revisions
  • ulif's avatar
    ulif committed
    #  diceware -- passphrases to remember
    #  Copyright (C) 2015  Uli Fouquet
    #
    #  This program is free software: you can redistribute it and/or modify
    #  it under the terms of the GNU General Public License as published by
    #  the Free Software Foundation, either version 3 of the License, or
    #  (at your option) any later version.
    #
    #  This program is distributed in the hope that it will be useful,
    #  but WITHOUT ANY WARRANTY; without even the implied warranty of
    #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    #  GNU General Public License for more details.
    #
    #  You should have received a copy of the GNU General Public License
    #  along with this program.  If not, see <http://www.gnu.org/licenses/>.
    
    ulif's avatar
    ulif committed
    """diceware -- rememberable passphrases
    """
    
    ulif's avatar
    ulif committed
    import argparse
    
    ulif's avatar
    ulif committed
    import os
    
    ulif's avatar
    ulif committed
    import pkg_resources
    
    ulif's avatar
    ulif committed
    import re
    
    ulif's avatar
    ulif committed
    import sys
    
    from random import SystemRandom
    
    
    ulif's avatar
    ulif committed
    __version__ = pkg_resources.get_distribution('diceware').version
    
    ulif's avatar
    ulif committed
    
    #: The directory in which wordlists are stored
    
    ulif's avatar
    ulif committed
    WORDLISTS_DIR = os.path.abspath(
    
        os.path.join(os.path.dirname(__file__), 'wordlists'))
    
    ulif's avatar
    ulif committed
    
    
    ulif's avatar
    ulif committed
    #: A regular expression matching 2 consecutive ASCII chars. We
    #: consider this to represent some language/country code.
    RE_LANG_CODE = re.compile('^[a-zA-Z]{2}$')
    
    #: Special chars inserted on demand
    
    SPECIAL_CHARS = r"~!#$%^&*()-=+[]\{}:;" + r'"' + r"'<>?/0123456789"
    
    ulif's avatar
    ulif committed
    
    
    ulif's avatar
    ulif committed
    
    
    ulif's avatar
    ulif committed
    GPL_TEXT = (
        """
        This program is free software: you can redistribute it and/or modify
        it under the terms of the GNU General Public License as published by
        the Free Software Foundation, either version 3 of the License, or
        (at your option) any later version.
    
        This program is distributed in the hope that it will be useful,
        but WITHOUT ANY WARRANTY; without even the implied warranty of
        MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
        GNU General Public License for more details.
    
        You should have received a copy of the GNU General Public License
        along with this program.  If not, see <http://www.gnu.org/licenses/>.
        """
        )
    
    
    def print_version():
        """Output current version and other infos.
        """
        print("diceware %s" % __version__)
        print("Copyright (C) 2015 Uli Fouquet")
        print("diceware is based on suggestions of Arnold G. Reinhold.")
        print("See http://diceware.com for details.")
    
        print("'Diceware' is a trademark of Arnold G. Reinhold.")
        print(GPL_TEXT)
    
    
    
    ulif's avatar
    ulif committed
    def handle_options(args):
        """Handle commandline options.
        """
        parser = argparse.ArgumentParser(description="Create a passphrase")
    
    ulif's avatar
    ulif committed
        parser.add_argument(
            '-n', '--num', default=6, type=int,
            help='number of words to concatenate. Default: 6')
    
    ulif's avatar
    ulif committed
        cap_group = parser.add_mutually_exclusive_group()
        cap_group.add_argument(
    
    ulif's avatar
    ulif committed
            '-c', '--caps', action='store_true',
    
    ulif's avatar
    ulif committed
            help='Capitalize words. This is the default.')
        cap_group.add_argument(
    
    ulif's avatar
    ulif committed
            '--no-caps', action='store_false', dest='capitalize',
    
    ulif's avatar
    ulif committed
            help='Turn off capitalization.')
    
    ulif's avatar
    ulif committed
        parser.add_argument(
    
    ulif's avatar
    ulif committed
            '-s', '--specials', default=0, type=int, metavar='NUM',
    
    ulif's avatar
    ulif committed
            help="Insert NUM special chars into generated word.")
    
    ulif's avatar
    ulif committed
        parser.add_argument(
            '-d', '--delimiter', default='',
            help="Separate words by DELIMITER. Empty string by default.")
    
    ulif's avatar
    ulif committed
        parser.add_argument(
            'infile', nargs='?', metavar='INFILE', default=None,
            type=argparse.FileType('r'),
    
    ulif's avatar
    ulif committed
            help="Input wordlist. `-' will read from stdin.",
    
    ulif's avatar
    ulif committed
            )
    
        parser.add_argument(
            '--version', action='store_true',
            help='output version information and exit.',
            )
    
    ulif's avatar
    ulif committed
        parser.set_defaults(capitalize=True)
    
    ulif's avatar
    ulif committed
        args = parser.parse_args(args)
        return args
    
    
    
    ulif's avatar
    ulif committed
    def get_wordlist(file_descriptor):
        """Parse file in `file_descriptor` and build a word list of it.
    
    ulif's avatar
    ulif committed
    
    
    ulif's avatar
    ulif committed
        `file_descriptor` is expected to be a file descriptor, already
    
    ulif's avatar
    ulif committed
        opened for reading. The descriptor will be closed after
        processing.
    
    ulif's avatar
    ulif committed
    
        A wordlist is expected to contain lines of words. Each line a
        word. Empty lines are ignored. Returns a list of terms (lines)
        found.
        """
    
    ulif's avatar
    ulif committed
        result = [
            line.strip() for line in file_descriptor.readlines()
            if line.strip() != '']
        file_descriptor.close()
        return result
    
    ulif's avatar
    ulif committed
    def get_wordlist_path(lang):
        """Get path to a wordlist file for language `lang`.
    
        The `lang` string is a 2-char country code. Invalid codes raise a
        ValueError.
        """
    
    ulif's avatar
    ulif committed
        if not RE_LANG_CODE.match(lang):
    
    ulif's avatar
    ulif committed
            raise ValueError("Not a valid language code: %s" % lang)
    
    ulif's avatar
    ulif committed
        basename = 'wordlist_%s.txt' % lang
    
    ulif's avatar
    ulif committed
        return os.path.join(WORDLISTS_DIR, basename.lower())
    
    ulif's avatar
    ulif committed
    def insert_special_char(word, specials=SPECIAL_CHARS, 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.
        """
        if rnd is None:
            rnd = SystemRandom()
        char_list = list(word)
        char_list[rnd.choice(range(len(char_list)))] = rnd.choice(specials)
        return ''.join(char_list)
    
    
    
    ulif's avatar
    ulif committed
    def get_passphrase(wordnum=6, specialsnum=1, delimiter='', lang='en',
    
    ulif's avatar
    ulif committed
                       capitalized=True, wordlist_fd=None):
    
        """Get a diceware passphrase.
    
    ulif's avatar
    ulif committed
    
        The passphrase returned will contain `wordnum` words deliimted by
        `delimiter`.
    
        If `capitalized` is ``True``, all words will be capitalized.
    
    
    ulif's avatar
    ulif committed
        If `wordlist_fd`, a file descriptor, is given, it will be used
        instead of a 'built-in' wordlist (and `lang` will be
        ignored). `wordlist_fd` must be open for reading.
    
    ulif's avatar
    ulif committed
    
    
    ulif's avatar
    ulif committed
        The wordlist to pick words from is determined by `lang`,
    
    ulif's avatar
    ulif committed
        representing a language (unless `wordlist_fd` is given).
    
    
    ulif's avatar
    ulif committed
        if wordlist_fd is None:
            wordlist_fd = open(get_wordlist_path(lang), 'r')
        word_list = get_wordlist(wordlist_fd)
    
        rnd = SystemRandom()
        words = [rnd.choice(word_list) for x in range(wordnum)]
        if capitalized:
            words = [x.capitalize() for x in words]
    
    ulif's avatar
    ulif committed
        result = delimiter.join(words)
    
    ulif's avatar
    ulif committed
        for _ in range(specialsnum):
    
    ulif's avatar
    ulif committed
            result = insert_special_char(result, rnd=rnd)
    
    ulif's avatar
    ulif committed
    def main(args=None):
    
    ulif's avatar
    ulif committed
        """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`.
        """
    
    ulif's avatar
    ulif committed
        if args is None:
    
    ulif's avatar
    ulif committed
            args = sys.argv[1:]
        options = handle_options(args)
    
    ulif's avatar
    ulif committed
        if options.version:
            print_version()
    
            raise SystemExit(0)
    
    ulif's avatar
    ulif committed
        print(
            get_passphrase(
                wordnum=options.num,
                specialsnum=options.specials,
                delimiter=options.delimiter,
                capitalized=options.capitalize,
    
    ulif's avatar
    ulif committed
                wordlist_fd=options.infile,