Programming Python

Single line secure password generator in Python 3 using SystemRandom

May 14, 2019

Generating secure passwords for applications like database servers is a must. However, generating passwords online can be slightly disconcerting, especially if the password is going into production. Thankfully, there is a one-line Python command you can use to generate a password of any length.

Use this command:

import random;print(''.join([random.SystemRandom().choice(list('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>[email protected]')) for x in range(20)]))

It may look ugly, but this command will generate a random password from all the printable ASCII characters. In its current state, it will generate 20 random characters. You can adjust this value up or down based on your needs by changing the number in the range(x) function.

But how does it work?

This command is actually two commands squished into one line. The first command, separated by a semicolon, imports the random module.

The next command is a little more complicated. It makes more sense if we break it up like this:

random_str = ""
sys_rand = random.SystemRandom()
for x in range(20):
 random_str += sys_rand.choice(list('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>[email protected]'))

print(random_str)

At the top of the code we define our random_str which is our password, and sys_rand which is a modified version of the standard random class. The difference here is that using the SystemRandom function will make the random choice (and thus the characters), cryptographically secure.

Then, in the for loop, we add a random character from a list of all the ASCII characters that can be printed to random_str.

Finally, we print the result of our function.