Node.js crypto.randomFillSync() Method
Last Updated :
11 Oct, 2021
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:
- buffer This parameter holds Buffer, TypedArray, or DataView type of data.
- offset: It is a number whose default value is 0.
- size: It is a number whose default value is (buffer.length – offset).
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:
javascript
const crypto = require( 'crypto' );
const buffer = Buffer.alloc(15);
console.log(crypto.randomFillSync(buffer).toString( 'ascii' ));
crypto.randomFillSync(buffer, 4);
console.log(buffer.toString( 'base64' ));
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:
javascript
const crypto = require( 'crypto' );
const x = new Int8Array(5);
console.log(Buffer.from(crypto.randomFillSync(x).buffer,
x.byteOffset, x.byteLength).toString( 'base64' ));
console.log();
const y = new BigInt64Array(4);
console.log(Buffer.from(crypto.randomFillSync(y).buffer,
y.byteOffset, y.byteLength).toString( 'ascii' ));
console.log();
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
Share your thoughts in the comments
Please Login to comment...