Javascript: generate random number within the range of crypto.getRandomValues

As far as I understand, you can generate a random number in JavaScript within a range using this function:

function getRandomInt (min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } 

Courtesy of IonuΕ£ G. Stan here .

What I want to know is that you can generate the best random number in a range using crypto.getRandomValues ​​() instead of Math. randomly(). I would like to be able to generate a number from 0 to 10 inclusive, or 0 - 1, or even 10 - 5000 inclusive.

You will notice that Math.random () creates a number like: 0.8565239671015732 .

The getRandomValues ​​API might return something like:

  • 231 with Uint8Array(1)
  • 54328 with Uint16Array(1)
  • 355282741 with Uint32Array(1) .

So, how do I translate this back to decimal so that I can stick to the same range algorithm above? Or do I need a new algorithm?

Here is the code I tried, but it does not work too well.

 function getRandomInt(min, max) { // Create byte array and fill with 1 random number var byteArray = new Uint8Array(1); window.crypto.getRandomValues(byteArray); // Convert to decimal var randomNum = '0.' + byteArray[0].toString(); // Get number in range randomNum = Math.floor(randomNum * (max - min + 1)) + min; return randomNum; } 

At the lower end (range 0 - 1), it returns more than 0 than 1. What is the best way to do this with getRandomValues ​​()?

Many thanks

+8
javascript random cryptography range
source share
2 answers

The easiest way is probably to filter the cull (see http://en.wikipedia.org/wiki/Rejection_sampling ). For example, assuming max - min less than 256:

 function getRandomInt(min, max) { // Create byte array and fill with 1 random number var byteArray = new Uint8Array(1); window.crypto.getRandomValues(byteArray); var range = max - min + 1; var max_range = 256; if (byteArray[0] >= Math.floor(max_range / range) * range) return getRandomInt(min, max); return min + (byteArray[0] % range); } 
+11
source share

IMHO, the easiest way to generate a random number in the range [min..max] with window.crypto.getRandomValues() described here .

ECMAScript 2015 syntax if link TL, TR:

 function getRandomIntInclusive(min, max) { const randomBuffer = new Uint32Array(1); window.crypto.getRandomValues(randomBuffer); let randomNumber = randomBuffer[0] / (0xffffffff + 1); min = Math.ceil(min); max = Math.floor(max); return Math.floor(randomNumber * (max - min + 1)) + min; } 
+1
source share

All Articles