Skip to content

Crypto Random vs Math.random()

Cryptographically strong randomness versus fast pseudorandom numbers—compare predictability and correct use cases.

Overview

Both APIs return numbers that look random, but only one is designed to resist an adversary. A pseudorandom generator produces a deterministic sequence from internal state, so observing enough output can reveal what comes next—fine for shuffling a carousel, disqualifying for a password reset token. The cost of the secure option is small enough that it should be the default for anything security-adjacent.

Pros

  • Unpredictable output suitable for secrets
  • Backed by the operating system entropy pool
  • Available in browsers via Web Crypto

Cons

  • Slower than a plain pseudorandom call
  • Cannot be seeded for reproducible tests

Math.random()

Pros

  • Extremely fast for bulk values
  • Fine for animation jitter and sampling
  • Available with no API ceremony

Cons

  • Output is predictable from observed values
  • Never acceptable for tokens or keys

Comparison table

AspectCrypto randomMath.random()
PredictabilityNot feasible to predictPredictable from enough output
SpeedFast enough, slightly slowerFastest
Correct useTokens, passwords, keys, IDsVisual noise, sampling, games
Best fitThe value protects something or must be unguessableThe value is cosmetic or statistical only

Recommendation

Use a cryptographic source for passwords, tokens, identifiers, and anything drawn as a fair outcome, and keep the fast generator for cosmetic effects. When randomness needs to be reproducible in tests, seed an explicit generator rather than weakening production code.

Related tools

Related articles

Frequently asked questions

Is Math.random() ever acceptable?
Yes, for visual jitter, sampling, and non-competitive simulations. It is never acceptable for secrets, tokens, or anything a user could benefit from predicting.
How do I avoid bias when picking a range?
Rejection sampling. Naively taking a modulus of random bytes over-weights the low end unless the range divides the byte space evenly.
What pushes someone toward Crypto random instead of Math.random()?
Crypto random wins when the value protects something or must be unguessable. The practical upside is that unpredictable output suitable for secrets, and backed by the operating system entropy pool. The trade-off to watch is that slower than a plain pseudorandom call.
When does Math.random() beat Crypto random for the same job?
Reach for Math.random() when the value is cosmetic or statistical only. It gives you extremely fast for bulk values plus fine for animation jitter and sampling, at the cost that output is predictable from observed values.
Can ToolHub help me try Crypto random and Math.random() before I commit?
Yes. The tools linked from each side of Crypto Random vs Math.random() run in your browser, so you can exercise Crypto random and Math.random() with sample data without uploading anything.