How to Generate Secure Random Number in Python
Use the
secrets module in Python to generate secure random numbers. For example, secrets.randbelow(n) returns a secure random integer less than n. This module is designed for cryptographic use and is safer than random.Syntax
The secrets module provides functions to generate secure random numbers suitable for security-sensitive applications.
secrets.randbelow(n): Returns a secure random integer in the range0ton-1.secrets.randbits(k): Returns an integer withkrandom bits.secrets.choice(sequence): Returns a secure random element from a non-empty sequence.
python
import secrets # Generate a secure random integer less than 100 num = secrets.randbelow(100) # Generate a secure random number with 8 random bits bits = secrets.randbits(8) # Choose a secure random element from a list element = secrets.choice(['apple', 'banana', 'cherry'])
Example
This example shows how to generate a secure random number between 0 and 99 and print it. It uses secrets.randbelow() which is safe for cryptographic use.
python
import secrets secure_number = secrets.randbelow(100) print(f"Secure random number (0-99): {secure_number}")
Output
Secure random number (0-99): 42
Common Pitfalls
Many beginners use the random module for random numbers, but it is not secure for sensitive data like passwords or tokens. The random module uses a predictable algorithm, which can be guessed by attackers.
Always use the secrets module for security-related random numbers.
python
import random import secrets # Insecure way (do NOT use for security) print(f"Insecure random number: {random.randint(0, 99)}") # Secure way print(f"Secure random number: {secrets.randbelow(100)}")
Output
Insecure random number: 17
Secure random number: 83
Quick Reference
Use this quick reference to pick the right secrets function:
| Function | Description | Example |
|---|---|---|
| secrets.randbelow(n) | Random int in [0, n-1] | secrets.randbelow(10) |
| secrets.randbits(k) | Random int with k bits | secrets.randbits(8) |
| secrets.choice(seq) | Random element from sequence | secrets.choice(['a', 'b', 'c']) |
Key Takeaways
Use the secrets module for generating secure random numbers in Python.
Avoid the random module for security-sensitive tasks as it is predictable.
secrets.randbelow(n) generates a secure random integer less than n.
secrets.randbits(k) generates a secure random integer with k bits.
secrets.choice(sequence) picks a secure random element from a sequence.