Node.js | crypto.createHash() Method

The crypto.createHash() method is used to create a Hash object that can be used to create hash digests by using the stated algorithm.

Syntax:

crypto.createHash( algorithm, options )

Parameters: This method accept two parameters as mentioned avobe 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.
  • options: It is optional parameter and is used to control stream behavior. It returns an object. Moreover, For XOF hash functions like ‘shake256’, the option outputLength can be used to determine the required output length in bytes.

Return Type: It returns Hash object.

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



Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Node.js program to demonstrate the     
// crypto.createHash() method
  
// Includes crypto module
const crypto = require('crypto');
  
// Defining key
const secret = 'Hi';
  
// Calling createHash method
const hash = crypto.createHash('sha256', secret)
                     
                   // updating data
                   .update('How are you?')
  
                   // Encoding to be used
                   .digest('hex');
  
// Displays output
console.log(hash);

chevron_right


Output:

df287dfc1406ed2b692e1c2c783bb5cec97eac53151ee1d9810397aa0afa0d89

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Node.js program to demonstrate the     
// crypto.createHash() method
  
// Defining filename
const filename = process.argv[2];
  
// Includes crypto and  fs module
const crypto = require('crypto');
const fs = require('fs');
  
// Creating Hash 
const hash = crypto.createHash('sha256', 'Geeksforgeeks');
  
// Creating read stream
const input = fs.createReadStream(filename);
  
input.on('readable', () => {
   
 // Calling read method to read data
  const data = input.read();
  if (data)
      
    // Updating
    hash.update(data);
  else
   {
    // Encoding and displaying filename
    console.log(`${hash.digest('base64')} ${filename}`);
  }
});
console.log("Program done!");

chevron_right


Output:

Program done!
n95mt3468ZzAIwu/bbNU7dej6CoFkDRcNaJo7rGpLF4= index.js

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




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.