How to generate SHA-256 hash a string in NodeJS with example
In Web applications, Clients such as browsers send the data to the server. To secure the data, We need to encrypt data before sending data. Example
There are different algorithms to generate encrypted hash data. Nodejs provides js-sha256🔗 library to generate the cryptographic hash.
What is JS-SHA?
SHA is an alias for a Secure hash algorithm that is used to generate a hash of a given data using crypto algorithms. There are many implementations and variations of SHA1 and SHA2.
It is one way of encrypting a given string, not decrypted by design. There are many libraries in Nodejs and the Client side to generate a hash function
In Nodejs, in many ways, we can do
one way using the
First, install the library using npm or yarn in the Nodejs project
npm install js-sha256 yarn add js-sha256
Import module into code
using require in ES5 language
var sha256 = require('js-sha256');
Use import in ES6
import sha256 from 'js-sha256';
Here is the code to generate hash and encryption for string.
var sha256 = require('js-sha256'); console.log(sha256("welcome"))
Second-way using the
crypto-js library provides different algorithms such as SHA, AES, HMAC algorithm
The following are supported in SHA types
npm install crypto-js
Here is an example
var algo = require("crypto-js/sha256"); var hash = algo("welcome"); console.log(hash)
How to decode sha 256 encoded string
SHA-256 is a secured algorithm that encodes the string into a hash. It is not possible to decode the encryped hash. To check given hash is equal to the given string, First, convert the given string into a hash and compare the hash for both are equal.