JavaScript Randomness: Math.random(), Web Crypto, and Modulo Bias

From generating session tokens and cryptographic nonces to shuffling game decks and determining randomized decision outcomes, randomness is a cornerstone of web software. For decades, JavaScript developers have relied instinctively on Math.random() whenever an element of chance was required.

However, Math.random() is not actually random. It is a deterministic mathematical sequence governed by a pseudorandom number generator (PRNG). In high-security contexts, relying on Math.random() has led to catastrophic vulnerabilities, including session hijacking, predictable password reset tokens, and game rigging. In this guide, we dissect the internal mechanics of V8's PRNG, demonstrate why its internal state can be reverse-engineered, and show how tools like our Spin Decide harness the W3C Web Cryptography API for cryptographically strong pseudorandom values.

1. The Mechanics of Pseudorandom Number Generators

Computers are deterministic state machines. Given identical hardware inputs and software state, a CPU will execute instructions identically every single time. True physical randomness—entropy derived from thermal noise, atmospheric static, or radioactive decay—is not readily accessible through a simple CPU arithmetic instruction.

To simulate randomness efficiently, programming languages use Pseudorandom Number Generators (PRNGs). A PRNG is a deterministic mathematical formula that takes an initial seed value, maintains an internal state, and generates a sequence of numbers that statistically mimic a uniform random distribution.

ECMAScript leaves the algorithm behind Math.random() implementation-dependent and does not require it to be cryptographically secure. Engine versions may change the generator, output caching, and seeding. Security guidance should not depend on a single named browser algorithm.

2. Why general-purpose randomness is unsuitable for tokens

Some non-cryptographic generators permit state reconstruction when an attacker observes enough suitable outputs and knows the implementation. The number of observations and feasibility depend on the generator and how outputs are exposed; there is no universal two-to-five-output prediction guarantee.

Do not generate session identifiers, reset tokens, or encryption material with Math.random(). Use an established authentication library or an appropriate cryptographic API, with enough entropy and secure token handling.

3. Cryptographically Secure PRNGs (CSPRNG)

To withstand adversarial attacks, a random number generator must be a Cryptographically Secure Pseudorandom Number Generator (CSPRNG). A CSPRNG satisfies two strict cryptographic criteria:

  1. Next-output unpredictability: under the security assumptions, an attacker with feasible computational resources should not be able to predict future output from observed output with a useful advantage.
  2. State Compromise Resistance (Forward & Backward Secrecy): If an attacker somehow discovers the internal state of the generator at time T, they cannot deduce any numbers generated before time T, nor any numbers generated after entropy re-seeding.

4. Harnessing Web Cryptography API: crypto.getRandomValues()

Modern web browsers provide native access to the operating system's kernel-level entropy pool (e.g., /dev/urandom on Linux/macOS, or BCryptGenRandom on Windows) via the Web Cryptography API.

The crypto.getRandomValues() method accepts a typed array (such as Uint8Array, Uint16Array, or Uint32Array) and populates it with cryptographically secure random integers:

// Generate a cryptographically secure 32-bit unsigned integer
function getSecureRandomInt() {
    const buffer = new Uint32Array(1);
    window.crypto.getRandomValues(buffer);
    return buffer[0];
}

// Generate a secure float in the range [0, 1)
function getSecureRandomFloat() {
    const buffer = new Uint32Array(1);
    window.crypto.getRandomValues(buffer);
    // Divide by 2^32 (4294967296) to obtain a normalized float [0, 1)
    return buffer[0] / 4294967296;
}

5. Avoiding the Modulo Bias Trap

Even when using a secure entropy source, developers often introduce statistical bias when mapping large random integers into a smaller discrete range (such as choosing a number between 0 and 5 for a 6-sided die):

// BIASED ANTI-PATTERN: Modulo bias distorts probabilities
function biasedRoll(sides) {
    const rand = getSecureRandomInt();
    return (rand % sides) + 1; // Numbers below (2^32 % sides) have higher probability!
}

Because 232 (4,294,967,296) is rarely evenly divisible by sides, the lower numbers receive slightly more opportunities to be chosen. In fair gaming and cryptographic key derivation, this bias must be eliminated using rejection sampling:

// UNBIASED: Rejection sampling eliminates modulo bias
function secureRandomRange(min, max) {
    const range = max - min + 1;
    if (!Number.isSafeInteger(min) || !Number.isSafeInteger(max) ||
        !Number.isSafeInteger(range) || range < 1 || range > 4294967296) {
        throw new RangeError("Use safe integer bounds spanning 1 to 2^32 values");
    }
    const maxValid = Math.floor(4294967296 / range) * range;
    const buffer = new Uint32Array(1);

    let rand;
    do {
        window.crypto.getRandomValues(buffer);
        rand = buffer[0];
    } while (rand >= maxValid); // Discard numbers in the remainder zone

    return min + (rand % range);
}

Conclusion

Use Math.random() for ordinary non-security effects. Use cryptographic APIs for security-sensitive randomness, and validate range limits before rejection sampling. A secure random source alone does not make an authentication or prize-draw system secure.

To make fair, unbiased decisions using client-side cryptographic entropy and rejection sampling algorithms, try our free decision wheel tool: Spin Decide.

References

Sudarshan Babar

Sudarshan Babar

Founder & Lead Developer at getinfotoyou. Specialized in full-stack web architecture, client-side algorithm engineering, and transparent personal finance modeling.