📜  Node.js hmac.digest() 方法(1)

📅  最后修改于: 2023-12-03 14:44:39.068000             🧑  作者: Mango

Node.js hmac.digest() 方法

hmac.digest() 方法是 Node.js 中用于计算 HMAC(Hash-based Message Authentication Code)摘要的一个方法。HMAC 是一种使用哈希函数与签名密钥对消息进行完整性验证和认证的算法。

语法
hmac.digest([encoding])
参数
  • encoding(可选):指定摘要结果的编码格式,默认为 'hex'
返回值
  • 返回一个计算完成的 HMAC 摘要结果,根据指定的编码格式进行编码。
示例

以下示例演示了如何使用 hmac.digest() 方法计算 HMAC 摘要结果:

const crypto = require('crypto');

const secretKey = "mySecretKey";
const message = "Hello, World!";
const hmacAlgorithm = 'sha256';

const hmac = crypto.createHmac(hmacAlgorithm, secretKey);
hmac.update(message);
const digest = hmac.digest();

console.log(digest);

上述示例中,我们首先导入 crypto 模块,该模块为我们提供了加密和解密功能。然后,我们定义了一个使用的秘钥 secretKey,一个消息 message,以及指定的 HMAC 哈希算法 hmacAlgorithm(常用的有 'sha256''sha512' 等)。

接下来,我们通过 crypto.createHmac() 方法创建了一个 HMAC 对象,并传入了 HMAC 算法和秘钥。然后,我们调用 hmac.update() 方法来更新 HMAC 对象的内容为我们的消息,并最后调用 hmac.digest() 方法来获取计算完成的摘要结果。

最后,我们将摘要结果打印到控制台。

补充说明

hmac.digest() 方法生成的摘要结果是二进制数据。如果指定了 encoding 参数,摘要结果会被编码为指定的格式,常用的编码格式有 'hex''base64' 等。

如果需要将二进制数据转换为字符串格式的摘要结果,可以使用以下代码片段:

const digestString = digest.toString('encoding');
参考文档