Node.js crypto.randomFillSync() 方法
crypto.randomFillSync() 方法是加密模块的内置应用程序编程接口,用于返回作为缓冲区参数传递的对象。
句法:
crypto.randomFillSync( buffer, offset, size )
参数:此方法接受三个参数,如上所述,如下所述:
- buffer该参数保存 Buffer、TypedArray 或 DataView 类型的数据。
- offset:它是一个数字,默认值为 0。
- size:它是一个数字,其默认值为(buffer.length – offset) 。
返回值:返回Buffer、TypedArray或DataView类型的数据。
下面的示例说明了在 Node.js 中使用crypto.randomFillSync() 方法:
示例 1:
javascript
// 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'));
javascript
// 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'));
输出:
+~`Ld#%KT&6VF1e
K/7gTBXCFISh30dPoE5o
K/7gTO7iUG+h30dPoE5o
在这里,最后两个值是相同的。
示例 2:
javascript
// 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'));
输出:
BQrDFc8=
EM4;)N+.qY, o-kp:b:C.
479eb4d9175221
在这里,任何TypedArray 或 DataView实例都作为缓冲区传递。
参考: https://nodejs.org/api/crypto.html#crypto_crypto_randomfillsync_buffer_offset_size