Secure randomness

Generate tokens, ids and codes that an attacker cannot predict: use the operating system's CSPRNG in every language, size tokens from the attack, encode them without losing entropy, and avoid modulo bias when picking from an alphabet.

● EasyFREEBy ·Design problem·14 min read·Beginner → Intermediate
CSPRNGrandomnessMath.randomsecrets modulecrypto/randmodulo biastoken entropy

01Understand the problem

✓What you will learn
  • Tell a CSPRNG from a statistical PRNG and know which API is which in each language
  • Size tokens in bits of entropy from the attack, not from looks
  • Pick characters from an alphabet without modulo bias
  • Know which ids are not secrets (UUIDv1, UUIDv7, ULID, sequential ids)
◎Interview radar

What they probe: why Math.random is not acceptable for reset tokens, how many bits a session id needs, what an 8-character code really gives you, and why randomByte % 10 is subtly wrong. Where candidates slip: Python random or Go math/rand for tokens, UUIDs of any version treated as secrets, short codes with no attempt limit, seeding a generator with the time.

A statistical PRNG (V8's xorshift128+ behind Math.random, Python's Mersenne Twister in random, Go's math/rand) produces numbers that look uniform but whose internal state can be recovered from outputs: 624 consecutive 32-bit outputs give you the whole Mersenne Twister state, and published tools predict Math.random from a handful of values. A CSPRNG (cryptographically secure pseudo-random number generator) is seeded by the operating system (getrandom, BCryptGenRandom) and designed so that outputs reveal nothing about past or future outputs.

LanguageUse for secretsNever for secrets
Node.jscrypto.randomBytes, crypto.randomInt, crypto.randomUUID, crypto.getRandomValuesMath.random
Browsercrypto.getRandomValues, crypto.randomUUIDMath.random
Pythonsecrets.token_bytes, secrets.token_urlsafe, secrets.choice, os.urandomrandom.random, random.choice, random.seed(time.time())
Gocrypto/rand.Read, crypto/rand.Int, crypto/rand.Text (Go 1.24)math/rand, math/rand/v2 top-level functions

02Interfaces first

The contractts
export interface TokenFactory {
  /** URL-safe token with at least bits of entropy. bits must be a multiple of 8, minimum 128. */
  token(bits?: number): string;
  /** Uniformly random string over alphabet, for human-typed codes. */
  code(alphabet: string, length: number): string;
}

/** Inject randomness so tests are deterministic; production always passes crypto.randomBytes. */
export type RandomSource = (n: number) => Buffer;
UseEntropyWhy
Session id, API key, reset token128 bits minimum, 256 commonOnline guessing at 10^9 per second still needs about 10^21 years on average for 128 bits
Email verification link128 bitsSame as a reset token: it grants something
6-digit code typed by a humanAbout 20 bitsOnly safe with attempt limits and a short lifetime
Public object id (not a secret)Enough to avoid collisionsBirthday bound: with n ids of b bits, collision chance is roughly n squared over 2 to the b+1

03Tokens, unbiased codes and the other languages

Token factoryts
import { randomBytes } from "node:crypto";

export function makeTokenFactory(rand: RandomSource = randomBytes): TokenFactory {
  return {
    token(bits = 256) {
      if (!Number.isInteger(bits) || bits < 128 || bits % 8 !== 0) throw new RangeError("bits must be a multiple of 8 and at least 128");
      return rand(bits / 8).toString("base64url");        // 32 bytes -> 43 characters, 6 bits each, no padding
    },

    code(alphabet, length) {
      const n = alphabet.length;
      if (n < 2 || n > 256 || new Set(alphabet).size !== n) throw new RangeError("alphabet needs 2..256 distinct characters");
      if (!Number.isInteger(length) || length < 1 || length > 256) throw new RangeError("length out of range");
      const limit = 256 - (256 % n);                      // largest multiple of n that fits in a byte
      let out = "";
      while (out.length < length) {
        for (const b of rand(length * 2)) {
          if (b >= limit) continue;                       // rejection sampling: drop bytes that would bias the result
          out += alphabet[b % n];
          if (out.length === length) break;
        }
      }
      return out;
    },
  };
}

// Crockford-style alphabet without 0/O and 1/I/L for codes people read aloud: 31 symbols, about 4.95 bits each.
export const READABLE = "23456789ABCDEFGHJKMNPQRSTUVWXYZ";

Why the rejection step: with a 10-symbol alphabet, bytes 0 to 255 map to digits by b % 10. 256 is not a multiple of 10, so digits 0 to 5 get 26 bytes each and 6 to 9 get 25. That is a small bias per character, but it compounds across a code and it is entirely avoidable. Discarding bytes 250 to 255 makes every digit exactly 25 in 250. Node's crypto.randomInt(min, max) and Python's secrets.randbelow do this for you.

Pythonpython
import secrets, string

reset_token = secrets.token_urlsafe(32)          # 32 random bytes, base64url, about 43 characters
api_key = "cy_live_" + secrets.token_hex(32)     # 64 hex characters, 256 bits
otp = "".join(secrets.choice(string.digits) for _ in range(6))   # choice is unbiased
pin = f"{secrets.randbelow(10**6):06d}"          # same distribution, one call
Gogo
package tokens

import (
	"crypto/rand"
	"encoding/base64"
	"math/big"
)

// Token returns n random bytes encoded as unpadded base64url.
func Token(n int) string {
	b := make([]byte, n)
	if _, err := rand.Read(b); err != nil { // documented never to fail on supported platforms since Go 1.24
		panic(err)
	}
	return base64.RawURLEncoding.EncodeToString(b)
}

// Digits returns a uniformly random decimal code of the given length.
func Digits(length int) (string, error) {
	out := make([]byte, length)
	ten := big.NewInt(10)
	for i := range out {
		d, err := rand.Int(rand.Reader, ten) // rand.Int rejects biased values internally
		if err != nil {
			return "", err
		}
		out[i] = byte('0' + d.Int64())
	}
	return string(out), nil
}
▭On the whiteboard · Design choices4 points
01
source
OS CSPRNG only, behind an injectable function for tests
02
size
256 bits for long-lived secrets, never below 128
03
encoding
base64url or hex; the encoding does not add entropy, only bytes do
04
codes
rejection sampling or the library helper; short codes need attempt limits and expiry

04Traps and tests

TrapWhy it failsFix
Math.random().toString(36)Predictable state and only about 52 bits per callrandomBytes(32).toString('base64url')
UUID as a secretUUIDv1 and v7 contain a timestamp; v4 has 122 bits but some libraries used weak generatorsUse a token API for secrets; UUIDs for identifiers
Seeding with the timerandom.seed(time.time()) leaves a few million candidate seedsNever seed a CSPRNG yourself
Hashing a weak valuesha256(userId + Date.now()) looks random but has tiny entropyEntropy comes only from the random bytes
Truncating a tokenSlicing 43 characters to 8 leaves 48 bitsSize by bits; if it must be short, add rate limits and expiry
Forked or cloned VMsTwo VM clones resume with the same userspace generator stateUse the kernel generator (getrandom); modern kernels reseed on VM generation ID changes
!Short codes need guard rails

A 6-digit code has a million values. Without limits, an attacker trying 100 codes per second finds it in under three hours on average. Pair short codes with attempt limits per code and per account, expiry in minutes, and single use.

vitestts
import { describe, it, expect } from "vitest";

describe("token factory", () => {
  const real = makeTokenFactory();

  it("produces 256-bit base64url tokens by default", () => {
    const t = real.token();
    expect(t).toMatch(/^[A-Za-z0-9_-]{43}$/);
    expect(real.token()).not.toBe(t);
  });
  it("refuses weak sizes", () => {
    expect(() => real.token(64)).toThrow(RangeError);
  });
  it("rejects biased bytes instead of folding them", () => {
    // Bytes 250..255 must be skipped for a 10-symbol alphabet: 255 is dropped, 7 maps to "7".
    const fake = makeTokenFactory(() => Buffer.from([255, 7]));
    expect(fake.code("0123456789", 1)).toBe("7");
  });
  it("is close to uniform over many draws", () => {
    const counts = new Map<string, number>();
    for (let i = 0; i < 1000; i++) for (const ch of real.code("0123456789", 100)) counts.set(ch, (counts.get(ch) ?? 0) + 1);
    for (const c of counts.values()) expect(Math.abs(c - 10_000)).toBeLessThan(500);   // about 5 standard deviations
  });
});

05Extensions, follow-ups, how to say it

  • Prefixes: cy_live_ style prefixes let secret scanners find leaked keys; GitHub and Stripe do this.
  • Checksums: a CRC32 suffix lets you reject typos and scanner false positives without a database lookup; it adds no security.
  • Store hashes: a token that grants access should be stored as SHA-256, so a database read does not hand out live tokens.
  • Deterministic tests: inject the random source, as above, rather than mocking the crypto module globally.
Q1Is a UUIDv4 from crypto.randomUUID good enough for a session id?+

It carries 122 random bits from a CSPRNG in Node and browsers, which is enough. A dedicated 256-bit token is still clearer about intent and avoids depending on how a given library builds its UUIDs.

Q2How many bits does a 43-character base64url token have?+

43 characters at 6 bits each is 258 bits of encoding, carrying the 256 bits from 32 random bytes; the last character holds 2 padding bits.

Q3Why is `randomBytes(1)[0] % 6` wrong for a die roll?+

256 is not divisible by 6, so values 0 to 3 occur 43 times in 256 and 4 to 5 only 42. Reject bytes of 252 and above, or use crypto.randomInt(6).

“How to say it in the room

"Anything an attacker must not guess comes from the OS CSPRNG: randomBytes or randomInt in Node, the secrets module in Python, crypto/rand in Go, never Math.random, random or math/rand. Long-lived secrets get 256 bits, encoded base64url, and are stored hashed. For human codes I pick from an alphabet with rejection sampling to avoid modulo bias, and because they are short they get attempt limits, expiry and single use. Timestamps and UUIDv7 are identifiers, not secrets."

Test yourself

A password reset token is built as `sha256(email + Date.now()).hex()`. What is its real strength?

Finished this one?
Tick it and it shows as done on the roadmap and the course.