NodeJS - crypto.getRandomValues() Method


The NodeJs Crypto getRandomValues() method is used to fill the specified typed array with cryptographically secure random values. These secure random values are generated by the method and then filled into the specified typed array.

A secure random number is a number that is generated randomly in a way that it is not bound by any factor, it is highly unpredictable and can be used in security-sensitive applications such as generating cryptographic keys, strong passwords, or digital signatures.

The TypedArrays are array-like objects that provide a mechanism for reading and writing raw binary data in memory buffers. They can be any of the typed array types such as Int8Array, Int16Array, or Int32Array.

Here are some important points to remember when using this method:

  • The provided TypedArray must be an integer type.
  • If the size of the TypedArray is larger than 65,536 bytes, this method will throw an error.

Syntax

Following is the syntax of the NodeJs Crypto.getRandomValues() method −

Crypto.getRandomValues(typedarray)

Parameters

This method accepts a single parameter named 'typedarray', which is described below −

  • typedarray − It is a typedarray where the random values need to fill.

Return value

This method returns the same typed array that was passed to it, filled with random values.

Example 1

The following is the basic example of the NodeJs crypto.getRandomValues() Method.

const crypto = require('crypto');

// Creating a Uint8Array with 5 elements
const array = new Uint8Array(5);

// Filling the array with random values
crypto.randomFillSync(array);

console.log(array); // prints the array of 5 random numbers

Output

The above program produces the following output −

Uint8Array(5) [ 66, 92, 165, 91, 88 ]

Example 2

The following is another example of the NodeJs crypto getRandomValues() method. We use this method to fill the 10 random values to the specified typedarray(int32array).

const crypto = require('crypto');

// Creating a Int32Array with 10 elements
const array = new Int32Array(10);

// Filling the array with random values
crypto.randomFillSync(array);

console.log(array); // prints the array of 10 random numbers

Output

The above program produces the following output −

Int32Array(10) [
  -1965795337, -1818733850,
   2025232344, -1120136716,
   1293668707, -1440944093,
   1948921771,   444689755,
   -975518890,   136290660
]

Example 3

If the specified typedarray size is larger than the 65,536 bytes, it throws an error.

In the example below we use the crypto getRandomValues() method to to fill the random values to the specified typedarray.

const { webcrypto } = require('crypto');

function generateLargeRandomValues(byteLength) {
  const chunkSize = 65537; // larger than 65536 bytes
  const numChunks = Math.ceil(byteLength / chunkSize);
  const remainder = byteLength % chunkSize;
  
  // Create a buffer to hold the entire result
  const resultBuffer = new Uint8Array(byteLength);

  // Generate random values for each chunk
  for (let i = 0; i < numChunks; i++) {
    const start = i * chunkSize;
    const end = (i + 1) * chunkSize > byteLength ? byteLength : (i + 1) * chunkSize;
    const currentChunkSize = end - start;
    
    const tempBuffer = new Uint8Array(currentChunkSize);
    webcrypto.getRandomValues(tempBuffer);
    
    resultBuffer.set(tempBuffer, start);
  }

  return resultBuffer;
}

const largeRandomValues = generateLargeRandomValues(100000);
console.log(largeRandomValues);

Output

After executing the above program it will display the following output −

node:internal/crypto/random:322
    throw lazyDOMException(
    ^

DOMException [QuotaExceededError]: The requested length exceeds 65,536 bytes
    at Crypto.getRandomValues (node:internal/crypto/random:322:11)
    at generateLargeRandomValues (/index.js:18:15)
    at Object. (/index.js:26:27)
    at Module._compile (node:internal/modules/cjs/loader:1103:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1157:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
    at node:internal/main/run_main_module:17:47
nodejs_crypto.htm
Advertisements