Open In App

Node 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 accepts two parameters as mentioned above and described below:

Return Type: It returns Hash object. 



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




// 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);

Output:

df287dfc1406ed2b692e1c2c783bb5cec97eac53151ee1d9810397aa0afa0d89

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




// Node.js program to demonstrate the    
// crypto.createHash() method
 
// Defining filename
const filename = process.argv[1];
 
// 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!");

Output:

Program done!
n95mt3468ZzAIwu/bbNU7dej6CoFkDRcNaJo7rGpLF4= index.js

We have a Cheat Sheet on Node crypto methods where we covered all the crypto methods to check those please go through Node Crypto Complete Reference article.


Article Tags :