VOOZH about

URL: https://www.geeksforgeeks.org/node-js/node-js-crypto-createhmac-method/

⇱ Node.js crypto.createHmac() Method - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Node.js crypto.createHmac() Method

Last Updated : 8 Jan, 2025

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 accepts 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.

Features

  • Generates a unique hash based on the content and a secret key.
  • Supports various cryptographic algorithms such as 'sha256', 'sha1', 'md5', etc.
  • Can be used with streams for processing large amounts of data.

Below examples illustrate the use of crypto.createHmac() method in Node.js:

Example 1: This example demonstrates using the crypto.createHmac() method to generate an HMAC hash of the string "GeeksforGeeks" using the SHA-256 algorithm and a secret key, then outputting the hash in hexadecimal format.

Output:

a08116905e92633e4f30eefd1276206b259305c8783642fc5b7f51c089187939

Example 2: This example demonstrates using the crypto.createHmac() method to generate an HMAC hash of the contents of the current file, read via a stream, and then outputs the hash along with the filename.

Output:

Program done!
The hmac object returns: 4605d44703c2620fc2574c9a9216bd3267457324 /run_dir/interp.js

Summary

The crypto.createHmac() method in Node.js is a powerful tool for generating HMACs, ensuring the integrity and authenticity of data. It supports various algorithms and integrates seamlessly with other Node.js modules, making it a versatile choice for secure data handling in your applications.

Reference:https://nodejs.org/api/crypto.html#crypto_crypto_createhmac_algorithm_key_options

Comment

Explore