Get Random Numbers, Cryptographically Secure, in Javascript

javascript
Published on March 9, 2020

Random numbers that are cryptographically strong, can be generated in Javascript using the Web Crypto API.

Math.rand() is the most popular and easiest way to generate random numbers in Javascript.

However the Web Crypto API provides another method to generate random numbers that are cryptographically strong. This is cryptoOb.getRandomValues() method.

// global Crypto object
var crypto = window.crypto;

// we need 5 positive random numbers, each 8-bit (255 max value)  
var numbers = new Uint8Array(5);

// fill array with random numbers
window.crypto.getRandomValues(numbers);

// random numbers 
for(var i=0; i<numbers.length; i++) {
	console.log(numbers[i]);
}

The getRandomValues() method takes a typed array as parameter. All elements of the typed array are going to be filled with random numbers. If only a single random number is required, the length of the array should be 1.

Typed arrays can be :

  • Int8Array — 8-bit integer typed array. Random numbers will be between -127 to 127
  • Uint8Array — 8-bit unsigned integer typed array. Random numbers will be between 0 to 255
  • Int16Array — 16-bit integer typed array. Random numbers will be between -32768 to 32767
  • Uint16Array — 16-bit unsigned integer typed array. Random numbers will be between 0 to 65535
  • Int32Array — 32-bit integer typed array. Random numbers will be between -2147483648 to 2147483647
  • Uint32Array — 32-bit unsigned integer typed array. Random numbers will be between 0 to 4294967295

Useful Resources

In this Tutorial