Node.js hmac.update() 方法
hmac.update()方法是加密模块中 HMAC 类的内置方法,用于更新 hmac 对象的数据。
句法:
hmac.update(data[, inputEncoding])
参数:该方法采用以下两个参数:
- 数据:它 可以是字符串、Buffer、TypedArray 或 DataView 类型。传递给此函数的是数据。
- inputEncoding:它是一个可选参数。它是数据字符串的编码。
返回值:此方法不返回任何内容。
项目设置:创建一个新的 NodeJS 项目并将其命名为hmac 。
mkdir hmac && cd hmac
npm init -y
现在在您的项目根目录中创建一个.js文件并将其命名为index.js
示例 1:
index.js
// Node.js program to demonstrate the
// crypto hmac.update() 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
// Return calculated hash
const result = hmac.digest('base64')
// Print the result
console.log(`HMAC hash: ${result}`)
index.js
// Node.js program to demonstrate the
// crypto hmac.update() 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
// Return hash value
const result = hmac.digest('hex')
// Display result
console.log(`HMAC hash value of ${myfile}: ${result}`);
}
});
使用以下命令运行index.js文件:
node index.js
输出:
HMAC hash: yK4+CYVa56w0Ba1g2TdY7cDM68HPXFKb+10FhnRpXFM=
示例 2:
index.js
// Node.js program to demonstrate the
// crypto hmac.update() 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
// Return hash value
const result = hmac.digest('hex')
// Display result
console.log(`HMAC hash value of ${myfile}: ${result}`);
}
});
使用以下命令运行index.js文件:
node index.js package.json
输出:
HMAC hash value of package.json: 38f0f975f8964343c24da940188eaeb6bb20842e3c5bf03ccb66773e98beeb73
参考: https://nodejs.org/api/crypto.html#crypto_hmac_update_data_inputencoding