Node.js 中的 crypto.randomFillSync() 方法
该方法接受一个缓冲区参数并通过用其加密值填充缓冲区来返回缓冲区。顾名思义,这将是一个同步过程。crypto.randomFillSync()
语法
crypto.randomFillSync(buffer, [offset], [size])
参数
上述参数描述如下-
缓冲区 ——该字段包含数据内容。可能的缓冲区类型有:string、TypedArray、Buffer、ArrayBuffer、DataView。缓冲区的大小不能大于2**31-1。
offset –从randomFill开始的偏移值。默认值为0。
size –偏移后缓冲区的大小,即(buffer.length-offset)。该值不能大于2**31-1。
示例
创建一个具有名称的文件-randomFillSync.js并复制以下代码片段。创建文件后,使用以下命令运行此代码,如下例所示-
node randomFillSync.js
随机填充同步.js
//crypto.randomFillSync()示例演示
//导入加密模块
const crypto = require('crypto');
//定义缓冲区长度
const buffer = Buffer.alloc(15);
//缓冲
console.log(crypto.randomFillSync(buffer).toString('base64'));
//缓冲 and Offset
crypto.randomFillSync(buffer, 4);
console.log(buffer.toString('base64'));
//缓冲, offset and size
crypto.randomFillSync(buffer, 4, 4);
console.log(buffer.toString('base64'));输出结果C:\home\node>> node randomFillSync.js wVBZ+i/nvmL3Ce4kBOl0 wVBZ+hkP5DB/4Ci8yTGs wVBZ+stVWJZ/4Ci8yTGs
示例
让我们再看一个例子。
//crypto.randomFillSync()示例演示
//导入加密模块
const crypto = require('crypto');
//创建TypedArray实例,即Int8Array
const data = new Int8Array(16);
//缓冲, offset and size
console.log(Buffer.from(crypto.randomFillSync(data).buffer, data.byteOffset, data.byteLength).toString('base64'));
console.log();
//创建一个TypedArray实例,即BigInt64Array
const data2 = new BigInt64Array(4);
console.log(Buffer.from(crypto.randomFillSync(data2).buffer, data2.byteOffset, data2.byteLength).toString('ascii'));
console.log();
//创建DataView实例
const data3 = new DataView(new ArrayBuffer(7));
console.log(Buffer.from(crypto.randomFillSync(data3).buffer, data3.byteOffset, data3.byteLength).toString('hex'));输出结果C:\home\node>> node randomFillSync.js iNm8tiwDATcV6I8xjTSTbQ== ra+I=(6&Xse"�hjw?!EO?D#S7M d957fb1dbdfa00