Newer
Older
#: The directory in which wordlists are stored
SRC_DIR = os.path.dirname(__file__)
#: 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 = "~!#$%^&*()-=+[]\{}:;\"'<>?/0123456789"
def handle_options(args):
"""Handle commandline options.
"""
parser = argparse.ArgumentParser(description="Create a passphrase")
parser.add_argument(
'-n', '--num', default=6, type=int,
help='number of words to concatenate. Default: 6')
cap_group = parser.add_mutually_exclusive_group()
cap_group.add_argument(
help='Capitalize words. This is the default.')
cap_group.add_argument(
def get_wordlist(path):
"""Parse file at `path` and build a word list of it.
A wordlist is expected to contain lines of words. Each line a
word. Empty lines are ignored. Returns a list of terms (lines)
found.
result = [line.strip() for line in fd.readlines()
if line.strip() != '']
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.
"""
raise ValueError("Not a valid language code: %s" % lang)
return os.path.abspath(os.path.join(SRC_DIR, basename.lower()))
def get_passphrase(wordnum=6, specials=True, separator='', lang='en',
capitalized=True):
"""Get a diceware passphrase.
"""
word_list = get_wordlist(get_wordlist_path(lang))
rnd = SystemRandom()
words = [rnd.choice(word_list) for x in range(wordnum)]
if capitalized:
words = [x.capitalize() for x in words]
result = separator.join(words)
result = list(result)
result[rnd.choice(range(len(result)))] = rnd.choice(SPECIAL_CHARS)
result = ''.join(result)
return result
def main(args=1):
if args is 1:
args = sys.argv[1:]
options = handle_options(args)
print(get_passphrase(wordnum=options.num,
capitalized=options.capitalize))