Node.js 中的 crypto.randomFill() 方法

无论是方法和方法几乎是相同的。两者之间的唯一区别是——在方法中,第一个参数是一个将被填充的缓冲区。它还有一个回调方法,只有在配置了回调时才会在遇到错误时调用。crypto.randomFill()crypto.randomBytes()randomFill()

语法

crypto.randomFill(buffer, [offset], [size], [callback])

参数

上述参数描述如下 -

  • 缓冲区 ——该字段包含数据内容。可能的缓冲区类型有:string、TypedArray、Buffer、ArrayBuffer、DataView。缓冲区的大小不能大于 2**31-1。

  • offset  – 从 randomFill 开始的偏移值。默认值为 0。

  • size  – 偏移后缓冲区的大小。即(buffer.length-offset)。该值不能大于 2**31-1。

  • callback  – 抛出错误时将调用的函数。

示例

创建一个具有名称的文件 -randomFill.js并复制以下代码片段。创建文件后,使用以下命令运行此代码,如下例所示 -

node randomFill.js

随机填充.js

//Node.jsprogram 演示了 crypto.randomFill() 方法的流程

// 导入加密模块
const crypto = require('crypto');
const fs = require("fs");

// 初始化缓冲区字节值
const buf = Buffer.alloc(6);

// 使用缓冲区和回调调用 randomFill 方法
crypto.randomFill(buf, (err, buf) => {
   if (err) throw err;
   // 填充后打印缓冲区数据值
   console.log(buf.toString('ascii'));
});

//使用上面定义的所有参数调用 randomFill
crypto.randomFill(buf, 3, 2, (err, buf) => {
   if (err) throw err;
   // 打印缓冲区中的新随机数据
   console.log(buf.toString('base64'));
});

// 我们可以看到以下函数的输出是相同的
crypto.randomFill(buf, 3, 3, (err, buf) => {
   if (err) throw err;
   console.log(buf.toString('base64'));
});
输出结果
C:\home\node>> node randomFill.js
f!]"+–
ZqHdoit8
ZqHdoit8

示例

让我们再看一个例子。

//Node.jsprogram 演示了 crypto.randomFill() 方法的流程

// 导入加密模块
const crypto = require('crypto');
const fs = require("fs");

// 初始化缓冲区字节值 using data view
const data = new DataView(new ArrayBuffer(16));

// 使用缓冲区和回调调用 randomFill 方法
crypto.randomFill(data, (err, buf) => {
   if (err) throw err;
   // 使用编码打印 randomFill 数据
   console.log(Buffer.from(buf.buffer,
      buf.byteOffset, buf.byteLength).toString('ascii'));
});
输出结果
C:\home\node>> node randomFill.js
>h(Be#D8h0