Blog · 3 min read ·
The Subtle Bug in Most Random Password Generators
When I built my password generator, the obvious code was: get a random number, take it modulo the alphabet length, pick that character. It looks right, and it's slightly wrong.
Modulo bias
Say your random source gives a number from 0 to 9 and your alphabet has 4 letters. Using n % 4: 0, 4 and 8 give the first letter; 1, 5 and 9 give the second; but only 2 and 6 give the third, and 3 and 7 give the fourth. The first two letters are 50% more likely than the last two.
With a 32-bit random number and a 60-character alphabet the bias is tiny, but it's real, and a password generator is exactly the place you don't want it.
Rejection sampling
The fix is to throw away the numbers that cause the imbalance. Find the largest multiple of the alphabet length that fits in the random range. If a random number lands at or above it, discard it and draw again. Every remaining number maps to each character the same number of times, so every character is exactly equally likely. In practice a redraw almost never happens.
The other details
- Random numbers come from
crypto.getRandomValues, notMath.random, which isn't meant for security. - At least one character from each chosen set is included, then the whole password is shuffled with a Fisher–Yates shuffle (also using rejection sampling).
- Look-alike characters such as l, 1, O and 0 are left out so the password is easy to type.
- Nothing is sent anywhere; it all runs in your browser.