DEV Community

Sikandar Bro
Sikandar Bro

Posted on

My password generator used crypto.getRandomValues and was still wrong 15% of the time

My site has a small client-side password generator. It has a length slider, four checkboxes (A–Z, a–z, 0–9, symbols) and crypto.getRandomValues. I assumed it was done. Then I went back to it while writing a blog post, and it had two problems. One was mostly theoretical. The other was very practical.

The original code

let s = '';
if (up.checked) s += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
if (lo.checked) s += 'abcdefghijklmnopqrstuvwxyz';
if (nu.checked) s += '0123456789';
if (sy.checked) s += '!@#$%^&*()-_=+[]{};:,.?';

const a = new Uint32Array(L);
crypto.getRandomValues(a);
let p = '';
for (let i = 0; i < L; i++) p += s[a[i] % s.length];
Enter fullscreen mode Exit fullscreen mode

It uses a cryptographic RNG, so it looks fine. Here's what's wrong with it.

Problem 1: "Password must contain a number"

Ticking "0–9" only means digits are allowed. Nothing guarantees one shows up. With all four groups ticked, the combined set has 85 characters, and only 10 of them are digits.

I simulated 200,000 passwords at each length and counted how many were missing at least one of the ticked groups:

Length Missing a ticked group
6 70.6%
8 51.0%
12 26.5%
16 (my default) 14.6%

So roughly one in seven passwords at the default length would be rejected by a sign-up form that requires "at least one number and one symbol". The user ticked the boxes, copied the password, and the website said no. That's a real bug, not a theory.

Problem 2: modulo bias

a[i] % s.length maps 2³² possible values onto 85 characters. 2³² isn't a multiple of 85 (the remainder is 1), so one character gets picked very slightly more often than the others. Here the difference is about 2 in 10 billion, which nobody will ever exploit. But the fix is three lines, and it matters more when the set size is large relative to the random range. So:

// unbiased integer in [0, n)
function rnd(n) {
  const lim = Math.floor(2 ** 32 / n) * n;   // largest multiple of n
  const b = new Uint32Array(1);
  do { crypto.getRandomValues(b); } while (b[0] >= lim);
  return b[0] % n;
}
Enter fullscreen mode Exit fullscreen mode

This is rejection sampling: throw away the few values from the incomplete top range and draw again. For small n a retry almost never happens.

The fix for problem 1

Pick one character from each ticked group first, fill the rest from the combined set, then shuffle so the guaranteed characters aren't always at the start:

const sets = [];   // only the ticked groups
// ...push each ticked group's characters...
const all = sets.join('');

const c = sets.map(g => g[rnd(g.length)]);   // one from each group
while (c.length < L) c.push(all[rnd(all.length)]);

for (let i = c.length - 1; i > 0; i--) {     // Fisher–Yates
  const j = rnd(i + 1);
  [c[i], c[j]] = [c[j], c[i]];
}
const password = c.join('');
Enter fullscreen mode Exit fullscreen mode

I ran 20,000 passwords of length 6 with all groups ticked through the new version. All 20,000 contained every group.

Does guaranteeing one of each make the passwords weaker? Slightly, in theory, because the space is a little smaller than "any 16 of 85". In practice it's negligible. A 16-character password with all four groups is still around 100 bits of entropy, and the alternative is a password the website refuses.

The lesson

Using crypto.getRandomValues makes a generator secure. It doesn't make it correct. The bug that hurt users was in the logic around the RNG: what the checkboxes promise versus what the code guarantees. If you've written a generator like this, run a quick simulation over its output. It takes five minutes.

The generator is part of 14FreeTools, a set of free tools that run entirely in the browser. Nothing you generate is sent anywhere.

Top comments (3)

Collapse
 
browsercraft profile image
Browser Craft •

The other edge the original checkboxes hide: if someone sets the length slider below the number of ticked groups (length 3, all four boxes on), the “pick one from each group first” path has nowhere to put the fourth character. I now clamp L to at least sets.length, or disable the extra checkboxes once L is below the group count. Otherwise you either truncate a guaranteed character or loop forever depending on how the fill is written.

Also worth returning early when no box is ticked — the original s[a[i] % s.length] with an empty s is a hard crash, which is a worse UX than asking the user to pick a character set.

Collapse
 
kling4ai-production profile image
Kling4 AI •

Seeing a 14.6% miss rate at length 16 with all four checkboxes ticked makes that bug immediately real. Guaranteeing one char from each selected group before Fisher-Yates shuffling fixes the exact UX failure users blame on sign-up forms.

Collapse
 
maxbuildsdev profile image
Max Kaya •

One number worth putting next to that table: at length 6 the group guarantee is not a small entropy trade. The valid set is 85^6 minus the passwords missing a group - roughly 29% of the raw space - so a 6-char password loses about 1.8 bits to the constraint on top of being short. At 16 it is about 0.23 bits, which is why your "negligible in practice" is right there and wrong at the short end. If a strength bar ever reports L*log2(85), the short lengths are exactly the ones it flatters; inclusion-exclusion over the four ticked groups gives the real count.

The next bug is probably not in the RNG: a site whose server truncates at maxlength (or trims ;, <>, space) accepts the paste, stores 12 of your 16 characters, and the user meets it at the login screen. Same class as the rejected-password one - the generator thinks it made a password and the consumer silently edited it.

Question about the deployment rather than the algorithm: the value has to sit in the page's JS to be copied, so anything third-party on that origin (analytics, tag manager, ads) can read it off the DOM or patch crypto.getRandomValues before you call it. Does 14FreeTools ship that page with zero third-party scripts, or is the generator iframed from a separate origin?