Node.js hmac.digest() Method
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
// Node.js program to demonstrate the// crypto hmac.digest() method // Importing crypto moduleconst { createHmac } = require('crypto') // Creating and initializing algorithm// and passwordconst algo = 'sha256'const secret = 'GFG Secret Key' // Create an HMAC instanceconst hmac = createHmac(algo, secret) // Update the internal state of// the hmac objecthmac.update('GeeksForGeeks') // Perform the final operations// No encoding provided// Return calculated hmac hash// value as Bufferlet result = hmac.digest() // Check whether returns value is// instance of buffer or notconsole.log(Buffer.isBuffer(result)) // true // Convert buffer to stringresult = result.toString('hex') // Print the resultconsole.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
// Node.js program to demonstrate the // crypto hmac.digest() method // Defining myfileconst myfile = process.argv[2]; // Includes crypto and fs moduleconst crypto = require('crypto');const fs = require('fs'); // Creating and initializing // algorithm and passwordconst algo = 'sha256'const secret = 'GFG Secret Key' // Creating Hmacconst hmac = crypto.createHmac(algo, secret); // Creating read streamconst 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}`); }}); |
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



