
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Crypto CreateHash Method in Node.js
The crypto.createHash() method will create a hash object and then return it. THis hash object can be used for generating hash digests by using the given algorithm. The optional options are used for controlling the stream behaviour. For some hash functions like XOF and 'shake256' the output length is used for specifying the desired output length in bytes.
Syntax
crypto.createHash(algorithm, [options])
Parameters
The above parameters are described as below −
algorithm – This algorithm is used for generating the hash digests. Input type is string.
options – These are optional parameters which can be used for controlling the stream behaviour.
Example
Create a file with name – createHash.js and copy the below code snippet. After creating file, use the following command to run this code as shown in the example below −
node createHash.js
createHash.js
// crypto.createHash() demo example // Importing crypto module const crypto = require('crypto'); // Deffining the secret key const secret = 'TutorialsPoint'; // Initializing the createHash method using secret const hashValue = crypto.createHash('sha256', secret) // Data to be encoded .update('Welcome to TutorialsPoint !') // Defining encoding type .digest('hex'); // Printing the output console.log("Hash Obtained is: ", hashValue);
Output
C:\home
ode>> node createHash.js Hash Obtained is: 5f55ecb1ca233d41dffb6fd9e307d37b9eb4dad472a9e7767e8727132b784461
Example
Let's take a look at one more example.
// crypto.createHash() demo example // Importing crypto module const crypto = require('crypto'); const fs = require('fs'); // Getting the current file path const filename = process.argv[1]; // Creting hash for current path using secret const hash = crypto.createHash('sha256', "TutorialsPoint"); const input = fs.createReadStream(filename); input.on('readable', () => { // Reading single element produced by hash stream. const val = input.read(); if (val) hash.update(val); else { console.log(`${hash.digest('hex')} ${filename}`); } });
Output
C:\home
ode>> node createHash.js d1bd739234aa1ede5acfaccee657296ead1879644764f45be17466a9192c3967 /home/node/test/createHash.js