crypto.createHmac() Method in Node.js


The crypto.createHmac() method will create a Hmac object and then return it. THis Hmac uses the passed algorithm and key. The optional options will be used for controlling the stream behaviour. The key defined will be the HMAC key used for generating cryptographic HMAC hash.

Syntax

crypto.createHmac(algorithm, key, [options])

Parameters

The above parameters are described as below −

  • algorithm – This algorithm is used for generating the Hmac objects. Input type is string.

  • key – Hmac key used for generating the cryptographic Hmac hash.

  • options – These are optional parameters which can be used for controlling the stream behaviour.

  • encoding – String encoding to use.

Example

Create a file with name – createHmac.js and copy the below code snippet. After creating file, use the following command to run this code as shown in the example below −

node createHmac.js

createHmac.js

 Live Demo

// crypto.createHmac() demo example

// Importing the crypto module
const crypto = require('crypto');

// Defining the secret key
const secret = 'TutorialsPoint';

// Initializing the createHmac method using secret
const hmacValue = crypto.createHmac('sha256', secret)

   // Data to be encoded
   .update('Welcome to TutorialsPoint !')

   // Defining encoding type
   .digest('hex');

// Printing the output
console.log("Hmac value Obtained is: ", hmacValue);

Output

C:\home
ode>> node createHmac.js Hmac value Obtained is: dd897f858bad70329fad82087110059f5cb920af2736d96277801f70bd57618e

Example

Let's take a look at one more example.

 Live Demo

// crypto.createHmac() demo example

// Importing the crypto & fs module
const crypto = require('crypto');
const fs = require('fs');

// Getting the current file path
const filename = process.argv[1];

// Creting hmac for current path using secret
const hmac = crypto.createHmac('sha256', "TutorialsPoint");

const input = fs.createReadStream(filename);
input.on('readable', () => {
   // Reading single element produced by hmac stream.
   const val = input.read();
   if (val)
      hmac.update(val);
   else {
      console.log(`${hmac.digest('hex')} ${filename}`);
   }
});

Output

C:\home
ode>> node createHmac.js 0489ce5e4bd940c06253764e03927414f79269fe4f91b1c75184dc074fa86e22 /home/node/test/createHmac .js

Updated on: 20-May-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements