crypto.createHmac() Method in Node.js

Node.jsJavascriptWeb DevelopmentFront End Technology

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.


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


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.


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


 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

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


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


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 =;
   if (val)
   else {
      console.log(`${hmac.digest('hex')} ${filename}`);


C:\home\node>> node createHmac.js
/home/node/test/createHmac .js
Updated on 20-May-2021 11:56:45