简体   繁体   中英

Converting random bytes to an integer range - how?

I'm trying to get a random integer within a range by reading from crypto.randomBytes().

Now, my problem is that I do not know how to read integers from that byte stream. I imagine generating a range is simply a matter of 'throwing away' the ints not in range.

Any ideas?

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 (ie 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);

const { randomInt } = await import('crypto');

const n = randomInt(1, 7);
console.log(`The dice rolled: ${n}`);

Now it is implemented in node itself https://nodejs.org/api/crypto.html#crypto_crypto_randomint_min_max_callback

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