How to Generate Random Cryptographically Secure Passwords in Python

Sometimes it is necessary to generate cryptographically secure strings/passwords randomly in Python. You can do this using the secrets package, which provides the most secure source of randomness that your operating system provides.

 

Generate Secure Random String

Let's begin by generating a secure random string 10 characters long, using upper and lower case letters from the Python string package.

 

import secrets
import string

secure_string = ''.join((secrets.choice(string.ascii_letters) for i in range(10)))

print(secure_string)
aMekYGptmc

 

Generate Secure Random Password

To create a secure password we will need to use combination of letters, digits and punctuation characters like this:

 

chars = string.ascii_letters + string.digits + string.punctuation

password = ''.join((secrets.choice(chars) for i in range(10)))

print(password)
-c:?$s("U7