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 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( 'w3wiki' ) // 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
Output:
true
HMAC hash: c8ae3e09855ae7ac3405ad60d93758edc0ccebc1cf5c529bfb5d058674695c53
Example 2:
index.js
// 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 = 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
Contact Us