Node.js | crypto.randomBytes() Method

The crypto.randomBytes() method is used to generate a cryptographically well-built artificial random data and the number of bytes to be generated in the written code.

Syntax:

crypto.randomBytes( size, callback )

Parameters: This method accept two parameters as mentioned above and described below:

  • size: It is of type number which indicates the number of bytes to be generated.
  • callback: It is a function which is made of two parameters namely, err and buf. However, if a callback function is available in the stated code then the bytes are generated asynchronously else these bytes are generated synchronously.

Return Type: It returns a Buffer if the callback function is given.

Below example illustrate the use of crypto.randomBytes() method in Node.js:



Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Node.js program to demonstrate the 
// crypto.randomBytes() method
  
// Including crypto module
const crypto = require('crypto');
  
// Calling randomBytes method with callback
crypto.randomBytes(127, (err, buf) => {
  
  if (err) 
  {
    // Prints error
    console.log(err);
  }
  else
  {
  
  // Prints random bytes of generated data
  console.log("The random data is: "
             + buf.toString('hex'));
    }
});

chevron_right


Output: Here, callback function is provided so random bytes are generated synchronously.

The random data is: 074e48c8e3c0bc19f9e22dd7570037392e5d0bf80cf9dd51bb7808872a511b3
c1cd91053fca873a4cb7b2549ec1010a9a1a4c2a6aceead9d115eb9d60a1630e056f3accb10574cd563
371296d4e4e898941231d06d8dd5de35690c4ba94ca12729aa316365145f8a00c410a859c40a46bbb4d
5d51995241eec8f6b7a90415e

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Node.js program to demonstrate the 
// crypto.randomBytes() method
  
// Including crypto module
const crypto = require('crypto');
  
// Calling randomBytes method without callback
const buf = crypto.randomBytes(60); 
  
// Prints random bytes of generated data
console.log("The random bytes of data generated is: "
                + buf.toString('utf8'));

chevron_right


Output: Here, callback function is not provided so bytes are generated synchronously

The random bytes of data generated is: _??i???Z?Z?o?i?W??bEC
?F????#?-??T??jDqmm?v??7?Q?c_G?%?

Reference: https://nodejs.org/api/crypto.html#crypto_crypto_randombytes_size_callback




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.