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

How to create hash using SHA-256 alogorithm with JavaScript in Nodejs

In Nodejs, in many ways, we can do

one way using the JS-sha256 library 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"))

Output:

280d44ab1e9f79b5cce2dd4f58f5fe91f0fbacdac9f7447dffc318ceb79f2d02

Second-way using the crypto-js library.

crypto-js library provides different algorithms such as SHA, AES, HMAC algorithm The following are supported in SHA types

  • crypto-js/md5
  • crypto-js/sha1
  • crypto-js/sha256
  • crypto-js/sha224
  • crypto-js/sha512
  • crypto-js/sha384
  • crypto-js/sha3
  • crypto-js/ripemd160
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.