hmac.digest() 方法是crypto 模塊中hmac 類的內置應用程序編程接口,用於返回輸入數據的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 hash: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
相關用法
- Node.js console.timeLog()用法及代碼示例
- Node.js x509.toLegacyObject()用法及代碼示例
- Node.js fs.fsyncSync()用法及代碼示例
- Node.js process.nextTick()用法及代碼示例
- Node.js GM charcoal()用法及代碼示例
- Node.js GM blur()用法及代碼示例
注:本文由純淨天空篩選整理自braktim99大神的英文原創作品 Node.js hmac.digest() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。