Published on

Create SHA256 Hash with salt in Javascript

Create SHA256 Hash with salt in Javascript

SHA256 is (atleast when it was created) a standardized 1-way function that takes in data input of any form and maps it to a fixed-size output string, irrespective of the size of the input string.

Though it is used as a cryptographic hash function, it has been found to suffer from a lot of vulnerabilities.

A salt is a randomly generated string of characters that is used as an additional input to a one-way hash function. Salts are used to protect against dictionary attacks and rainbow table attacks.

The SHA256 hash with salt is generated by concatenating the salt to the password and then hashing the resulting string. The salt is then appended to the generated hash to form the complete hash. This complete hash is then stored in the database. When a user attempts to login, the salt is retrieved from the database and used to generate a hash from the provided password. The generated hash is then compared to the hash stored in the database. If the two hashes match, the user is authenticated.

We can create an SHA256 hash of a string in JavaScript without using an hash as well. In this article we will create a hash by using a salt.

If you are looking to generate sha256 checksum in nodejs, please follow this article - Creating SHA256 Hash with salt in Node.js.

The method below are for creating it at client-side or browser.

Using CryptoJS SHA256 hash with salt

Here we will be using the above npm package directly in HTML code. We are using version 4.1.1 of the crypto-js package. Let's use the Cloudflare CDN links and use <script> tags to import core.min.js and sha256.js scripts.

After that, you can use it in your code as CryptoJS.SHA256(yourString). Here is an example demonstrating crypto-js and sha256 implementation-

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script src=""></script>
    <script src=""></script>
      let digest = "password"
      let salt = "80zzm081sr@nd0m"
      let algo = CryptoJS.algo.SHA256.create()
      algo.update(digest, "utf-8")
      algo.update(CryptoJS.SHA256(salt), "utf-8")
      hash = algo.finalize().toString(CryptoJS.enc.hex)

Output of the above code is going to be an alert with value 00fd5f9738e7f53a1f2ead4da19882a53ecc4ff5ee5ae56bd09b7d98f33c2b69.

I'm glad that you found the content useful. Happy Coding.