How to Use Secrets Module in Python for Secure Random Numbers
Use the
secrets module in Python to generate cryptographically strong random numbers and tokens. Import it with import secrets and use functions like secrets.token_hex() or secrets.randbelow() for secure random values.Syntax
The secrets module provides functions to generate secure random numbers and tokens. Common functions include:
secrets.token_bytes(n): Returnsnrandom bytes.secrets.token_hex(n): Returns a random text string, in hexadecimal, of length2*n.secrets.token_urlsafe(n): Returns a random URL-safe text string.secrets.randbelow(n): Returns a random integer in the range[0, n).secrets.choice(sequence): Returns a random element from a non-empty sequence.
python
import secrets # Generate 16 random bytes random_bytes = secrets.token_bytes(16) # Generate a 32-character hex token hex_token = secrets.token_hex(16) # Generate a URL-safe token url_token = secrets.token_urlsafe(16) # Generate a random integer below 100 rand_int = secrets.randbelow(100) # Choose a random element from a list choice = secrets.choice(['apple', 'banana', 'cherry'])
Example
This example shows how to generate a secure random password token and a random number below 50 using the secrets module.
python
import secrets # Generate a secure 24-character hex token password_token = secrets.token_hex(12) print(f"Secure password token: {password_token}") # Generate a random number between 0 and 49 random_number = secrets.randbelow(50) print(f"Random number below 50: {random_number}")
Output
Secure password token: 9f8b7c4d2a1e3f5b6c7d8e9f
Random number below 50: 23
Common Pitfalls
One common mistake is using the random module for security-sensitive tasks, which is not safe because it is predictable. Another pitfall is not specifying the correct number of bytes or characters needed for tokens, leading to weak security.
Always use secrets for generating passwords, tokens, or keys that require strong randomness.
python
import random # Unsafe: predictable random number print(random.randint(0, 100)) import secrets # Safe: cryptographically secure random number print(secrets.randbelow(101))
Output
42
17
Quick Reference
| Function | Description |
|---|---|
| secrets.token_bytes(n) | Generate n random bytes |
| secrets.token_hex(n) | Generate a hex string of length 2*n |
| secrets.token_urlsafe(n) | Generate a URL-safe string |
| secrets.randbelow(n) | Generate a random int in [0, n) |
| secrets.choice(seq) | Choose a random element from a sequence |
Key Takeaways
Use the secrets module for generating secure random numbers and tokens.
Avoid the random module for security-sensitive randomness.
Functions like token_hex and randbelow provide easy ways to get secure values.
Always specify the correct size for tokens to ensure strong security.
secrets.choice helps pick random elements securely from sequences.