Open In App

Node.js hmac.update() Method

Improve
Improve
Like Article
Like
Save
Share
Report

The hmac.update() method is an inbuilt method of class HMAC within the crypto module which is used to update the data of hmac object. 

Syntax:

hmac.update(data[, inputEncoding])

Parameters: This method takes the following two parameters:

  • data: It can be of string, Buffer, TypedArray, or DataView type. It is the data that is passed to this function.
  • inputEncoding: It is an optional parameter. It is the encoding of the data string.

Return Value: This method returns nothing.

 

Project Setup: Create a new NodeJS project and name it hmac.

mkdir hmac && cd hmac
npm init -y

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


Run the index.js file using the following command:

node index.js

Output:

HMAC hash: yK4+CYVa56w0Ba1g2TdY7cDM68HPXFKb+10FhnRpXFM=

Example 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}`);
  }
});


Run the index.js file using the following command:

node index.js package.json

Output:

HMAC hash value of package.json: 38f0f975f8964343c24da940188eaeb6bb20842e3c5bf03ccb66773e98beeb73

Reference: https://nodejs.org/api/crypto.html#crypto_hmac_update_data_inputencoding



Last Updated : 03 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads