Home  >  Article  >  Web Front-end  >  How to create a hash from a string in JavaScript?

How to create a hash from a string in JavaScript?

WBOY
WBOYforward
2023-08-25 15:49:041344browse

如何在 JavaScript 中从字符串创建哈希?

Before we begin, let’s learn about hashes in JavaScript. A hash value is also a string, but it is encrypted using a specific algorithm. Usually, we use hashes for security purposes.

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

So, in this way, we can convert the data into hash format. Whenever we need to compare the original data with new data, we can use the same algorithm to convert the new data into a hash value and compare it with the hash value of the original data. We will learn how to create a hash from a string in JavaScript.

Create an algorithm that converts a string into a hash

In this method, we will create a custom function to generate a hash value from a string. We will take the ASCII value of each string character, perform some operations like multiplication, addition, subtraction, OR, etc. and generate a hash from it.

grammar

Users can generate hashes from strings following the following syntax.

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 value of the str string.

algorithm

  • Step 1 - Initialize the hashString variable to zero.

  • Step 2 - Iterate over the string using a for-of loop.

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

  • Step 4 - After that, shift the hashString left by 5, multiply by 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 on the hashString variable value and itself.

  • Step 7 - Once all iterations of the for loop are completed, we obtain the final hash value of the 32-bit integer.

Example 1

In the example below, we take different strings to generate their hash values. We created the convertToHash() function which takes a string as parameter and implements the above algorithm to convert it into a hash value.

Users can observe the 32-bit integer value representing the hash value in the output. Furthermore, we can observe that it always generates the same hash value 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 implement the above algorithm to convert a string into a hash, but we use the reduce method instead of a for loop. We use the split() method to convert the string into a character array.

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

<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>

Using crypto-js NPM package

Crpyo-js is an Npm package that contains various methods for generating hashes from strings. It also contains some algorithms for decrypting messages.

Users need to use the following command to install the crypto-js npm package into the node project.

npm i crypto-js

grammar

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

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

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

parameter

  • String - It is the message or data in string format and is used to generate the hash.

  • The secret key is the secret key that the algorithm will use when generating the hash. As complex as the hash is, it will produce a more secure encrypted text.

Example 3

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

Users can observe the hash values ​​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 teaches us two ways to generate hashes from strings or data. The first method is simple and encrypts text without any key. So, we cannot use it in actual development.

The CryptoJs package contains various modules for various algorithms. We can use an encryption method with any algorithm that also uses an encryption key. Therefore, even if you know the algorithm but not the key, you cannot decrypt the ciphertext.

The above is the detailed content of How to create a hash from a string in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete