11

When I declared a variable like:

const FileId = Math.random().toString(36).substr(2, 9);

I am getting this error in Sonar:

Make sure that using this pseudorandom number generator is safe here.

How should I address this? What is wrong with my code?

Can anyone help me?

kmoser
  • 8,780
  • 3
  • 24
  • 40
3gwebtrain
  • 14,640
  • 25
  • 121
  • 247

2 Answers2

13

They want to alert you to the fact that Math.random is not a true random generator but a PRNG. If you need this to be safe you need a CSPRNG.

Here is the spec

Using PseudoRandom Number Generators (PRNGs) is security-sensitive

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.

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.

You are at risk if you answered yes to the first question and any of the following ones.

Code example

const crypto = window.crypto || window.msCrypto;
var array = new Uint32Array(1);
crypto.getRandomValues(array); // Compliant for security-sensitive use cases
const FileId = array[0];
console.log(FileId);
mplungjan
  • 169,008
  • 28
  • 173
  • 236
2

As the java.util.Random class relies on a pseudorandom number generator, this class and relating java.lang.Math.random() method should not be used for security-critical applications or for protecting sensitive data. In such context, the java.security.SecureRandom class which relies on a cryptographically strong random number generator (RNG) should be used in place.

SecureRandom random = new SecureRandom(); // Compliant for security-sensitive use cases
int bound = 100;
random.nextInt(bound);

Ref: https://rules.sonarsource.com/java/RSPEC-2245

Muhammed_G
  • 375
  • 3
  • 7