Secure random numbers
Cryptographically secure random numbers are values that cannot be predicted, even by someone who has seen earlier ones. Browsers provide them through crypto.getRandomValues in the Web Crypto API. They are the right source for passwords, random IDs, test data and fair shuffles, where Math.random is not.
Random is easy to ask for and easy to get wrong. A sequence can look random and still be predictable, and a choice can look fair and still favour some outcomes.
Two sources in a browser
Math.random returns numbers that are fine for a game’s sparkle effect. The specification does not promise that they are unpredictable, and some engines use generators whose state can be recovered from a few outputs.
crypto.getRandomValues, part of the W3C Web Crypto API, draws from the operating system’s secure generator. Its output is meant to be unpredictable even to someone who has seen everything it produced before. Anything that guards access, such as a password or a token, should come from here.
Picking without bias
Getting secure bytes is half the job. Turning them into a choice is the other half. A byte has 256 values; taking it modulo 10 to pick a digit makes 0 to 5 slightly more likely than 6 to 9, because 256 is not a multiple of 10. The fix is rejection sampling: discard bytes that fall in the uneven tail and draw again.
Fair shuffles
The Fisher-Yates shuffle walks a list from the end, swapping each item with one chosen at random from those not yet placed. With unbiased picks, every possible order is equally likely. The popular trick of sorting by a random key is not fair, and the bias depends on the sorting method the engine uses.
Where it matters
Passwords, API keys, invite codes, raffle draws, the order of survey questions and test data that must not collide with real records all depend on randomness nobody can predict or steer.
Frequently asked questions
Why not use Math.random?
Its output is not guaranteed to be unpredictable, and in some engines it can be reconstructed from a handful of values. For a password, a token or anything an opponent might want to guess, use crypto.getRandomValues.
What makes a shuffle fair?
Every order has to be equally likely. The Fisher-Yates shuffle does that, as long as each pick is unbiased. Sorting by a random number is a common shortcut that is not fair.
What is modulo bias?
Taking a random byte modulo a number that does not divide 256 makes the low values slightly more likely. Rejecting out-of-range bytes and drawing again removes the bias.