CSPRNGs, Timing Attacks & Key Hygiene
Why Math.random breaks security tokens, how timing side-channels leak MAC bytes, and how key separation, zeroization, and dual-read rotation stay safe.
In this lesson (3 bite-sized sections)
Predictable randomness breaks perfect ciphers
Even AES-256 and Ed25519 collapse if the random bits feeding your keys, nonces, session tokens, or password-reset links can be predicted. Non-cryptographic PRNGs like JavaScript's Math.random() (xorshift128+) or Python's random (Mersenne Twister) are designed for simulation speed, not unpredictability. Observing just a handful of consecutive outputs lets an attacker reconstruct the entire internal state and predict every past and future token.
Always draw security-sensitive bytes from an OS-backed CSPRNG (Cryptographically Secure Pseudorandom Number Generator): /dev/urandom or getrandom() on Linux, crypto.randomBytes / crypto.getRandomValues in Node and browsers, or secrets.token_bytes in Python. On modern Linux kernels, getrandom() blocks briefly only during early boot until the entropy pool initializes and never depletes afterward, avoiding the legacy /dev/random stall bug. Watch out for timestamp-bearing IDs too: UUIDv1 and the timestamp prefix of UUIDv7 are predictable by design, so use them for database ordering, never as unguessable bearer tokens or password-reset links.
Interview nuance: Garbage-collected runtimes (Java, Go, Node, Python) make true memory zeroization tricky because immutable strings are copied during heap compaction. Keep raw keys inside explicit byte arrays (Buffer, Uint8Array, byte[]), overwrite them with zeros in a finally block, disable core dumps on containers, and never interpolate secrets into structured logs or exception messages.
| Hygiene boundary | Unsafe pattern | Safe production pattern | Failure if skipped |
|---|---|---|---|
| Random generation | Math.random(), random.randint(), UUIDv1 | crypto.getRandomValues, secrets.token_bytes, UUIDv4/v7 + CSPRNG | Attackers predict reset tokens, session IDs, or nonces |
| Secret comparison | mac === expectedMac or Buffer.equals() | crypto.timingSafeEqual() after length check / HMAC double-compare | Timing side-channel leaks MAC one byte at a time |
| Key reuse | One AES key used for both JWT HMAC and DB encryption | Distinct keys derived via HKDF with purpose-specific info strings | Cross-protocol oracle or blast-radius amplification |
| Memory handling | Immutable strings or logged env dumps holding raw keys | Byte buffers zeroized after use; secrets excluded from logs and dumps | Heap dumps, core files, or swap leak raw key material |
Constant-time comparisons and timing side-channels
Standard equality operators (===, memcmp) return false on the very first mismatching byte. If an API checks a webhook HMAC or API token with ===, a guess whose first byte matches executes slightly more CPU instructions before rejecting than a guess that fails on byte zero. Over a low-jitter local network (or averaged across thousands of remote requests), an attacker can measure nanosecond-to-microsecond differences and forge a 32-byte MAC in at most 32 * 256 = 8,192 guesses instead of 2^256.
Use crypto.timingSafeEqual (Node), hmac.compare_digest (Python), or subtle.ConstantTimeCompare (Go). Better yet, when input lengths could vary (like comparing user-supplied tokens of different lengths), compare HMAC(ephemeral_key, user_input) against HMAC(ephemeral_key, expected) in constant time so even the length comparison never leaks secret length.
Key separation, zeroization, and zero-downtime key rotation
Key separation enforces one key per cryptographic purpose: never share a key between encryption and signing, or between environments (staging and prod). If you derive subkeys from a root secret, bind every key to a unique HKDF label. In memory, hold plaintext DEKs in mutable byte buffers rather than immutable heap strings (which garbage collectors copy and leave behind), wipe them with zeros immediately after use, and disable core dumps in containers handling raw keys.
Finally, design dual-read key rotation from day one so rotating a key is a routine config change instead of an outage. Every ciphertext and signed token carries an explicit kid (key version ID) in its unencrypted header.
- 1. Stage v2Generate kid=v2 and distribute to all verifiers/decryptors
- 2. Dual-read activeServices accept both v1 and v2; writers still emit v1
- 3. Flip writersNew encryptions/signatures switch to kid=v2
- 4. Drain or re-wrapWait for v1 tokens to expire or re-wrap stored DEKs to v2
- 5. Retire v1Confirm zero v1 reads in telemetry, then disable and destroy v1
Separate safe key-hygiene practices from practices that cause breaches or outages.
Sort 4 more items to check
Recap: always source keys and tokens from OS CSPRNGs, compare MACs and tokens in constant time, enforce strict one-key-per-purpose separation with buffer zeroization, and embed kid versions so every rotation follows a calm dual-read lifecycle.
Sources: NIST SP 800-90A Rev. 1, DRBG · NIST SP 800-57 Part 1, Key Management · Web Crypto API, getRandomValues
Apply
Your turn
The task this lesson builds to.
Architect the token-generation, validation, and quarterly key-rotation workflow for an API-key and webhook-signing platform serving 50,000 developer accounts with zero downtime.
Think about
- How many bits of CSPRNG entropy should API keys and webhook secrets carry?
- How do you validate variable-length user-supplied tokens without leaking timing or length?
- What exact state transitions prevent outages during quarterly HMAC key rotation?
Draft your design answer here Save your draft, compare against the model answer, and track progress.
Practice
Make it stick
A second problem on the same idea, so it survives past today.
Audit a password-reset microservice where engineers used Math.random().toString(36).slice(2) for 10-character reset codes, checked codes with code === dbRow.code, and shared the database encryption key as the JWT signing key. Rank the three vulnerabilities by exploitability and design the clean remediation plan.
Think about
- How can an attacker predict another user's reset link after requesting a few reset links for their own account?
- Why does sharing one key between DB AES-GCM and JWT HMAC expand blast radius?
- How do you roll out new reset tokens and separate keys without invalidating every active user session at once?
Draft your design answer here Save your draft, compare against the model answer, and track progress.