15th April, 2014

Generating Reasonable Passwords with Python

Filed under: python — andy47 @ 4:33 pm

Thanks to a certain recent Open SSL bug there’s been a lot of attention paid to passwords in the media. I’ve been using KeePassX to manage my passwords for the last few years so it’s easy for me to find accounts that I should update. It’s also a good opportunity to use stronger passwords than ‘banana’.

My problem is that I have always resisted the generation function in KeePassX because the resulting strings are very hard to remember and transcribe. This isn’t an issue if you always use one machine but I tend to chop and change and don’t always have my password database on the machine I’m using. I usually have a copy on my phone but successfully typing ‘Gh46^f27EEGR1p{‘ is a hit and miss affair for me. So I prefer passwords that are long but easy to remember, not unlike the advice from XKCD.

Which leaves a problem. Given that I now have to change quite a lot of passwords how can I create suitably random passwords that aren’t too difficult to remember or transcribe? Quite coincidentally I read an article titled “Using Vim as a password manager”. The advice within it is quite sound and at the bottom there is a Python function to generate a password from word lists (in this case the system dictionary). This does a nice job with the caveat that it I understand from a cryptographic standpoint the passwords it creates are not that strong. But useful enough for sites which aren’t my bank or primary email. For those I’m using stupidly long values generated from KeePassX. When I tried the Python function on my machine there was one drawback, it doesn’t work in Python 3. This is because the use of ‘map’ is discouraged in Python 3. But that’s alright because I can replace it with one of my favourite Python constructs – the list comprehension. Here is an updated version of invert’s function that works in Python 3. Use at your own risk.

def get_password():
    import random
    # Make a list of all of the words in our system dictionary
    f = open('/usr/share/dict/words')
    words = [x.strip() for x in f.readlines()]
    # Pick 2 random words from the list
    password = '-'.join(random.choice(words) for i in range(2)).capitalize()
    # Remove any apostrophes
    password = password.replace("'", "")
    # Add a random number to the end of our password
    password += str(random.randint(1, 9999))
    return password

Powered by WordPress