等效于node.js中的window.crypto()



我正在尝试将其转换为node.js脚本。由于window.crypto在node.js中不可用,我遇到的问题是Box Müller变换不起作用,相反,我从下面代码的else部分(几乎(得到了伪随机结果。

我试着使用这个问题的一些答案,但都不起作用。node.js模块crypto与浏览器方法window.crypto不是1:1匹配的,所以我很难将Box Müller转换脚本从浏览器调整到node.js。

具体来说,我正在寻找这部分代码的node.js版本:

if (crypto && typeof crypto.getRandomValues === 'function') { // What library can be used as an equivalent of crypto.getRandomValues?
RAND_MAX = Math.pow(2, 32) - 1;
array = new Uint32Array(1); // What is the node.js equivalent?
random = function () {
crypto.getRandomValues(array); // What is the node.js equivalent?
return array[0] / RAND_MAX;
};
} else {
random = Math.random; // I don't want this
}

更具体地说,是一种实现该代码中crypto.getRandomValues(array)正在做的相同事情的方法。

非常感谢您的帮助!

我们可以使用crypto.randomBytes((生成一个由4个随机字节(32位(组成的数组,然后除以0xffffffff的最大无符号32位整数(2^32-1(,得到一个0到1之间的随机数。

可以潜在地使用多于4个字节,例如可能使用8个字节。原则上,这样会更安全。

const crypto = require("crypto");
function random() {
const buffer = crypto.randomBytes(4);
return buffer.readUInt32LE() / (0xffffffff); // Divide by maximum value of 32-bit unsigned int.
}
// Generate 10 numbers..
console.log(Array.from({ length: 10 }, (v,k) => random()));

最新更新