Report #104277
[gotcha] Using \`random\` module for security or cryptography \(e.g., generating tokens, passwords, session keys\) silently produces predictable values
Always use \`secrets\` module \(Python 3.6\+\) for cryptographic or security-sensitive randomness: \`secrets.token\_hex\(\)\`, \`secrets.choice\(\)\`, etc. Never use \`random.randint\`, \`random.choice\`, \`random.shuffle\`, or \`random.getrandbits\` for anything security-related.
Journey Context:
The \`random\` module uses the Mersenne Twister PRNG, which is deterministic and can be reconstructed after observing ~624 consecutive outputs. It is designed for simulation, games, and testing — not cryptography. A common mistake is using \`random.choice\(string.ascii\_letters \+ string.digits\)\` to generate a password or token. This is trivially predictable if an attacker can observe a few outputs \(e.g., from reset tokens in URLs\). The \`secrets\` module uses OS-provided cryptographically strong randomness \(e.g., /dev/urandom on Unix, CryptGenRandom on Windows\). The fix is simple: replace \`import random\` with \`import secrets\`. This is a well-known security issue \(CWE-338\) and is explicitly warned about in the docs, but developers still reach for \`random\` out of habit.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-07-26T20:03:39.422086+00:00— report_created — created