Node.js hmac.digest() Method
Last Updated :
26 May, 2021
The hmac.digest() method is an inbuilt application programming interface of class hmac within crypto module which is used to return the hmac hash value of inputted data.
Syntax:
hmac.digest([encoding])
Parameter: This method takes encoding as a parameter which is an optional parameter.
Return Value: This method calculates the hmac digest of all data pass using hmac.update(). If no encoding provided then Buffer is returned, otherwise String is returned.
Note: The hmac.digest() performs final operations. So, hmac object become unusable after calling hmac.digest(). Calling multiple hmac.digest() causing error.
Project Setup: Create a new NodeJS project and name it hmac
mkdir hmac && cd hmac
npm init -y
npm install crypto
Now create a .js file in your project root directory and name it index.js
Example 1:
index.js
const { createHmac } = require( 'crypto' )
const algo = 'sha256'
const secret = 'GFG Secret Key'
const hmac = createHmac(algo, secret)
hmac.update( 'GeeksForGeeks' )
let result = hmac.digest()
console.log(Buffer.isBuffer(result))
result = result.toString( 'hex' )
console.log(`HMAC hash: ${result}`)
|
Run the index.js file using the following command:
node index.js
Output:
true
HMAC hash: c8ae3e09855ae7ac3405ad60d93758edc0ccebc1cf5c529bfb5d058674695c53
Example 2:
index.js
const myfile = process.argv[2];
const crypto = require( 'crypto' );
const fs = require( 'fs' );
const algo = 'sha256'
const secret = 'GFG Secret Key'
const hmac = crypto.createHmac(algo, secret);
const readfile = fs.createReadStream(myfile);
readfile.on( 'readable' , () => {
const data = readfile.read();
if (data) {
hmac.update(data);
} else {
const result = hmac.digest( 'base64' )
console.log(
`HMAC hash value of ${myfile}: ${result}`);
}
});
|
Run the index.js file using the following command:
node index.js package.json
Output:
HMAC hash value of package.json:
L5XUUEmtxgmSRyg12gQuKu2lmTJWr8hPYe7vimS5Moc=
Reference: https://nodejs.org/api/crypto.html#crypto_hmac_digest_encoding
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...