Select Secure Randomness with secrets
Core idea
The secrets module draws randomness from the operating system for security-sensitive tasks. Use token_hex(nbytes) or token_urlsafe(nbytes) with an explicitly chosen byte count appropriate to the application. Use randbelow(n) for a uniform integer from zero through n-1.
import secretstoken = secrets.token_hex(32)print(len(token))Each byte produces two hexadecimal characters; only the length is printed.
Check secure choice bounds
import secretsprint(all(0 <= secrets.randbelow(10) < 10 for _ in range(10)))The invariant is stable even when the actual values vary.
Compare synthetic tokens
import secretsprint(secrets.compare_digest("demo-a", "demo-a"))print(secrets.compare_digest("demo-a", "demo-b"))compare_digest is designed to reduce timing leakage from content comparisons of compatible types; these are synthetic values only.
Common mistake
Never log real tokens or use seeded random for them. Generating a token alone does not provide expiration, safe storage or a complete authentication system.
Practice
Generate a 16-byte and a 32-byte demonstration token, check only the hexadecimal lengths, and explain why a fixed expected token is not a suitable test.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Secure randomness
Check your understanding of secrets.
What is printed?
import secretsprint(len(secrets.token_hex(16)))What is printed?
import secretsprint(0 <= secrets.randbelow(5) < 5)What is printed?
import secretsprint(secrets.compare_digest("test-a", "test-b"))What is appropriate to log about a real token?