13

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?

1
  • 1
    This question might help: stackoverflow.com/questions/15753019/… If you can get that working you can do Math.floor(randomFloat() * maxInteger) to get an integer between 0 and (maxInteger - 1). Commented Apr 4, 2013 at 20:58

3 Answers 3

17

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)

Sign up to request clarification or add additional context in comments.

2 Comments

Just what I needed, thanks! Here's the one-line version: parseInt(crypto.randomBytes(4).toString('hex'), 16);
A good reason to use crypto.randomBytes() insteaad of just Math.random is becuase of this cwe.mitre.org/data/definitions/330.html
7

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

Comments

4
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

1 Comment

Looks like it's cryptographically secure as well

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.