# Generating Cryptographically Secure Random Numbers in Vanilla JavaScript

Learn how to generate cryptographically secure random numbers in vanilla JavaScript.
Written by Maxwell Pelic,

Ever wonder how to get cryptographically random numbers in JavaScript? No? Either way, today is your lucky day, because I’m going to show you how to do it.

## The Problem

Although you may be temped to just use the `Math.random()` function to create random numbers, it’s not technically cryptographically secure. That means, although difficult, it’s possible to predict how that function will behave and what numbers it will generate.

## The Solution

Luckily, there’s a simple solution to this problem. You can use the `crypto.getRandomValues()` function to generate cryptographically secure random numbers. This function is available in all modern browsers, and it’s also available in Node.js.

## Usage

Let’s generate a random password using the crypto library. First, we’ll define the characters allowed in the password:

``````const PASSWORD_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#\$%^&*()_+ -=[]{}|;':,./<>?";
``````

Next, we’ll make a function that generates a random number in a given range:

``````const random_range = (minimum, maximum) => {

if(!window.crypto) throw new Error("Crypto library not available");

//check that the provided values are valid
if(minimum >= maximum) throw new Error("Minimum must be less than maximum");
if(maximum - minimum > 255) throw new Error("Maximum range must be less than 256");

//get random byte
let random_byte = new Uint8Array(1);
crypto.getRandomValues(random_byte);

const result = random_byte + minimum;

//rejection sampling
if(result > maximum) return random_range(minimum, maximum);
else return result;
}
``````

Finally, let’s make a function to generate a random string:

``````const random_string = (length) => {

//check that the provided values are valid
if(length < 1) throw new Error("Length must be greater than 0");

let result = "";

for(let i = 0; i < length; i++) {
}

return result;
}
``````

Now, we can generate a random password:

``````const password = random_string(16);
``````

## Example

Here’s an example of a random password generated using the code above:

Previous Article: Copilot

Next Article: I Made a Chess game in JavaScript