Generate SHA256 hash with Node.js
In this tutorial, you will learn how to generate a SHA256 hash value for a specific string in Node.js.
Secure Hash Algorithm 256 or SHA-256 belongs to SHA2. It is a cryptographic hash function or algorithm that is used to generate a hash value for any specified original value. The generated value is 256 bit of hash value. It is known as message digest.
In Node.js, we can use the crypto module from npm to perform our task. Let’s first install the module:
npm i crypto
Below is given our code snippet to generate a SHA256 hash value from our provided string value:
var crypto = require('crypto'); //creating object of hash var hash = crypto.createHash('sha256'); //Pass the original data to be hashed originalValue = hash.update('Hello Everyone!', 'utf-8'); //Creating the hash value in the specific format hashValue= originalValue.digest('hex'); //Printing the output on the console console.log("Hash value is : " + hashValue);
Hash value is : 4f594d1752823de5707b8cba245ad79d223846f69d0c43f4622bf7e270967664
In the above code, we first imported the crypto module. Then created an object of the hash:
var hash = crypto.createHash('sha256');
As you can see, we have pass
"sha256" as we want to get SHA-256 for the original string.
Next, we pass the original value to the
hash.update() method as you can see below:
originalValue = hash.update('Hello Everyone!', 'utf-8');
In the last two lines of code, we first set the type to
hex and print the hash value.
In this example, we have created the SHA256 hash value for the string
Leave a Reply