We had been using Math.random to get random numbers between 4000-64000.:
Math.floor(Math.random() * 60000 + 4000);
We have to now replace this with a more cryptographically secure random number generator. After searching on this issue we have decided to go with window.crypto.getRandomValues. I am not able to figure out how to use this to get a random number between a particular range. Can someone please help out.
A simple replacement for
Math.random
might look like this:To extend this to integers:
To extend this to arrays of integers:
Generate an array of ten integers from 0 to 2 inclusive:
For a given min and max, the formula describes how many bits you'll use on average if you request
u
bits at once and retry if returning the result would introduce bias.Fortunately, the optimal strategy is simply requesting
ceil(log2(max - min + 1))
bits at once. We can only get full bytes withcrypto.getRandomValues
anyways, so if we have one call ofcrypto.getRandomValues
per function call, the best we can do is:If you generate many values, you may consider some optimizations, namely requesting more bytes (i.e. a larger array) in advance. If your range becomes smaller (say you want to flip a coin), than it may also be beneficial to work in a bit-based manner, i.e. request many bits upfront and then only use up the random bits you really need.