简体   繁体   English

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

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

I am trying to convert this into a node.js script.我想转换成的node.js脚本。 The issue I am running into, because window.crypto is not available in node.js, is that the Box Müller transform is not working and instead I am getting (barely) pseudo-random results from the else portion of the code below.我遇到的问题,因为window.crypto在 node.js 中不可用,是 Box Müller 变换不起作用,而是我从下面代码的else部分获得(几乎)伪随机结果。

I tried using some of the answers from this question , but none of them are working.我尝试使用this question中的一些答案,但没有一个有效。 The node.js module crypto is not a 1:1 match for the browser method window.crypto , so I am struggling to adapt the Box Müller transform script from browser to node.js. node.js 模块crypto与浏览器方法window.crypto不是 1:1 匹配,因此我正在努力将 Box Müller 转换脚本从浏览器调整为 node.js。

Specifically, I am looking for a node.js version of this portion of code:具体来说,我正在寻找这部分代码的 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
}

And more specifically, a way to accomplish the same thing that crypto.getRandomValues(array) in that code is doing.更具体地说,是一种完成与该代码中的crypto.getRandomValues(array)相同的事情的方法。

Any help is greatly appreciated!任何帮助是极大的赞赏!

We can use crypto.randomBytes() to generate an array of 4 random bytes (32 bits), then divide by the maximum unsigned 32-bit integer size (2^32-1) of 0xffffffff to give us a random number between 0 and 1.我们可以使用 crypto.randomBytes() 生成 4 个随机字节(32 位)的数组,然后除以 0xffffffff 的最大无符号 32 位整数大小(2^32-1),得到一个介于 0 和1.

One could potentially use more than 4 bytes, eg perhaps use 8 bytes.一个人可能会使用超过 4 个字节,例如可能使用 8 个字节。 This would, in principal be more secure.这原则上会更安全。

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