Creating a random user password

suggest change

In order to create a random user password we can use the symbols provided in the string module. Specifically punctuation for punctuation symbols, ascii_letters for letters and digits for digits:

from string import punctuation, ascii_letters, digits

We can then combine all these symbols in a name named symbols:

symbols = ascii_letters + digits + punctuation

Remove either of these to create a pool of symbols with fewer elements.

After this, we can use random.SystemRandom to generate a password. For a 10 length password:

secure_random = random.SystemRandom()
password = "".join(secure_random.choice(symbols) for i in range(10))
print(password)  # '^@g;J?]M6e'

Note that other routines made immediately available by the random module — such as random.choice, random.randint, etc. — are unsuitable for cryptographic purposes.

Behind the curtains, these routines use the Mersenne Twister PRNG, which does not satisfy the requirements of a CSPRNG. Thus, in particular, you should not use any of them to generate passwords you plan to use. Always use an instance of SystemRandom as shown above.

Starting from Python 3.6, the secrets module is available, which exposes cryptographically safe functionality.

Quoting the official documentation, to generate “a ten-character alphanumeric password with at least one lowercase character, at least one uppercase character, and at least three digits,” you could:

import string
alphabet = string.ascii_letters + string.digits
while True:
    password = ''.join(choice(alphabet) for i in range(10))
    if (any(c.islower() for c in password)
            and any(c.isupper() for c in password)
            and sum(c.isdigit() for c in password) >= 3):
        break

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents