Firefox Tomorrow

web api instance method

Crypto: getRandomValues() method

View on MDN ↗

Available in workers

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 pseudo-random number generator algorithm (PRNG) may vary across user agents, but is suitable for cryptographic purposes.

getRandomValues() is the only member of the Crypto interface which can be used from an insecure context.

Syntax

getRandomValues(typedArray)

Parameters

Return value

The same array passed as typedArray but with its contents replaced with the newly generated random numbers. Note that typedArray is modified in-place, and no copy is made.

Exceptions

Usage notes

Prefer the generateKey() method for key generation, which is guaranteed to be running in a secure context.

There is no minimum degree of entropy mandated by the Web Cryptography specification. User agents are instead urged to provide the best entropy they can when generating random numbers, using a well-defined, efficient pseudorandom number generator built into the user agent itself, but seeded with values taken from an external source of pseudorandom numbers, such as a platform-specific random number function, the Unix /dev/urandom device, or other source of random or pseudorandom data.

Examples

const array = new Uint32Array(10);
self.crypto.getRandomValues(array);

console.log("Your lucky numbers:");
for (const num of array) {
  console.log(num);
}

Specifications

SpecificationsStandards references are available on the canonical MDN page.

Browser compatibility

Browser compatibilityCompatibility data is available on the canonical MDN page.

See also