Converting random bytes to an integer range - how?

You can get one 32 bit integer from crypto.randomBytes with the code below. If you need more than one you can ask for more bytes from crypto.randomBytes and then use substr to individually select and convert each integer.

crypto.randomBytes(4, function(ex, buf) {
  var hex = buf.toString('hex');
  var myInt32 = parseInt(hex, 16);
});

Having said that, you might want to just use Math.floor(Math.random() * maxInteger)


To obtain a cryptographically secure and uniformly distributed value in the [0,1) interval (i.e. same as Math.random()) in NodeJS

const random = crypto.randomBytes(4).readUInt32LE() / 0x100000000;
console.log(random); //e.g. 0.9002735135145485

or in the Browser

const random = window.crypto.getRandomValues(new Uint32Array(1))[0] / 0x100000000;
console.log(random);