简体   繁体   中英

Equivalent of window.crypto() in node.js

I am trying to convert this into a node.js script. 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.

I tried using some of the answers from this question , but none of them are working. 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.

Specifically, I am looking for a node.js version of this portion of code:

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.

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.

One could potentially use more than 4 bytes, eg perhaps use 8 bytes. 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()));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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