Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make crypto.randomBytes() to replace Math.random()

Tags:

node.js

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)

like image 846
samol Avatar asked Oct 11 '25 23:10

samol


1 Answers

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.

like image 55
Sigmatics Avatar answered Oct 14 '25 14:10

Sigmatics