gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 00:28:37 26 4
gpt4 key购买 nike

当我声明一个变量时:

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

我在 Sonar 中收到此错误:

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



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

谁能帮我?

最佳答案

他们想提醒您 Math.random 不是真正的随机生成器,而是 PRNG。 .如果您需要确保安全,您需要 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);

    关于javascript - 确保在这里使用这个伪随机数生成器是安全的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62036514/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com