Reputation: 20590
I need a cryptographically secure random number generator to replace Math.random()
I came across crypto.randomBytes()
however, it returns a byte array. What is a way to make the byte array into 0-1 ( so that it is compatible with Math.random
)
Upvotes: 4
Views: 2880
Reputation: 99
For reactJS or node JS server side we can do as mention below
Below code will always return under the 100000
const crypto = require('crypto');
crypto.randomBytes(1)[0] * 200
It will also return always under the 100000
Math.floor(Math.random() * 100000)
Upvotes: 0
Reputation: 793
This should do the trick:
crypto.randomBytes(4).readUInt32LE() / 0xffffffff;
randomBytes generates 4 random bytes, which are then read as a 32-bit unsigned integer in little endian. The max value of a 32bit unsigned int is 0xffffffff (or 4,294,967,295 in decimal). By dividing the randomly generated 32bit int by its max value you get a value between 0 and 1.
Upvotes: 4
Reputation: 106696
You could do something like:
var randomVal = (crypto.randomBytes(1)[0] / 255);
Upvotes: -1