确保在这里使用这个伪随机数生成器是安全的

Make sure that using this pseudorandom number generator is safe here

当我声明一个变量时:

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

我在 Sonar 中遇到这个错误:

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

我应该如何解决这个问题?我的代码有什么问题?

谁能帮帮我?

他们想提醒您 Math.random 不是真正的随机生成器,而是 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.
  • 您使用的函数生成了一个可以预测的值(伪随机)。
  • 生成的值被多次使用。
  • 攻击者可以访问生成的值。

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

代码示例

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);