How to Implement SHA-256 in JavaScript

Mehvish Ashiq Feb 02, 2024
  1. What Is Hashing in JavaScript
  2. What Is the SHA-256 Algorithm in JavaScript
  3. the SHA-256 Implementation in JavaScript
  4. Use Crypto Library to Implement SHA-256 in JavaScript
  5. Use the node-forge Module to Implement SHA-256 in JavaScript
How to Implement SHA-256 in JavaScript

Various kinds of hashes can be generated, for instance, MD5, SHA-1, SHA-2, SHA-256, etc. This article focuses on SHA-256 implementation in JavaScript.

Before that, it is good to have a basic understanding of hashing and the SHA-256 algorithm. Let’s start!

What Is Hashing in JavaScript

Hashing is a procedure that transforms the specified string or key into some other value that can’t be converted back to its real form. A hash function converts the plain text that does some mathematical operations on the given input (string).

The output produced by the hash function is called Digest or Hash Value.

sha-256 implementation in javascript - what is hashing

What Is the SHA-256 Algorithm in JavaScript

The SHA stands for Secure Hash Algorithm, which is from the family of the SHA-2 algorithm. What does 256 mean in SHA-256?

It means the final hash value would always be 256-bits regardless of plain text’s size. The SHA-256 is also similar to other SHA algorithms.

Let’s begin its implementation of SHA-256 in JavaScript.

the SHA-256 Implementation in JavaScript

We’ll learn different ways of SHA-256 implementation in JavaScript that you can use as per your project needs. But before that, let’s understand how to generate a hash using String’s function.

Example code is given below to practice.

// conversts to 32bit integer
function stringToHashConversion(string) {
  var hashVal = 0;
  if (string.length == 0) return hashVal;
  for (i = 0; i < string.length; i++) {
    char = string.charCodeAt(i);
    hashVal = ((hashVal << 5) - hashVal) + char;
    hashVal = hashVal & hashVal;
  }
  return hashVal;
}
var input_str = 'I am converting string to hash.';
console.log('Input String: ' + input_str);
console.log('Hash Value: ' + stringToHashConversion(input_str));

Output:

"Input String: I am converting string to hash."
"Hash Value: 625005622"

The function stringToHashConversion() returns zero (0) for an empty string. It iterates until the string.length-1 gets the charCode of each character and calculates the hash by shifting 5-bits to the left.

The final hash value is a 32-bit integer.

Now, the point to focus on is the 5-bits left shift. Why is it 5, not 6 or 4? It is because (hashVal << 5) is the same as (hashVal * 32).

In this way, ((hashVal << 5) - hashVal) is equivalent to (hashVal * 31). We get the same hash if we replace ((hashVal << 5) - hashVal) with (hashVal * 31).

Are you still confused about the 31 number?

The 31 is selected because it’s one of the odd prime numbers. Just imagine, if this was an even number & multiplication overflowed, all the details would be gone because multiplication by 2 is identical to shifting.

Then why (hashVal * 31) is not used? It is because, (hashVal << 5) - hashVal is faster than (hashVal * 31).

We can also use the faster version by using ES6 Math.imul, which assists in computing the 32-bit integer multiplication of the specified two values (see the following code).

The | 0 optimize hash for better speed and forces it to be a 32-bit number in the following solution.

JavaScript Code:

function stringToHashConversion(string) {
  for (var i = 0, hash = 0; i < string.length; i++)
    hash = Math.imul(31, hash) + string.charCodeAt(i) | 0;
  return hash;
}
var input_str = 'I am converting string to hash.';
console.log('Input String: ' + input_str);
console.log('Hash Value: ' + stringToHashConversion(input_str));

Output:

"Input String: I am converting string to hash."
"Hash Value: 625005622"

Use Crypto Library to Implement SHA-256 in JavaScript

Let’s use the Crypto library to implement SHA-256. Import the crypto module using the require() method.

The getHashes() returns all the supported algorithms’ names. We create the Hash object using createHash(), which takes two parameters, the algorithm’s name and options.

The second parameter is optional. Further, we use this Hash object to generate hash digests using the specified algorithm.

The update() method updates the data, and digest() tells the encoding used. The digest is the result produced by the hash function, and this result only has hexadecimal values.

You can read more about it here. You must have Node.js to use the Crypto library.

JavaScript Code:

const crypto = require('crypto'), hash = crypto.getHashes();
var input_str = 'I am converting string to hash.';

hashPwd = crypto.createHash('sha256').update(input_str).digest('hex');

console.log('Input String: ' + input_str);
console.log('Hash Value: ' + hashPwd);

Output:

Input String: I am converting string to hash.
Hash Value: ceb443790638fbc0f543ccf80a08085a731c83a6fd1843c3c3ff2e6edd86c58b

Use the node-forge Module to Implement SHA-256 in JavaScript

We can use the following command to install the node-forge module in Node.js and then use it.

npm install node - forge

Forge is a native implementation of TLS (Transport Layer Security) and different cryptographic tools in JS (JavaScript). Firstly, we import the module using require() and then create a forge object initialized for the SHA-256 via calling the create() function.

The update() updates the data while the digest() function performs hashing and returns the hash value of the given text. See the following code.

var forge = require('node-forge');
var input_str = 'I am converting string to hash.';
var md = forge.md.sha256.create();
md.update(input_str);
console.log('Input String: ' + input_str);
console.log('Hash Value: ' + md.digest().toHex());

Output:

Input String: I am converting string to hash.
Hash Value: ceb443790638fbc0f543ccf80a08085a731c83a6fd1843c3c3ff2e6edd86c58b
Mehvish Ashiq avatar Mehvish Ashiq avatar

Mehvish Ashiq is a former Java Programmer and a Data Science enthusiast who leverages her expertise to help others to learn and grow by creating interesting, useful, and reader-friendly content in Computer Programming, Data Science, and Technology.

LinkedIn GitHub Facebook

Related Article - JavaScript Hash