How to create a hash from a string in JavaScript?


Before we start, let’s understand the hash in JavaScript. The hash is also a string, but it's encrypted using a particular algorithm. Generally, we use the hash for security purposes.

For example, Google stores users' emails and passwords in their database. Now, Google’s employees can access their database for development purposes. But can they get the user’s email and password from the database? No, because the password is stored in the hash form, and to decrypt the password, the employee needs the key which we used while creating the hash from the password string.

So, in such a way, we can convert the data to hash format. Whenever we require to compare the original data with new data, we can convert new data to hash using the same algorithm and compare it with the original data’s hash. We will learn to create a hash from a string in JavaScript.

Create an algorithm to convert string to hash

In this approach, we will create a custom function to generate a hash from the string. We will use the ASCII value of every string character, perform some operations such as multiplication, addition, subtraction, OR, etc., and generate a hash from that.

Syntax

Users can follow the syntax below to generate a hash from the string.

for (let character of str) {
   let charCode = character.charCodeAt(0);
   hashString = hashString << 5 – hashString + charCode;
   hashString |= hashString;
}

In the above syntax, hashstring contains the final hash of the str string.

Algorithm

  • Step 1 − Initialize the hashString variable with zero.

  • Step 2 − Use the for-of loop to iterate through the string.

  • Step 3 − Inside the for-of loop, get the ASCII value for every character.

  • Step 4 − After that, left shift the hashString by 5 to multiply it with 31, and subtract the hashString from it.

  • Step 5 − Add the ASCII value of the string character to the hashString variable.

  • Step 6 − Perform an OR operation of the hashString variable value with itself.

  • Step 7 − Once all iterations of the for-loop are completed, we can get the final hash of a 32-bit integer.

Example 1

We have taken the different strings to generate their hash in the example below. We have created the convertToHash() function, which takes the string as a parameter, and implements the above algorithm to convert it to the hash.

Users can observe the 32-bit integer value representing the hash in the output. Also, we can observe that it will always generate the same hash for the same string.

<html>
<body>
   <h2>Creating the <i> custom hash function </i> to convert string to hash</h2>
   <div id = "output"> </div>
   <script>
      let output = document.getElementById('output');
      function convertToHash(str) {
         if (str == "") return 0;
         let hashString = 0;
         for (let character of str) {
            let charCode = character.charCodeAt(0);
            hashString = hashString << 5 - hashString;
            hashString += charCode;
            hashString |= hashString;
         }
         output.innerHTML += "The original string is " + str + "<br/>";
         output.innerHTML += "The hash string related to original string is " + hashString + "<br/>";
         return hashString;
      }
      convertToHash("Hello Users");
      convertToHash("TutorialsPoint");
   </script>
</body>
</html>

Example 2

In the example below, we have implemented the above algorithm to convert the string to the hash, but we have used the reduce method rather than the for-loop. We have used the split() method to convert the string to a character array.

After that, we used the reduce() method and passed the callback function as the first parameter and 0 as a second parameter representing the initial value of the hash variable. In the callback function, we generate the hash using every character’s ASCII value.

<html>
<body>
   <h2>Using the <i> reduce() method </i> to convert string to hash</h2>
   <div id = "output"> </div>
   <script>
      let output = document.getElementById('output');
      function hashUsingReduce(string) {
         if (string == "") return 0;
         let charArray = string.split('');
         let hash = charArray.reduce((hash, char) => ((hash << 5 - hash) + char.charCodeAt(0)) | hash, 0);
         output.innerHTML += "The original string is " + string + "<br/>";
         output.innerHTML += "The hash string related to original string is " + hash + "<br/>";
         return hash;
      }
      hashUsingReduce("JavaScript");
      hashUsingReduce("TypeScript");
   </script>
</body>
</html>

Use the crypto-js NPM package

The Crpyo-js is an Npm package that contains various methods to generate a hash from the string. It also contains some algorithms to decrypt the messages.

Users need to install the crypto-js npm package into the node project using the below command.

npm i crypto-js

Syntax

Users can follow the syntax below to import and use the crypto-js package for encryption and decryption.

var ciphertext = CryptoJS.AES.encrypt('string', 'secret key').toString();

In the above syntax, we have used the encrypt() method of the AES module of the cryptoJS package.

Parameters

  • String − It is a message or data in the string format to generate a hash.

  • Secret key is a secret key that the algorithm will use while generating the hash. As complex as the hash, it will generate more secure encrypted text.

Example 3

We have imported the crypto-js package in the NodeJs file in the example below. After that, we accessed the AES module of the CryptoJs and used the encrypt() method to generate a hash from the string.

Users can observe the hash generated using the AES algorithm in the output.

var CryptoJS = require("crypto-js");
// Encrypt
var encryptedText = CryptoJS.AES.encrypt('Your Welcome!', 'This is my Secret').toString();
console.log("The hash string is " + encryptedText);

Output

"The hash string is U2FsdGVkX19br0LjrHteC9+dlP2PS9dVT03IrTc9zwQ="

This tutorial taught us two approaches to generating a hash from the string or data. The first approach is straightforward and encrypts the text without any key. So, we can’t use it in real-life development.

The CryptoJs package contains various modules for the various algorithms. We can use any algorithm's encrypt method, which also uses encryption keys. So, even anyone who knows the algorithm but doesn’t know the key can’t decrypt the cipher text.

Updated on: 16-Feb-2023

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements