Open In App

Node.js crypto.randomFillSync() Method

The crypto.randomFillSync() method is an inbuilt application programming interface of crypto module which is used to return the object passed as buffer argument.
Syntax: 
 

crypto.randomFillSync( buffer, offset, size )

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



Return Value: It returns Buffer, TypedArray, or DataView type of data.
Below example illustrate the use of crypto.randomFillSync() method in Node.js:
Example 1: 
 




// Node.js program to demonstrate the 
// crypto.randomFillSync() method
  
// Including crypto module
const crypto = require('crypto');
  
// Defining buffer
const buffer = Buffer.alloc(15);
  
// Calling randomFillSync method with only 
// one parameter, buffer
console.log(crypto.randomFillSync(buffer).toString('ascii'));
  
// Calling randomFillSync method with 
// two parameters, buffer and offset
crypto.randomFillSync(buffer, 4);
console.log(buffer.toString('base64'));
  
// Calling randomFillSync method with three 
// parameters, buffer, offset and size
crypto.randomFillSync(buffer, 4, 4);
console.log(buffer.toString('base64'));

Output: 
 



+~`Ld#%KT&6VF1e
K/7gTBXCFISh30dPoE5o
K/7gTO7iUG+h30dPoE5o

Here, the last two values are same.
Example 2: 
 




// Node.js program to demonstrate the 
// crypto.randomFillSync() method
  
// Including crypto module
const crypto = require('crypto');
  
// Creating TypedArray instance i.e, Int8Array
const x = new Int8Array(5);
  
// Calling randomFillSync with all its parameter
console.log(Buffer.from(crypto.randomFillSync(x).buffer,
         x.byteOffset, x.byteLength).toString('base64'));
  
console.log();
  
// Creating TypedArray instance i.e, BigInt64Array
const y = new BigInt64Array(4);
console.log(Buffer.from(crypto.randomFillSync(y).buffer,
          y.byteOffset, y.byteLength).toString('ascii'));
console.log();
  
// Creating a DataView instance
const z = new DataView(new ArrayBuffer(7));
console.log(Buffer.from(crypto.randomFillSync(z).buffer,
            z.byteOffset, z.byteLength).toString('hex'));

Output: 
 

BQrDFc8=

EM4;)N+.qY, o-kp:b:C.

479eb4d9175221

Here, any TypedArray, or DataView instance is passed as buffer.
Reference: https://nodejs.org/api/crypto.html#crypto_crypto_randomfillsync_buffer_offset_size
 


Article Tags :