Generating a Range of Cryptographically Strong Random Numbers in JavaScript

As part of making modifications to the existing Random Numbers article, I added a section on generating a random number in a more cryptographically sound way!

The following snippet shows the cryptoRandom function and how we can use it to generate a range of cryptographically strong random numbers:

function cryptoRandom() {
  let initial = new Uint32Array(1);
  window.crypto.getRandomValues(initial);

  return initial[0] / (0xFFFFFFFF + 1);
}

function getSecureRandomNumber(low, high) {
  let r = Math.floor(cryptoRandom() * (high - low + 1)) + low;
  return r;
}

// Random number between 0 and 10 (inclusive)
let foo = getSecureRandomNumber(0, 10);
console.log(foo);

// Random number between 0 and 100 (inclusive)
let bar = getSecureRandomNumber(0, 100);
console.log(bar);

// Random number between 5 and 25 (inclusive)
let zorb = getSecureRandomNumber(5, 25);
console.log(zorb);

You can see this covered more fully with a larger working example here: Random Numbers in JavaScript

The thing to keep in mind is that this cryptoRandom function can be substituted anywhere you would use Math.random. What it returns is a number between 0 and almost 1:

1 Like