Crypto.getRandomValues()

The Crypto.getRandomValues() method lets you get cryptographically strong random values. The array given as the parameter is filled with random numbers (random in its cryptographic meaning).

To guarantee enough performance, implementations are not using a truly random number generator, but they are using a pseudo-random number generator seeded with a value with enough entropy. The PRNG used differs from one implementation to the other but is suitable for cryptographic usages. Implementations are also required to use a seed with enough entropy, like a system-level entropy source.

Syntax

cryptoObj.getRandomValues(typedArray);

Parameters

typedArray
Is an integer-based TypedArray, that is an Int8Array, a Uint8Array, an Int16Array, a Uint16Array, an Int32Array, or a Uint32Array. All elements in the array are going to be overwritten with random numbers.

Exceptions

Examples

/* Assuming that window.crypto.getRandomValues is available */

var array = new Uint32Array(10);
window.crypto.getRandomValues(array);

console.log("Your lucky numbers:");
for (var i = 0; i < array.length; i++) {
  console.log(array[i]);
}

For a more secure implementation of Math.random, you could try this:

function secureMathRandom() {
  // Divide a random UInt32 by the maximum value (2^32 -1) to get a result between 0 and 1
  return window.crypto.getRandomValues(new Uint32Array(1))[0] / 4294967295;
}

Specification

Specification Status Comment
Web Cryptography API Recommendation Initial definition

Browser compatibility

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
getRandomValuesChrome Full support 11Edge Full support 12Firefox Full support 26IE Full support 11Opera Full support 15Safari Full support 6.1WebView Android Full support YesChrome Android Full support 18Firefox Android Full support 26Opera Android Full support 14Safari iOS Full support 6.1Samsung Internet Android Full support Yes

Legend

Full support  
Full support

See also