Courses

Weak Random Token Generation
OSWE · Chapter 21

Weak Random Token Generation

Weak random token generation undermines password reset links, session IDs, API keys, and CSRF tokens alike — if the token generator is predictable (e.g. seeded from time, or using a non-cryptographic PRNG), an attacker can guess or reconstruct valid tokens without ever intercepting one.

Key concepts

  • Never use a general-purpose PRNG (like `Math.random()` in JavaScript, or `rand()` in many languages) for anything security-sensitive — these are not cryptographically secure and are often predictable given a few samples.
  • Always use a CSPRNG (`crypto.randomBytes` in Node.js, `secrets` module in Python, `SecureRandom` in Java) with at least 128 bits of entropy for tokens.
  • Timestamp- or counter-seeded tokens are especially dangerous because the seed space is small enough to brute-force offline once the algorithm is known.
  • Token length is not the same as entropy — a long token built from a weak/predictable generator is still weak, no matter how many characters it has.

Example

// Vulnerable — Math.random() is not cryptographically secure
const token = Math.random().toString(36).slice(2);

// Safe — CSPRNG with sufficient entropy
const token = require("crypto").randomBytes(32).toString("hex");

Try it yourself

Generate 5 password-reset-style tokens using `Math.random()` in a Node.js REPL and look for any obvious pattern (e.g. shared prefixes tied to system time) before comparing against `crypto.randomBytes`.

@ Daniel Burlacu