← Back to section · Tutorials & Labs

Randomness Discipline: Why Keys Must Come from secrets, Never from random

The random module's Mersenne Twister is a predictable pseudorandom generator; keys, tokens and verification codes produced with it are effectively public. This tutorial explains how secrets, os.urandom and SystemRandom divide the work, with correct patterns for tokens, codes and generated passwords.

Published 22 November 2026 · 6 min read · PQ Frontier

Randomness Discipline: Why Keys Must Come from secrets, Never from random
AI-generated site artwork
Video explainer · Python cryptography: experiments and prototypes

What this tutorial aims to do

Randomness is the most underestimated part of cryptography. You can pick the right algorithm and the right library, but if your randomness is predictable, your keys might as well be handed to the attacker. This tutorial establishes one clear rule: in Python, anything security-related — keys, session tokens, password-reset links, SMS verification codes, lotteries and shuffles — must draw from a cryptographically secure source, namely the secrets module and os.urandom; the random module is reserved for simulations, sampling and games, where losing costs nothing. We first explain why the two differ, then give the correct pattern for each common scenario, and finish with a checklist of the most frequent mistakes.

Why random is predictable

The core of the random module is the Mersenne Twister, designed for good statistical properties, a long period and speed — everything except unpredictability. In fact, after observing enough outputs (the Twister’s internal state is 624 32-bit words), an attacker can reconstruct the entire state and compute every subsequent output. This is not theoretical fussiness: a long list of predictable-token vulnerabilities traces back to developers casually using the built-in general-purpose generator for session identifiers or reset links; an attacker registers a few accounts, collects samples, and derives the next victim’s token. A second, quieter problem is seeding: programs seeded with timestamps or process IDs have a seed space small enough to brute-force. The conclusion is one sentence: the output of random is a mathematically deterministic sequence that can be continued by anyone who knows the algorithm and part of the output — the exact opposite of what cryptography needs.

The correct doors: secrets and os.urandom

For this purpose the standard library provides the dedicated secrets module (since Python 3.6), which draws on the operating system’s cryptographically secure random source — on Linux, the getrandom system call backed by the kernel entropy pool — producing bytes that are neither predictable nor reproducible. The three most useful functions are secrets.token_bytes(n) for raw random bytes, secrets.token_hex(n) for a hexadecimal string, and secrets.token_urlsafe(n) for a URL-safe string suitable for links. Note that n counts bytes, not characters: token_urlsafe(32) turns 32 bytes of entropy into a string of about 43 characters. When you need raw bytes to feed a crypto library directly, the lower-level os.urandom(n) works just as well; both share the same source, and the difference is only that secrets wraps it in application-shaped helpers.

import secrets

# Session token: 32 bytes of entropy, URL-safe, ready for a link or cookie
session_token = secrets.token_urlsafe(32)

# Password-reset token: also 32 bytes; do not truncate it
reset_token = secrets.token_hex(32)

# Raw bytes for a symmetric key, handed straight to the crypto library
raw_key_material = secrets.token_bytes(32)
print(session_token, reset_token, len(raw_key_material))

Verification codes, passwords and shuffles

Beyond tokens, three more everyday scenarios need the secure source. First, numeric verification codes: use secrets.randbelow(1_000_000) to draw a uniform number from 0 to 999999 and format it as a six-digit string. Do not squeeze a code out of a larger random number with the modulo operator — that introduces distribution bias; randbelow uses rejection sampling internally to stay uniform. Second, temporary passwords and random strings: pick character by character with secrets.choice from your alphabet, which gives every character equal probability. Third, shuffles and draws: random.shuffle runs on the predictable Twister, so draw results can be computed in advance; the correct tool is the shuffle method of a secrets.SystemRandom instance, which draws from the operating system’s secure source.

import secrets

# Six-digit code: randbelow is uniform; zero-pad when formatting
code = f"{secrets.randbelow(1_000_000):06d}"

# Temporary password: equal-probability choice per character
alphabet = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789"
temp_password = "".join(secrets.choice(alphabet) for _ in range(16))

# Lottery shuffle: SystemRandom.shuffle uses the OS secure source
names = ["Alice", "Bob", "Carol", "Dave"]
secrets.SystemRandom().shuffle(names)
print(code, temp_password, names)

Where entropy comes from: why virtual machines and containers need extra care

The bytes behind secrets ultimately come from the entropy pool maintained by the operating-system kernel: as the system runs, the kernel harvests hard-to-predict events such as hardware noise and device-interrupt timing, feeds them into a cryptographically secure generator, and hands the result to applications through a system call. Two links in this chain have caused repeated real-world incidents. The first is the moment right after boot: generating long-term keys before the pool has accumulated enough noise once left large fleets of embedded devices with predictable keys. The modern Linux getrandom system call blocks until the pool is ready, and secrets goes through exactly that path — so never bypass it by reading a raw device early in boot “for speed”. The second is virtual-machine snapshots and clones: when a VM is cloned into many instances, or restored repeatedly from one snapshot, a copied generator state can make the instances produce identical or predictable random sequences; pre-generating keys into cloud images or container templates is the same accident in another costume. The defensive rule is singular: keys are generated on the machine itself, at first real run, never baked into an image, template or installer. These two links explain why “we used secrets” is not the whole story — beyond choosing the right interface, generation timing and environment are part of randomness discipline too.

A checklist of common mistakes

Finally, pin the four most common practical mistakes to the wall. Mistake one: building tokens or keys out of random.random() — the most serious and most frequent error; any secret it produces is not a secret. Mistake two: seeding a generator with a timestamp, user ID or process ID — the seed space is so small that an attacker can enumerate it second by second. Mistake three: inventing your own randomness scheme, such as XOR-ing or multiplying several ordinary random numbers in the hope of making them “more random” — XOR-ing predictable sequences yields predictable sequences; entropy never appears from nothing. Mistake four: comparing tokens with the ordinary equality operator where a constant-time comparison is required — string comparison short-circuits byte by byte and leaves a timing side channel; verify tokens and codes with secrets.compare_digest or hmac.compare_digest instead. The general principle: the quality of randomness depends not on how much code you write but on where the entropy comes from — with the right source, a single line of secrets.token_urlsafe(32) is enough; with the wrong one, no amount of post-processing is anything but self-deception.

Tags: PythonsecretsRandomnessSecure Coding