【发布时间】:2019-09-07 18:30:05
【问题描述】:
我知道我们可以使用window.crypto 来生成一个安全的随机数,但是window.crypto.getRandomValues() 使用的是typedArray。
请问如何才能在 JavaScript 中准确地实现这个 Java 功能:
new BigInteger(130, new SecureRandom()).toString(32)
【问题讨论】:
我知道我们可以使用window.crypto 来生成一个安全的随机数,但是window.crypto.getRandomValues() 使用的是typedArray。
请问如何才能在 JavaScript 中准确地实现这个 Java 功能:
new BigInteger(130, new SecureRandom()).toString(32)
【问题讨论】:
您可以生成四个 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()。
【讨论】: