在JavaScript中实现新的BigInteger(130,新的SecureRandom()).toString(32)

在JavaScript中实现新的BigInteger(130,新的SecureRandom()).toString(32),javascript,secure-random,Javascript,Secure Random,我知道我们可以使用window.crypto生成安全的随机数,但是window.crypto.getRandomValues()正在使用typedArray。 我想知道我们如何用JavaScript实现这个Java函数: new BigInteger(130, new SecureRandom()).toString(32) 您可以生成四个32位数字,总共128位-接近Java的最大值130(指定给biginger构造函数的值是最大位数,如中所述),然后将它们全部转换为基数32,最后将它们连接

我知道我们可以使用
window.crypto
生成安全的随机数,但是
window.crypto.getRandomValues()
正在使用
typedArray
。 我想知道我们如何用JavaScript实现这个Java函数:

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

您可以生成四个32位数字,总共128位-接近Java的最大值130(指定给
biginger
构造函数的值是最大位数,如中所述),然后将它们全部转换为基数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("");
}
调用是必需的,因为
TypedArray.prototype.map
返回另一个
TypedArray
,并且类型化数组不能包含字符串。我们首先将类型化数组
randoms
转换为普通数组,然后对其调用
.map()