Skip to content

Randomness and entropy in the browser

The difference between cryptographic randomness and Math.random(), how entropy is measured, and when each source is appropriate.

Two functions can both return numbers that look random while offering completely different guarantees. A pseudorandom generator produces a deterministic sequence from internal state, so given enough output an observer can predict what comes next. A cryptographic generator draws from the operating system entropy pool and is designed to make that prediction infeasible.

Where the distinction matters

Shuffling a carousel, jittering an animation, or sampling rows for a preview are all fine with a fast pseudorandom source. Password resets, session tokens, API keys, coupon codes, and anything presented as a fair draw are not—those need a cryptographic source, and the performance difference is irrelevant at the volumes involved.

Measuring entropy

Entropy is measured in bits: log2 of the number of equally likely possibilities. A 16-character password drawn from a 62-character alphabet carries about 95 bits, while a "clever" human password with substitutions typically carries far less because the pattern is predictable. Length raises entropy faster than adding symbol classes.

Avoiding bias in ranges

Taking the modulus of random bytes over-weights the low end of a range unless the range divides the byte space evenly. Correct implementations reject and redraw out-of-range values instead, which is why a good range generator is slightly more involved than one line of arithmetic.

Generate locally

Draw numbers with Random Number Generator, tokens with Random String Generator, and identifiers with UUID Generator. Compare the two sources in Crypto Random vs Math.random().

Try related tools

Keep exploring