crypto.randomFillSync() Method in Node.js

Node.jsJavascriptWeb DevelopmentFront End Technology

The crypto.randomFillSync() method takes a buffer argument and returns the buffer by filling it with its encrypted value. As the name suggests, this will be a sync process.

Syntax

crypto.randomFillSync(buffer, [offset], [size])

Parameters

The above parameters are described as below −

  • buffer – This field contains the data content. Possible buffer types are: string, TypedArray, Buffer, ArrayBuffer, DataView. The size of the buffer cannot be greater than 2**31-1.

  • offset – The value of the offset from where randomFill will start. Default value is 0.

  • size – The size of the buffer after the offset, i.e., (buffer.length-offset). This value cannot be greater than 2**31-1.

Example

Create a file with name – randomFillSync.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 randomFillSync.js

randomFillSync.js

// crypto.randomFillSync() Example Demo

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

// Defining buffer length
const buffer = Buffer.alloc(15);

// Buffer
console.log(crypto.randomFillSync(buffer).toString('base64'));

// Buffer and Offset
crypto.randomFillSync(buffer, 4);
console.log(buffer.toString('base64'));

// Buffer, offset and size
crypto.randomFillSync(buffer, 4, 4);
console.log(buffer.toString('base64'));

Output

C:\home\node>> node randomFillSync.js
wVBZ+i/nvmL3Ce4kBOl0
wVBZ+hkP5DB/4Ci8yTGs
wVBZ+stVWJZ/4Ci8yTGs

Example

Let's take a look at one more example.

// crypto.randomFillSync() Example Demo

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

// Creating TypedArray instance i.e, Int8Array
const data = new Int8Array(16);

// Buffer, offset and size
console.log(Buffer.from(crypto.randomFillSync(data).buffer, data.byteOffset, data.byteLength).toString('base64'));

console.log();

// Creating a TypedArray instance i.e, BigInt64Array
const data2 = new BigInt64Array(4);
console.log(Buffer.from(crypto.randomFillSync(data2).buffer, data2.byteOffset, data2.byteLength).toString('ascii'));

console.log();

// Creating a DataView instance
const data3 = new DataView(new ArrayBuffer(7));
console.log(Buffer.from(crypto.randomFillSync(data3).buffer, data3.byteOffset, data3.byteLength).toString('hex'));

Output

C:\home\node>> node randomFillSync.js
iNm8tiwDATcV6I8xjTSTbQ==

ra+I=(6&Xse"�hjw?!EO?D#S7M

d957fb1dbdfa00
raja
Published on 20-May-2021 12:58:22
Advertisements