Node.js – hmac.update() Method

Node.jsServer Side ProgrammingProgramming

The Hmac class is one of the many utility classes that is used for creating the cryptographic HMAC digests. The Hmac.update() method is used for updating the Hmac content with the data passed. If encoding is not provided and the data is in string format, then the default encoding 'utf8' is enforced.

Syntax

hmac.update(data, [encoding])

Parameters

The parameters are described below:

  • data − This input parameter takes input for the data with which Hmac will be updated.
  • encoding − This input parameter takes input for the encoding to be considered while updating the Hmac.

Example 1

Create a file with the name "hmacUpdate.js" and copy the following code snippet. After creating the file, use the command "node hmacUpdate.js" to run this code.

 Live Demo

// 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');
hmac.update('To');
hmac.update('TutorialsPoint')

// Printing the hmac value using digests
console.log("Hmac is: " + hmac.digest('hex'))

Output

C:\home\node>> node hmacUpdate.js
Hmac is: 641538b74bf1a59cd9a5cbd97dd0cf3b76b572e17432997230ae346feb41d149

Example 2

 Live Demo

// 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');
const hmac1 = crypto.createHmac('sha256', 'secretKey');
const hmac2 = crypto.createHmac('sha256', 'secretKey');
// Updating hmac with below data
hmac.update('TutorialsPoint');
hmac1.update('TutorialsPoint');
hmac2.update('TutorialsPoint');

// Printing the hmac value using different digests
console.log("Hmac(with hex Encoidng) is: " + hmac.digest('hex'))

console.log("Hmac(with Base64 Encoding) is: " + hmac1.digest('base64'))

console.log("Hmac(with Default Encoding) is: " + hmac2.digest())

Output

C:\home\node>> node hmacUpdate.js
Hmac(with hex Encoidng) is: 9534f1298c89fcd4e42e3fecbb26ac66148a1a607e6fb122ef0af4859f9eb0e5
Hmac(with Base64 Encoding) is: lTTxKYyJ/NTkLj/suyasZhSKGmB+b7Ei7wr0hZ+esOU=
Hmac(with Default Encoding) is: �4�)�����.?�&�f��`~o�"�􅟞��
raja
Published on 17-Aug-2021 11:15:31
Advertisements