繁体   English   中英

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

[英]Equivalent of window.crypto() in node.js

我想转换成的node.js脚本。 我遇到的问题,因为window.crypto在 node.js 中不可用,是 Box Müller 变换不起作用,而是我从下面代码的else部分获得(几乎)伪随机结果。

我尝试使用this question中的一些答案,但没有一个有效。 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()));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM