DEV Community

Leo Ho
Leo Ho

Posted on

Why crypto.getRandomValues() is not Math.random(), and the password code that gets it right

Math.random() is a PRNG. It is fine for particle positions and test data; it is not fine for passwords, session ids, reset tokens, or anything an attacker can guess or replay. V8's implementation is fast and deterministic, and its internal state is small enough that research has recovered it from observed outputs. You do not need to understand that attack to know the rule: Math.random is not designed to be unpredictable.

crypto.getRandomValues is the platform CSPRNG. It fills a typed array with random bytes from the operating system, synchronously, with a hard cap of 65,536 bytes per call. That is the primitive a password generator should stand on.

Entropy is length first

length × log2(alphabet): 12 characters from a 94-character alphabet is about 79 bits, 16 is about 105, 20 is about 131. Each extra character buys roughly 6.5 bits, far more than swapping one symbol set for another. But the formula assumes every character is drawn uniformly from the alphabet, and that assumption is where generator bugs live.

Bug 1: modulo bias

charset[byte % charset.length] with a single random byte looks fine until you do the arithmetic: 256 = 2×94 + 68. The first 68 characters of a 94-character alphabet get three byte values each; the last 26 get two. In a 2.56 million-draw simulation, the first 68 appeared 30,000 times each on average, the last 26 only 20,000: a 1.5× bias in a password that otherwise looks random. The fix is rejection sampling with 32-bit values: throw away values above the largest multiple of the alphabet size, then take the modulo.

Bug 2: no guaranteed character classes

Draw 16 characters uniformly from letters plus digits (62 symbols) and there is a 6% chance the result contains no digit at all. From a 94-symbol set the chance of no digit is 16%. Users get a "strong" password, then the site's policy rejects it or the password manager complains. Generate one character from each required class, fill the rest from the pool, then shuffle.

Bug 3: a Math.random shuffle

Generating with crypto and shuffling with sort(() => Math.random() - 0.5) leaks the whole point. That comparator is also not a uniform shuffle: it is a biased comparison sort, not Fisher-Yates. Shuffle with crypto-backed indices, inside the same function.

The code

const CHARSETS = {
  lower: "abcdefghijklmnopqrstuvwxyz",
  upper: "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
  digits: "0123456789",
  symbols: "!@#$%^&*()-_=+[]{};:,.?"
};

function randomInt(max) {
  const limit = Math.floor(0x100000000 / max) * max;
  const buf = new Uint32Array(1);
  for (;;) {
    crypto.getRandomValues(buf);
    if (buf[0] < limit) return buf[0] % max;
  }
}

function shuffle(arr) {
  for (let i = arr.length - 1; i > 0; i--) {
    const j = randomInt(i + 1);
    [arr[i], arr[j]] = [arr[j], arr[i]];
  }
  return arr;
}

function generatePassword(length = 16, required = ["lower", "upper", "digits", "symbols"]) {
  if (length < required.length) throw new Error("length < required classes");
  const pool = required.map((k) => CHARSETS[k]).join("");
  const chars = required.map((k) => CHARSETS[k][randomInt(CHARSETS[k].length)]);
  while (chars.length < length) chars.push(pool[randomInt(pool.length)]);
  return shuffle(chars).join("");
}

for (let i = 0; i < 3; i++) console.log(generatePassword(20));
Enter fullscreen mode Exit fullscreen mode

The code runs unchanged in a browser and in Node, which exposes the same Web Crypto globals. Over 20,000 generated passwords every result was 16 characters and contained all four classes; randomInt(94) over 188,000 draws gave a chi-square of 93.3 with 93 degrees of freedom, which is what uniform looks like.

What this does not solve

A generator cannot fix a weak server. Hash passwords with Argon2 or bcrypt, never log them, and treat the generated string as a secret from the moment it appears. Client-side generation still has a real advantage: the password is created in the tab and never crosses the network, so there is nothing to intercept.

Both versions run entirely in the browser with the Web Crypto API, so no password leaves the tab: English password generator and Vietnamese password generator. Generate, copy, store in a manager.

— Leo Ho

Top comments (0)