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 rangegetRandomValues 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?
Keep reading
Related articles from the SudoSecurity blog.
Angular 18: Deferred Views & Built-in Control Flow
The newest release of Angular – which is Angular 18 – is planned to be released on May 22nd, 2024. This is Google's super popular TypeScript based webapp framework that allows developers to create amazing web applications. The features, changes, and goodies of this release are deferrable views…
Angular 15: Simplifies Development Promises
Angular 15, a planned upgrade to Google’s TypeScript framework for web development, will stabilize standalone component APIs, simplifying application building, and offer a new way to compose UI logic, the company announced. Angular 15 is expected to arrive in November, said Minko Gechev, Google…
Angular 14 is Now Released
Angular 14, the latest version of the Google-developed, TypeScript-based web application framework, has arrived, featuring typed forms and a developer preview of standalone components. Standalone components simplify the development of Angular applications by reducing the need for NgModules.…
Node Runs TypeScript Now. Here's Exactly What It Strips, What It Refuses, and What It Costs
Node 24 and 26 run .ts files with no build step and no flags, by replacing types with whitespace. I ran eleven test cases, the TypeScript 7 compiler and tsx against both versions: enums, parameter properties and type imports without the type keyword all break, type errors run anyway, and...