Generating HMAC of a file using node.js


Overview

Hashing a file using HMAC : We are hashing the contents of a file using node.js streams , node.js filesystem and MD5 cryprographic hashing algorithm.

Code


													
//Name of the file : file-hmac.js
// Including the required modules
var crypto = require('crypto');
var fs = require('fs');

//Algorithm to be used for HMAC
var algorithm = 'md5';
//Secret to be used with HMAC
var secret ='Rj2895647';
//creating hmac object
var hmac = crypto.createHmac(algorithm, secret);

// reading the content of the file
var filename = "assets/new_data.txt";
var file_data = fs.ReadStream(filename);

//passing the data to be hashed
file_data.on('data', function(data) {
  hmac.update(data)
})

//Creating the hmac in the required format and writing it in file
file_data.on('end', function() {
  var gen_hmac = hmac.digest('hex')
  console.log('Hmac generated using ' + algorithm + ' \nHashed output is :  ' + gen_hmac + ' \nFile name is :  ' + filename);
  fs.writeFileSync(filename, gen_hmac);
}) 
													
												

Run

  • Now run the snippet using the following command :
    													
    >node file-hmac.js
    Hmac generated using md5
    Hashed output is :  36fd68f9594ea9137585aecb0be529e9
    File name is :  assets/new_data.txt