Node.js 中的 crypto.createHmac() 方法
crypto.createHmac() 方法创建一个 Hmac 对象,然后返回该对象。此 Hmac 使用传递的算法和密钥。可选选项将用于控制流行为。定义的密钥将用于生成 HMAC 加密哈希的 HMAC 密钥。
语法
crypto.createHmac(algorithm, key, [options])
参数
以上参数的说明如下 −
算法 – 此算法用于生成 Hmac 对象。输入类型为字符串。
密钥 – 用于生成 HMAC 加密哈希的 Hmac 密钥。
选项 – 这些是可选参数,可以用于控制流行为。
编码 – 要使用的字符串编码。
示例
创建一个名为 createHmac.js 的文件并复制下面的代码段。创建文件后,使用以下命令运行此代码,如下面的示例中所示 −
node createHmac.js
createHmac.js
// crypto.createHmac() demo example
// Importing the crypto module
const crypto = require('crypto');
// Defining the secret key
const secret = 'TutorialsPoint';
// Initializing the createHmac method using secret
const hmacValue = crypto.createHmac('sha256', secret)
// Data to be encoded
.update('Welcome to TutorialsPoint !')
// Defining encoding type
.digest('hex');
// Printing the output
console.log("Hmac value Obtained is: ", hmacValue);输出
C:\home
ode>> node createHmac.js Hmac value Obtained is: dd897f858bad70329fad82087110059f5cb920af2736d96277801f70bd57618e
示例
我们来看一个示例。
// crypto.createHmac() demo example
// Importing the crypto & fs module
const crypto = require('crypto');
const fs = require('fs');
// Getting the current file path
const filename = process.argv[1];
// Creting hmac for current path using secret
const hmac = crypto.createHmac('sha256', "TutorialsPoint");
const input = fs.createReadStream(filename);
input.on('readable', () => {
// Reading single element produced by hmac stream.
const val = input.read();
if (val)
hmac.update(val);
else {
console.log(`${hmac.digest('hex')} ${filename}`);
}
});输出
C:\home
ode>> node createHmac.js 0489ce5e4bd940c06253764e03927414f79269fe4f91b1c75184dc074fa86e22 /home/node/test/createHmac .js
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP