Node.js – hmac.update() 方法

HMAC类是用于创建加密HMAC摘要的许多公用事业类之一。该方法用于使用传递的数据更新 Hmac 内容。如果未提供编码且数据为字符串格式,则强制使用默认编码 ' utf8 '。Hmac.update()

语法

hmac.update(data, [encoding])

参数

参数说明如下:

  • data - 此输入参数接受将更新 Hmac 的数据的输入。

  • encoding - 此输入参数接受在更新 Hmac 时要考虑的编码的输入。

示例 1

创建一个名为“ hmacUpdate.js ”的文件并复制以下代码片段。创建文件后,使用命令“ node hmacUpdate.js ”运行此代码。

// Hmac.digest() 演示示例

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

// 使用编码和密钥初始化 Hmac 对象
const hmac = crypto.createHmac('sha256', 'secretKey');

// 使用以下数据更新 hmac
hmac.update('Welcome');
hmac.update('To');
hmac.update('nhooo')

// 使用摘要打印 hmac 值
console.log("Hmac是: " + hmac.digest('hex'))
输出结果
C:\home\node>> node hmacUpdate.js
Hmac是: 641538b74bf1a59cd9a5cbd97dd0cf3b76b572e17432997230ae346feb41d149

示例 2

// Hmac.digest() 演示示例

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

// 使用编码和密钥初始化 Hmac 对象
const hmac = crypto.createHmac('sha256', 'secretKey');
const hmac1 = crypto.createHmac('sha256', 'secretKey');
const hmac2 = crypto.createHmac('sha256', 'secretKey');
// 使用以下数据更新 hmac
hmac.update('nhooo');
hmac1.update('nhooo');
hmac2.update('nhooo');

// 使用不同的摘要打印 hmac 值
console.log("Hmac(with hex Encoidng) is: " + hmac.digest('hex'))

console.log("Hmac(with Base64 Encoding) is: " + hmac1.digest('base64'))

console.log("Hmac(with Default Encoding) is: " + hmac2.digest())
输出结果

C:\home\node>> node hmacUpdate.jsHmac(with hex Encoidng) is: 9534f1298c89fcd4e42e3fecbb26ac66148a1a607e6fb122ef0af4859f9eb0e5
Hmac(with Base64 Encoding) is: lTTxKYyJ/NTkLj/suyasZhSKGmB+b7Ei7wr0hZ+esOU=Hmac(with Default Encoding) is: �4�)�����.?�&�f��`~o�"�