Why do not use Math.random()

Kemil Beltre
2 min readJan 23, 2022

The JavaScript Math.random() function is designed to return a floating point value between 0 and 1. It is widely known (or at least should be) that the output is not cryptographically secure.

What’s the risk?

Using pseudorandom number generators (PRNGs) is security-sensitive. For example, it has led in the past to the following vulnerabilities:

When software generates predictable values in a context requiring unpredictability, it may be possible for an attacker to guess the next value that will be generated, and use this guess to impersonate another user or access sensitive information.

As the Math.random() function relies on a weak pseudorandom number generator, this function should not be used for security-critical applications or for protecting sensitive data. In such context, a cryptographically strong pseudorandom number generator (CSPRNG) should be used instead.

Are you at risk?

Ask Yourself Whether

  • the code using the generated value requires it to be unpredictable. It is the case for all encryption mechanisms or when a secret value, such as a password, is hashed.
  • the function you use generates a value which can be predicted (pseudo-random).
  • the generated value is used multiple times.
  • an attacker can access the generated value.

There is a risk if you answered yes to any of those questions.

Cryptographically strong generation method

Just tested the following code in Chrome to get a random byte:

(function(){
var buf = new Uint8Array(1);
window.crypto.getRandomValues(buf);
alert(buf[0]);
})();

Summary

  • You can use Math.random() when the expected value does not compromise the app.
  • It’s difficult for a web page to detect whether Math.random() is
    actually cryptographically strong or whether it’s a weak RNG.
  • Use strong generation methods as Crypto.getRandomValues() when required.

Sources

Thanks for reading, leave a comment on what you think about The Code Reviews. And don’t forget that if you liked this post you can leave 50 claps it’s free.

👋 Let’s be friends! Follow me on Twitter and connect with me on LinkedIn. Don’t forget to follow me here on Medium as well.

--

--