【问题标题】:Achieve new BigInteger(130, new SecureRandom()).toString(32) in JavaScript在 JavaScript 中实现 new BigInteger(130, new SecureRandom()).toString(32)
【发布时间】:2019-09-07 18:30:05
【问题描述】:

我知道我们可以使用window.crypto 来生成一个安全的随机数,但是window.crypto.getRandomValues() 使用的是typedArray。 请问如何才能在 JavaScript 中准确地实现这个 Java 功能:

new BigInteger(130, new SecureRandom()).toString(32)

【问题讨论】:

    标签: javascript secure-random


    【解决方案1】:

    您可以生成四个 32 位数字,总共 128 - 接近您的 Java 最大值 130(指定给 BigInteger 的构造函数的值是 最大 位数,如在docs中声明),然后将它们全部转换为base 32,最后将它们连接在一起。

    function getSecureRandom() {
        // allocate space for four 32-bit numbers
        const randoms = new Uint32Array(4);
        // get random values
        window.crypto.getRandomValues(randoms);
        // convert each number to string in base 32, then join together
        return Array.from(randoms).map(elem => elem.toString(32)).join("");
    }
    

    Array#from 调用是必要的,因为TypedArray.prototype.map 返回另一个TypedArray,并且类型化数组不能包含字符串。我们首先将类型化数组randoms转换为普通数组,然后在其上调用.map()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-22
      • 1970-01-01
      • 1970-01-01
      • 2019-06-28
      • 1970-01-01
      • 2014-07-14
      • 1970-01-01
      • 2021-08-11
      相关资源
      最近更新 更多