@ wrote... (4 years, 7 months ago)

There are dozens of similar programs on the the ol' internetz and here's mine.

I'm not a cryptographer.


import argparse
import string

import random as _random
random = _random.SystemRandom()

def generate_password(nchars, no_visual, include_punctuation):

    punctuation = set(string.punctuation) - set("'`\"") # quotes and backtick
    digits = set(string.digits)
    letters = set(string.ascii_letters) # includes lower and upper case

    if no_visual:
        digits -= set("10") # visually similar to lO and very common in passwords

    if include_punctuation:
        groups = [punctuation, digits, letters]
        punctuation = set()
        groups = [digits, letters]

    characters = punctuation | digits | letters

    password = []

    # make sure we have at least one char from each group
    # 1 or 2 chars from each group to break pattern
    for group in groups:
        password += random.sample(group, random.randint(1,2))

    # sample is pretty picky about sample size. 0 < n < 94
    while len(password) < nchars:
        password += random.sample(characters, 1)

    return "".join(password)

if __name__ == '__main__':

    parser = argparse.ArgumentParser(description='generate a password')
    parser.add_argument('num_chars', metavar='N', type=int, nargs='?', default=30,
                    help='number of characters in password')
    parser.add_argument('--no-visual', action='store_true', default=False,
                    help="don't use visually similar characters (01)")
    parser.add_argument('--punctuation', action='store_true', default=False,
                    help="include punctuation in password")

    args = parser.parse_args()

    print generate_password(args.num_chars, args.no_visual, args.punctuation)
$ mk_passwd
$ mkpasswd --punctuation
Category: tech, Tags: python
Comments: 0
Click here to add a comment