Math.random() is not secure ? 🤔

Chami Perera
2 min readApr 3, 2020

--

Yes. it is!

If you are using Javascript or any other JavaScript environment like NodeJs you may definitely use Math.random() as your default PRNG.

PRNG -> Pseudo-Random Number Generator

Actually there is no random in Math.random().

pseudorandom

By definition there no random in PRNGs. They have a set of initial seed values and they create random values. Because there are chances to repeat the same value or an attacker can predict these random values if he is aware of initial seed values.

Math.random() is useless when …

If you are using unique random numbers as session IDs for some active users in a system it would be a huge security issue.

But luckily there are some powerful PRNGs in the world as a solution for this,

  1. Xorshift
  2. PCG
  3. Mersenne Twister
  4. CSPRNG

CSPRNG

For security central scenarios, there is a Cryptographically Secure Pseudo-Random Number Generator. 1–3 listed PRNGs are really better than Math.random().They are fast, powerful, and efficient. But they are lack of cryptographic.

BY default NodeJS provide crypto.randomBytes() to generate random numbers. This is more impressive than Math.random(). In Math random() it generates a table of unique values at once. But crypto.randomBytes()

generates a table of unique possible random values in each call.

Math.random() is not a trash 🗑

If you are not using PRNG for some security things or session IDs as I mentioned it before, No Problem You can proceed with Math.random()!

Yes, You can use it a task as a simple dice game.

--

--

Chami Perera
Chami Perera

Written by Chami Perera

Engineer | Blogger | Traveler | Chef | Mum 👆🏻

No responses yet