Skip to content
Related Articles
Open in App
Not now

Related Articles

Node.js hmac.digest() Method

Improve Article
Save Article
  • Last Updated : 26 May, 2021
Improve Article
Save Article

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.  



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: 


// 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
// 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}`)

Run the index.js file using the following command:

node index.js


HMAC hash: c8ae3e09855ae7ac3405ad60d93758edc0ccebc1cf5c529bfb5d058674695c53

Example 2:


// 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 =;
    if (data) {
        // Updating
    } else {
        // Perform the final operations 
        // Encoding provided
        // Return hmac hash value
        const result = hmac.digest('base64')
        // Display result
    `HMAC hash value of ${myfile}: ${result}`);

Run the index.js file using the following command:

node index.js package.json


HMAC hash value of package.json: 


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!