Node.js crypto.createHmac() Method
The crypto.createHmac() method is used to create an Hmac object that uses the stated ‘algorithm’ and ‘key’. Syntax:
crypto.createHmac( algorithm, key, options )
Parameters: This method accept three parameters as mentioned above and described below:
- algorithm: It is dependent on the accessible algorithms which are favored by the version of OpenSSL on the platform. It returns string. The examples are sha256, sha512, etc.
- key: It is the HMAC key which is used to create the cryptographic HMAC hash. It returns string, Buffer, TypedArray, DataView, or KeyObject. And if it is a KeyObject, then its type must be secret.
- options: It is optional parameter and used to control stream behavior. It returns an object.
Return Type: It returns Hmac object. Below examples illustrate the use of crypto.createHmac() method in Node.js: Example 1:
javascript
// Node.js program to demonstrate the // crypto.createHmac() method // Includes crypto module const crypto = require( 'crypto' ); // Defining key const secret = 'GfG' ; // Calling createHmac method const hash = crypto.createHmac( 'sha256' , secret) // updating data .update( 'GeeksforGeeks' ) // Encoding to be used .digest( 'hex' ); // Displays output console.log(hash); |
Output:
a08116905e92633e4f30eefd1276206b259305c8783642fc5b7f51c089187939
Example 2:
javascript
// Node.js program to demonstrate the // crypto.createHmac() method // Defining myfile const myfile = process.argv[1]; // Includes crypto and fs module const crypto = require( 'crypto' ); const fs = require( 'fs' ); // Creating Hmac const creathmac = crypto.createHmac( 'sha1' , 'CS-Portal!' ); // Creating read stream const readfile = fs.createReadStream(myfile); readfile.on( 'readable' , () => { // Calling read method to read data const data = readfile.read(); if (data) // Updating creathmac.update(data); else { // Encoding and displaying filename console.log("The hmac object returns:", `${creathmac.digest( 'hex' )} ${myfile}`); } }); console.log("Program done!"); console.log(); |
Output:
Program done! The hmac object returns: 4605d44703c2620fc2574c9a9216bd3267457324 /run_dir/interp.js
Reference: https://nodejs.org/api/crypto.html#crypto_crypto_createhmac_algorithm_key_options
Please Login to comment...