# Generating a Range of Cryptographically Strong Random Numbers in JavaScript

**URL:** <https://forum.kirupa.com/t/generating-a-range-of-cryptographically-strong-random-numbers-in-javascript/652867>\
**Category:** Uncategorized\
**Created:** [July 28, 2022, 8:05pm UTC](https://forum.kirupa.com/t/generating-a-range-of-cryptographically-strong-random-numbers-in-javascript/652867 "2022-07-28T20:05:09Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![kirupa](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/kirupa/32/11616_2.png) [@kirupa](https://forum.kirupa.com/u/kirupa)\
**Post date:** [July 28, 2022, 8:05pm UTC](https://forum.kirupa.com/t/generating-a-range-of-cryptographically-strong-random-numbers-in-javascript/652867/1 "2022-07-28T20:05:09Z")

</div>

As part of making modifications to the existing [Random Numbers article](https://www.kirupa.com/html5/random_numbers_js.htm), 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:

```auto
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](https://www.kirupa.com/html5/random_numbers_js.htm#cryptoRandom)

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:

 ![image](https://canada1.discourse-cdn.com/flex011/uploads/kirupa/original/3X/d/1/d178efaeb0679e324b8e95c4b4e6ec9ed873d7a6.png)
