Entropy and Randomness
Why randomness matters and how to generate it securely
Skills taught: crypto.randomness
Why Weak Randomness Is Catastrophic
In 2012, researchers found thousands of HTTPS certificates sharing the same RSA private key because embedded devices had not collected enough entropy before generating keys at boot. Weak randomness has also broken Android Bitcoin wallets, Debian OpenSSL, and PlayStation 3 signing keys.
- Entropy
- A measure of unpredictability in a system. High entropy means outputs are hard to predict. Low entropy means they can be guessed.
- CSPRNG
- Cryptographically Secure Pseudo-Random Number Generator. Seeded from hardware entropy, safe for key generation, tokens, and nonces. Example: os.urandom() in Python.
- Nonce
- Number Used Once. A unique value that prevents replay attacks and nonce-reuse vulnerabilities. Must be generated from a CSPRNG.
Using Randomness Correctly in Python
import os
import secrets
import random # DANGEROUS for security
# --- CORRECT: OS CSPRNG ---
key = os.urandom(32) # 32 cryptographically random bytes (AES-256 key)
nonce = os.urandom(12) # 12-byte nonce for AES-GCM
iv = os.urandom(16) # 16-byte IV for AES-CBC
print("Key:", key.hex())
# --- CORRECT: secrets module (wraps os.urandom, easier API) ---
token = secrets.token_urlsafe(32) # URL-safe base64 token for password reset links
pin = secrets.token_hex(3) # 6 hex chars → 3-byte random PIN
api_key = secrets.token_bytes(32) # raw bytes
print("Reset token:", token) # e.g. jLDQvb3rFMBk9N2...
# --- WRONG: standard random module ---
# NEVER use for security: it is seeded with time and is predictable
bad_token = random.randint(100000, 999999) # attacker can guess this
bad_key = hex(random.getrandbits(256)) # completely insecure
Warning: Never use Python's random module for security. It is seeded with the current time and can be predicted by an attacker who knows roughly when your server started.
random vs secrets / os.urandom
- random module: Standard PRNG — seeded from system time
- secrets / os.urandom: OS CSPRNG — seeded from hardware entropy
Secure Token Patterns
import secrets
import hashlib
import hmac
# Password reset token (store in DB, email to user)
def generate_reset_token():
return secrets.token_urlsafe(32) # 256-bit URL-safe token
# API key (show once at creation, store hashed)
def generate_api_key():
raw = secrets.token_bytes(32)
hashed = hashlib.sha256(raw).hexdigest() # store this hash in DB
return raw.hex(), hashed # return raw to user, store hashed
# Constant-time comparison (prevents timing attacks)
def verify_token(user_token: str, stored_token: str) -> bool:
return hmac.compare_digest(user_token, stored_token)
# NEVER:
# if user_token == stored_token: # timing oracle!
Tip: Always use hmac.compare_digest() or secrets.compare_digest() when comparing tokens. Regular string comparison leaks timing information that lets attackers reconstruct the expected value byte by byte.
Frequently Asked Questions
What is a nonce vs an IV?
They serve the same purpose — a unique value per encryption — but naming differs by context. 'IV' (Initialisation Vector) is used with block ciphers (AES-CBC). 'Nonce' is used with stream ciphers and AEAD (AES-GCM, ChaCha20). Both must be generated with os.urandom().
How long should tokens be?
32 bytes (256 bits) is the standard for session tokens and password-reset links. 16 bytes (128 bits) is acceptable for short-lived tokens. Never less than 16 bytes.
What is a timing attack?
An attack where the attacker measures how long a comparison takes to infer information. A string comparison that returns early on mismatch reveals how many characters matched. Use hmac.compare_digest() to compare in fixed time.