相当于 node.js 中的 window.crypto()

Equivalent of window.crypto() in node.js

我正在尝试将 this 转换为 node.js 脚本。我 运行 遇到的问题是,因为 window.crypto 在 node.js 中不可用,所以 Box Müller 变换不起作用,而是我从else 以下部分代码。

我尝试使用 中的一些答案,但其中 none 有效。 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
}

更具体地说,是一种完成 that code 中的 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()));