Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Generate Secure Random Numbers for Managing Secrets using Python
To generate secure random numbers cryptographically we can use the secrets module in Python. This module is helpful to create secure passwords, account authentication tokens, security tokens, and other cryptographic secrets.
The secrets module provides access to the most secure source of randomness that your operating system provides, making it suitable for managing secrets where security is essential.
Importing the Secrets Module
To use the classes and functions of the secrets module, we need to import it into our code ?
import secrets
Random Number Generation Methods
The secrets module provides several methods for generating secure random numbers ?
secrets.choice(sequence)
This method chooses a random element from a non-empty sequence ?
import secrets
characters = ['a', 'b', 'c', '1', '2', '3', '@', '#', '$']
random_char = secrets.choice(characters)
print("Random character:", random_char)
Random character: #
secrets.randbelow(n)
This method returns a random integer from 0 to n (exclusive) ?
import secrets
# Generate random number between 0 and 99
random_num = secrets.randbelow(100)
print("Random number (0-99):", random_num)
# Generate random number between 0 and 9
dice_roll = secrets.randbelow(10)
print("Random digit:", dice_roll)
Random number (0-99): 47 Random digit: 3
secrets.randbits(k)
This method returns an integer with k random bits ?
import secrets
# Generate 8-bit random number (0-255)
random_8bit = secrets.randbits(8)
print("8-bit random number:", random_8bit)
# Generate 16-bit random number
random_16bit = secrets.randbits(16)
print("16-bit random number:", random_16bit)
8-bit random number: 203 16-bit random number: 41847
Generating Secure Tokens
The secrets module can generate secure tokens useful for password resets, session tokens, and secure URLs ?
secrets.token_bytes([nbytes=None])
Returns a random byte string containing nbytes number of bytes ?
import secrets
# Generate 16 random bytes
token_bytes = secrets.token_bytes(16)
print("Token bytes:", token_bytes)
print("Length:", len(token_bytes))
Token bytes: b'\x8f\x9a\x12\x34\x56\x78\x9a\xbc\xde\xf0\x11\x22\x33\x44\x55\x66' Length: 16
secrets.token_hex([nbytes=None])
Returns a random text string in hexadecimal format. Each byte results in two hex digits ?
import secrets
# Generate hex token with 8 bytes (16 hex characters)
hex_token = secrets.token_hex(8)
print("Hex token:", hex_token)
print("Length:", len(hex_token))
# Generate shorter hex token
short_hex = secrets.token_hex(4)
print("Short hex token:", short_hex)
Hex token: 3f7a8b9c2d1e4f56 Length: 16 Short hex token: a1b2c3d4
secrets.token_urlsafe([nbytes=None])
Returns a random URL-safe text string using Base64 encoding. Each byte results in approximately 1.3 characters ?
import secrets
# Generate URL-safe token
urlsafe_token = secrets.token_urlsafe(16)
print("URL-safe token:", urlsafe_token)
# Generate shorter URL-safe token
short_urlsafe = secrets.token_urlsafe(8)
print("Short URL-safe token:", short_urlsafe)
URL-safe token: mK3jL9xP7qR8sT2vW4nY1z Short URL-safe token: aB3dE6gH9j
Practical Example: Secure Password Generator
Here's a complete example that generates a secure password using multiple character sets ?
import secrets
import string
def generate_secure_password(length=12):
# Define character sets
characters = string.ascii_letters + string.digits + "!@#$%^&*"
# Generate secure password
password = ''.join(secrets.choice(characters) for _ in range(length))
return password
# Generate passwords of different lengths
password_12 = generate_secure_password(12)
password_16 = generate_secure_password(16)
print("12-character password:", password_12)
print("16-character password:", password_16)
# Generate secure tokens for different purposes
session_token = secrets.token_urlsafe(32)
api_key = secrets.token_hex(16)
print("Session token:", session_token)
print("API key:", api_key)
12-character password: K7@dE9mP!w3X 16-character password: R5$nT8@qY2#vB9zL Session token: mK3jL9xP7qR8sT2vW4nY1z6bC5dF8eG9hJ0kL3mN6oP API key: f3e68646dcf1082e1038a2b4
Security Comparison
| Module | Security Level | Best For |
|---|---|---|
random |
Low (Pseudorandom) | Simulations, games |
secrets |
High (Cryptographic) | Passwords, tokens, security |
Conclusion
The secrets module provides cryptographically secure random number generation essential for security applications. Always use secrets instead of random when generating passwords, tokens, or any security-related data.
