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:
- algorithm: It is dependent on the accessible algorithms that are favored by the version of OpenSSL on the platform. It returns a string. The examples are sha256, sha512, etc.
- options: It is an 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.
Example 1: Below examples illustrate the use of crypto.createHash() method in Node.js:
Javascript
const crypto = require( 'crypto' );
const secret = 'Hi' ;
const hash = crypto.createHash( 'sha256' , secret)
.update( 'How are you?' )
.digest( 'hex' );
console.log(hash);
|
Output:
df287dfc1406ed2b692e1c2c783bb5cec97eac53151ee1d9810397aa0afa0d89
Example 2: Below examples illustrate the use of crypto.createHash() method in Node.js:
Javascript
const filename = process.argv[1];
const crypto = require( 'crypto' );
const fs = require( 'fs' );
const hash =
crypto.createHash( 'sha256' , 'Geeksforgeeks' );
const input = fs.createReadStream(filename);
input.on( 'readable' , () => {
const data = input.read();
if (data) {
hash.update(data);
}
else {
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.
Last Updated :
15 Jan, 2024
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...