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
const { createHmac } = require( 'crypto' )
const algo = 'sha256'
const secret = 'GFG Secret Key'
const hmac = createHmac(algo, secret)
hmac.update( 'GeeksForGeeks' )
const result = hmac.digest( 'base64' )
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
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( 'hex' )
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
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
03 Apr, 2023
Like Article
Save Article