Your Backup Codes Are Weaker Than Your Passwords: Three Randomness Bugs You Can Measure
Most teams get the password generator right and then hand-write the account-recovery path in ten minutes. Here are three randomness bugs you can measure in a terminal, with the numbers I got today.
1. sort(() => Math.random() - 0.5) is not a shuffle
The "pick 4 distinct words from a list" pattern shows up in recovery phrases, invite codes and diceware-style generators:
const code = words.sort(() => Math.random() - 0.5).slice(0, 4).join('-'); Array.prototype.sort expects a consistent comparator; this one returns a random sign on every comparison, so the result depends on the engine's sort implementation, not on chance.
I shuffled [0,1,2,3] 200,000 times and counted each of the 24 permutations. Uniform would be about 8,333 each:
| method | least frequent | most frequent |
|---|---|---|
sort(() => Math.random() - 0.5) | 3,024 | 37,385 |
| Fisher–Yates | 8,166 | 8,520 |
One permutation comes up 12x more often than another. That is a measurable bias in a code you hand to users.
The fix is Fisher–Yates, with the index taken from a CSPRNG:
for (let i = a.length - 1; i > 0; i--) { const j = crypto.randomInt(i + 1); [a[i], a[j]] = [a[j], a[i]]; } 2. Composition rules buy 0.6 bits, length buys 6.5
"Must contain uppercase, digit and symbol" usually gets implemented as "regenerate until the regex passes". The rejection loop is not the real problem, the trade is: going from a 62-character alphabet to all 94 printable ASCII characters adds log2(94/62) = 0.60 bits per character. One extra character from the small alphabet adds log2(62) = 6.55 bits, eleven times more. If you have a length cap, spend it on length.
3. An 8-digit numeric recovery code is 26.6 bits
Math.floor(Math.random() * 1e8) looks like a big number. log2(1e8) = 26.58 bits. A single GPU does roughly 1e9 SHA-256 guesses per second, so the whole space is 0.1 seconds of offline work. If the code is checked by a database lookup with no rate limit, it is a 0.1-second lock.
Two acceptable shapes: make it long (10 alphanumeric characters is about 59 bits), or make it slow (store only a hash, count failures per account, lock after five).
Checklist
- CSPRNG for every index:
crypto.randomInt,secrets.choice,crypto/rand.Int. - Rejection sampling, not modulo. A 62-character alphabet over 256 byte values makes the first eight characters 25% more likely.
- Fisher–Yates for anything that says "pick N distinct".
- Treat recovery codes as credentials: hash them, rate-limit them, expire them.
I keep a local-only generator for the password half at codetoolbox.pro/tools/password-generator.html. It uses crypto.getRandomValues() with rejection sampling, so the alphabet stays uniform. The recovery-code half is still on you.