Node.js hmac.digest()方法
The hmac.digest() 方法是hmac类在crypto模块中的内置应用程序接口,用于返回输入数据的hmac哈希值。
语法:
hmac.digest([encoding])
参数: 此方法接受一个可选的编码参数。
返回值: 此方法计算使用hmac.update()传递的所有数据的hmac摘要。如果没有提供编码,则返回Buffer;否则返回String。
注意: hmac.digest()执行了最终的操作。因此,在调用hmac.digest()之后,hmac对象变得不可用。多次调用hmac.digest()会导致错误。
项目设置: 创建一个新的NodeJS项目,命名为 hmac
mkdir hmac && cd hmac
npm init -y
npm install crypto
现在在您的项目根目录中创建一个.js文件并将其命名为 index.js
示例1:
index.js
// Node.js program to demonstrate the
// crypto hmac.digest() method
// Importing crypto module
const { createHmac } = require('crypto')
// Creating and initializing algorithm
// and password
const algo = 'sha256'
const secret = 'GFG Secret Key'
// Create an HMAC instance
const hmac = createHmac(algo, secret)
// Update the internal state of
// the hmac object
hmac.update('GeeksForGeeks')
// Perform the final operations
// No encoding provided
// Return calculated hmac hash
// value as Buffer
let result = hmac.digest()
// Check whether returns value is
// instance of buffer or not
console.log(Buffer.isBuffer(result)) // true
// Convert buffer to string
result = result.toString('hex')
// Print the result
console.log(`HMAC hash: ${result}`)
使用以下命令运行 index.js 文件:
node index.js
输出:
true
HMAC哈希:c8ae3e09855ae7ac3405ad60d93758edc0ccebc1cf5c529bfb5d058674695c53
示例2:
index.js
// Node.js program to demonstrate the
// crypto hmac.digest() method
// Defining myfile
const myfile = process.argv[2];
// Includes crypto and fs module
const crypto = require('crypto');
const fs = require('fs');
// Creating and initializing
// algorithm and password
const algo = 'sha256'
const secret = 'GFG Secret Key'
// Creating Hmac
const hmac = crypto.createHmac(algo, secret);
// Creating read stream
const readfile = fs.createReadStream(myfile);
readfile.on('readable', () => {
// Calling read method to read data
const data = readfile.read();
if (data) {
// Updating
hmac.update(data);
} else {
// Perform the final operations
// Encoding provided
// Return hmac hash value
const result = hmac.digest('base64')
// Display result
console.log(
`HMAC hash value of {myfile}:{result}`);
}
});
使用以下命令运行 index.js 文件:
node index.js package.json
输出:
HMAC hash value of package.json:
L5XUUEmtxgmSRyg12gQuKu2lmTJWr8hPYe7vimS5Moc=
参考: https://nodejs.org/api/crypto.html#crypto_hmac_digest_encoding