Milind Soorya
milind's Blog

milind's Blog

Generate cryptographically safe passwords with Python in 4 lines of code

Generate cryptographically safe passwords with Python in 4 lines of code

Milind Soorya's photo
Milind Soorya

Published on Sep 14, 2021

1 min read

Subscribe to my newsletter and never miss my upcoming articles


The secrets module is used for generating cryptographically strong random numbers suitable for managing data such as passwords, account authentication, security tokens, and related secrets.

In particular, secrets should be used in preference to the default pseudo-random number generator in the random module, which is designed for modelling and simulation, not security or cryptography.

read more from the docs

Using secrets.token_hex

This is the easiest method to generate a random text of string, in hexadecimal.

>>> token_hex(16)  

In a single line, you get a good enough password. But, yeah there is a but, if you want real hardcore, unbreakable password this is how to do it.

Using secrets.choice

secrets.choice return a randomly-chosen element from a non-empty sequence. we just have to provide enough variation as the input string.

import string
from secrets import choice

characters = string.ascii_letters + string.punctuation + string.digits
# abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~0123456789

password = "".join(choice(characters) for x in range(0, 32))
# ONFe[)P>5^(jnJ\7ZgYw,|671BZ&!8R"


There you go a strong 32 character password 🎉🎉

Follow me on Twitter

If you like this article I am pretty sure you would like the following ones too 😉

Share this