The Hmac class is one of the many utility classes that is used for creating the cryptographic HMAC digests. The Hmac.digest() method is used for calculating all the data that is updated using the Hmac.update() method. If encoding is provided, a string will be returned, else a buffer is returned.
hmac.digest( [encoding] )
Create a file "hmacDigest.js" and copy the following code snippet. After creating the file use, use the command "node hmacDigest.js" to run this code.
// Hmac.digest() Demo Example // Importing the crypto module const crypto = require("crypto") // Initializing the Hmac object with encoding and key const hmac = crypto.createHmac('sha256', 'secretKey'); // Updating hmac with below data hmac.update('Welcome to Tutorials point'); // Printing the hmac value using digests console.log("Hmac is: " + hmac.digest('hex'))
C:\home\node>> node hmacDigest.js Hmac is: 4e6fa9b98ed4c498a498148bd720cc7b14b40b148e5b919bc89869b8c5dd5c9e
// Hmac.digest() Demo Example // Importing the crypto module const crypto = require("crypto") // Initializing the Hmac object with encoding and key const hmac = crypto.createHmac('sha256', 'secretKey'); // Defining the hmac encoding algorithm var encoding = "sha256" // Defining the secret key var secretKey = "1234567890" // Defining the data to be hashed var data = "TutorialsPoint" // Creating the Hmac in hex encoding let hmacDigest = crypto.createHmac(encoding, secretKey).update(data).digest("hex") // Creating the Hmac in base64 encoding let hmacDigestWithBase64 = crypto.createHmac(encoding, secretKey).update(data).digest("base64") // Printing the Hmac value using digests console.log("Hmac in Hex is: " + hmacDigest) console.log("Hmac in Base64 encoding: " + hmacDigestWithBase64)
C:\home\node>> node hmacDigest.js Hmac in Hex is: 05fa1c5566678274ca0a4db70b0522cbb765140fa5903fbd42c1eac8682538dd Hmac in Base64 encoding: BfocVWZngnTKCk23CwUiy7dlFA+lkD+9QsHqyGglON0=