Skip to content

Lesson 13 of 14 · 20m

Randomness, Tokens, and Why Math.random() Is Not Security

CSPRNGs, timing-safe comparison, hashing tokens vs stretching passwords, and what a JWT signature actually guarantees.

Math.random() is not random. It's a fast non-cryptographic PRNG — xorshift128+ in V8 — and its state is recoverable from a handful of observed outputs. Researchers have demonstrated predicting it from double outputs collected in the wild. If you ever generated a password reset token, a session ID, a UUID, or a "secret" with Math.random(), you generated a guessable string.

The CSPRNG you already have

// global crypto: every browser; Node 19+ unflagged (17.6/16.15 needed --experimental-global-webcrypto; before that, node:crypto.webcrypto)
crypto.getRandomValues(new Uint8Array(32));   // 32 bytes from the OS CSPRNG
crypto.randomUUID();                           // RFC 4122 v4 UUID

// node:crypto — the same primitives, Node-style
import { randomBytes, randomInt, randomUUID } from 'node:crypto';
randomBytes(32).toString('base64url');         // token: 256 bits of entropy
randomInt(0, 100);                             // unbiased integer in range

getRandomValues and randomBytes both draw from the operating system's CSPRNG — the same entropy source as crypto.randomBytes on every platform. Two boundaries worth knowing: getRandomValues throws QuotaExceededError on typed arrays over 65,536 bytes — WebCrypto was built for keys, not bulk output, so loop it or use randomBytes (uncapped) for a big buffer — and crypto.randomInt is Node-only; browsers get getRandomValues and randomUUID, nothing else. crypto.subtle is the other half of the same global: async, for hashing and key work, not quick token bytes. There is no acceptable reason for Math.random() in a security path. It's fine for jitter, animations, sampling, and load distribution — it was designed for exactly that — and nothing else.

Tokens: size, encoding, storage

A credential token wants at least 128 bits of entropy — 16 bytes minimum, 32 bytes (256 bits) standard. Encode it base64url (URL-safe, no +///=) or hex. randomBytes(32).toString('base64url') gives you a 43-character token with full entropy.

Store the hash, not the token: sha256(token) in the database means a leaked table doesn't leak usable credentials. High-entropy tokens don't need salting or stretching — they're unguessable to begin with, which is exactly the difference between an API key and a password.

randomInt(min, max) deserves a note of its own, because the naive alternative — Math.floor(Math.random() * n) — is both biased and insecure. randomInt uses rejection sampling internally to give you an unbiased distribution over the range. The same trick matters for crypto.randomUUID() versus hand-rolled Math.random-based "UUIDs": a v4 UUID is 122 bits of randomness with format bits set, and any shortcut that skips the format bits or uses a weaker source produces strings that look like UUIDs but collide or predict. randomUUID() is the same entropy in UUID clothing — fine as an identifier, equally fine as a token.

Comparing secrets without leaking them

tokenA === tokenB short-circuits on the first differing byte — an oracle for timing attacks on token verification. crypto.timingSafeEqual compares in constant time, and it requires equal-length Buffers:

import { timingSafeEqual } from 'node:crypto';
const a = Buffer.from(expectedHash);
const b = Buffer.from(providedHash);
const ok = a.length === b.length && timingSafeEqual(a, b);

Hash both sides first (sha256) so lengths always match — you compare the digests, not the tokens. In the browser, SubtleCrypto exposes no constant-time compare; that's one of many reasons secrets don't get verified client-side.

Passwords are not tokens

sha256(password) is brute-forceable at billions of guesses per second because humans pick bad passwords. Passwords need a memory-hard or iterated KDF: crypto.scrypt in Node (with a random salt), or argon2/bcrypt via a package. The rule: hash tokens (fast), stretch passwords (slow). Inverting the two — storing sha256(password) or scrypt(apiToken) — gets both wrong.

Signed is not encrypted

A JWT is Base64url-encoded JSON plus a signature. The signature proves integrity; it does not hide the payload — atob() in a browser console reads it instantly. Putting secrets or PII in JWT claims ships them to anyone holding the token, which is by design everyone holding the token. Claims carry identity and expiry, nothing sensitive — and "encrypted JWT" is a different spec (JWE), not a default.

Try this

Generate the same "token" twice: once via Math.random().toString(36) and once via crypto.randomUUID() / randomBytes. Look at the entropy difference. Then write a verifyToken(provided, storedHash) that compares sha256(provided) to storedHash with timingSafeEqual — and explain why === on the hex strings would have been the bug.

Was this lesson helpful?

Sign in to rate

Keep reading

Related articles from the SudoSecurity blog.