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