Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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.
Method 1: Custom Hash Algorithm
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
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
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/><br/>";
return hashString;
}
convertToHash("Hello Users");
convertToHash("TutorialsPoint");
</script>
</body>
</html>
The original string is Hello Users The hash string related to original string is -1777374048 The original string is TutorialsPoint The hash string related to original string is -928825504
Method 2: Using the reduce() Method
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/><br/>";
return hash;
}
hashUsingReduce("JavaScript");
hashUsingReduce("TypeScript");
</script>
</body>
</html>
The original string is JavaScript The hash string related to original string is 924844249 The original string is TypeScript The hash string related to original string is 1521015169
Method 3: Using the crypto-js NPM Package
The Crypto-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 install 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 ? It is a secret key that the algorithm will use while generating the hash. As complex as the key is, it will generate more secure encrypted text.
Example
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);
The hash string is U2FsdGVkX19br0LjrHteC9+dlP2PS9dVT03IrTc9zwQ=
Comparison
| Method | Security Level | Use Case | Dependency |
|---|---|---|---|
| Custom Hash Algorithm | Low | Learning/Simple hashing | None |
| reduce() Method | Low | Learning/Simple hashing | None |
| crypto-js Package | High | Production applications | NPM package |
Conclusion
This tutorial taught us three approaches to generating a hash from the string. The custom algorithms are suitable for learning but not for production use. The crypto-js package provides industry-standard encryption algorithms with proper security for real-world applications.
