Node.js 中的 crypto.createHmac() 方法
该方法将创建一个Hmac对象,然后返回它。这个Hmac使用传递的算法和密钥。可选选项将用于控制流行为。定义的密钥将是用于生成加密HMAC哈希的HMAC密钥。crypto.createHmac()
语法
crypto.createHmac(algorithm, key, [options])
参数
上述参数描述如下-
algorithm –该算法用于生成Hmac对象。输入类型是字符串。
key –用于生成加密Hmac哈希的Hmac密钥。
options –这些是可用于控制流行为的可选参数。
encoding --要使用的字符串编码。
示例
创建一个具有名称的文件-createHmac.js并复制以下代码片段。创建文件后,使用以下命令运行此代码,如下例所示-
node createHmac.js
创建Hmac.js
//crypto.createHmac()演示示例 //导入加密模块 const crypto = require('crypto'); //定义密钥 const secret = 'nhooo'; //使用secret初始化createHmac方法 const hmacValue = crypto.createHmac('sha256', secret) //要编码的数据 .update('Welcome to nhooo !') //定义编码类型 .digest('hex'); //打印输出 console.log("得到的Hmac值为: ", hmacValue);输出结果
C:\home\node>> node createHmac.js 得到的Hmac值为: dd897f858bad70329fad82087110059f5cb920af2736d96277801f70bd57618e
示例
让我们再看一个例子。
//crypto.createHmac()演示示例 // Importing the crypto & fs module const crypto = require('crypto'); const fs = require('fs'); //获取当前文件路径 const filename = process.argv[1]; //使用秘密为当前路径创建hmac const hmac = crypto.createHmac('sha256', "nhooo"); const input = fs.createReadStream(filename); input.on('readable', () => { //读取hmac流生成的单个元素。 const val = input.read(); if (val) hmac.update(val); else { console.log(`${hmac.digest('hex')} ${filename}`); } });输出结果
C:\home\node>> node createHmac.js 0489ce5e4bd940c06253764e03927414f79269fe4f91b1c75184dc074fa86e22 /home/node/test/createHmac .js