Python Secrets Module
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. It was introduced in Python 3.6.
Importing the Module
import secrets
Generating Random Numbers
The secrets module provides access to the most secure source of randomness that your operating system provides.
secrets.randbelow()
Return a random int in the range [0, n).
import secrets
# Generate a secure random integer between 0 and 9
print(secrets.randbelow(10))
secrets.choice()
Return a randomly-chosen element from a non-empty sequence.
import secrets
items = ['apple', 'banana', 'cherry']
print(secrets.choice(items))
Generating Tokens
The secrets module provides functions to generate secure tokens, suitable for password resets, hard-to-guess URLs, etc.
secrets.token_bytes()
Return a random byte string containing nbytes number of bytes.
import secrets
print(secrets.token_bytes(16))
secrets.token_hex()
Return a random text string, in hexadecimal. The string has nbytes random bytes, each byte converted to two hex digits.
import secrets
print(secrets.token_hex(16))
# Output example: 8f2d3c4b5a6e7f8g9h0i1j2k3l4m5n6o
secrets.token_urlsafe()
Return a random URL-safe text string, containing nbytes random bytes. The text is Base64 encoded, so on average each byte results in approximately 1.3 characters.
import secrets
reset_link = 'https://example.com/reset=' + secrets.token_urlsafe(16)
print(reset_link)
Comparing Strings
secrets.compare_digest()
Return True if strings a and b are equal, otherwise False, in such a way as to reduce the risk of timing attacks.
import secrets
valid_token = "my_secret_token"
user_token = "user_provided_token"
if secrets.compare_digest(valid_token, user_token):
print("Access granted")
else:
print("Access denied")