Computer >> Computer tutorials >  >> Programming >> Javascript

crypto.randomBytes() Method in Node.js


The crypto.randomBytes() generates cyprtographically strong pseudo-random data. This method will not be completed until there is sufficient entropy in the bytes created. But even after this it does not takes more than a few milliseconds. This method basically creates a few random bytes which are further used.

Syntax

crypto.randomBytes(size, [callback])

Parameters

The above parameters are described as below −

  • size – This argument defines the number of bytes to be generated. Size must not be greater than 2**31 – 1.

  • callback – The callback is called if any error occurs in the method.

Example

Create a file with name – randomBytes.js and copy the below code snippet. After creating file, use the following command to run this code as shown in the example below −

node randomBytes.js

randomBytes.js

// crypto.randomBytes() Asynchronous demo example

// Importing the crypto module
const crypto = require('crypto');

crypto.randomBytes(64, (err, buf) => {
   if (err) throw err;
   console.log(`${buf.length} bytes of random data: ${buf.toString('hex')}`);
});

Output

C:\home\node>> node randomBytes.js
64 bytes of random data:
eb2bcebb999407286caea729998e7fa0c089178f8ca43857e73ea3ff66dbe1852af24a4b0199be
9192798a3f8ad6d6475db3621cfacf38dcb0fba5d77d73aaf5

Example

Let's take a look at one more example.

// crypto.randomBytes() Synchronous demo example

// Importing the crypto module
const crypto = require('crypto');

const buffer = crypto.randomBytes(256);
console.log(
   `${buffer.length} bytes of random data: ${buffer.toString('base64')}`);

Output

C:\home\node>> node randomBytes.js
256 bytes of random data:
n7yfRMo/ujHfBWSF2VFdevG4WRbBoG9Fqwu51+/9ZBUV6Qo88YG7IbcEaIer+g+OgjMv4RyNQ6/67a
F5xWmkOR3oA6J6bdAJ1pbstTuhIfItF1PQfP26YXk1QlaoKy/YJxPUngyK4kNG9O04aret4D+2qIq9
BUaQcv+R9Xi014VKNUDZ+YQKEaLHBhJMq6JgehJ56iNbdNJ4+PN7SQwjNdZ8gS76izAwYsSZ7Kuyx2
VzdXIKsLmjleuJ2DZ7/6Yyn8WM9463dhuh0KQ5nwFbgzucvjmdvDjBlGFZBGlKs6AXqYh+0Oe6Ckkv
3OpnXOJs+GExbmnvjaeDQ03khpdJfA==