How to create hash from string in JavaScript ?
Last Updated :
30 May, 2024
To create a unique hash from a specific string, it can be implemented using its own string-to-hash converting function. It will return the hash equivalent of a string. Also, a library named Crypto can be used to generate various types of hashes like SHA1, MD5, SHA256, and many more.
These are the following methods to Create Hash from String:
Note: The hash value of an empty string is always zero.
The JavaScript str.charCodeAt() method returns a Unicode character set code unit of the character present at the index in the string specified as the argument. The index number ranges from 0 to n-1, where n is the string’s length.
Syntax:
str.charCodeAt(index)
Example: In this example, we will create a hash from a string in Javascript.
JavaScript
function stringToHash(string) {
let hash = 0;
if (string.length == 0) return hash;
for (i = 0; i < string.length; i++) {
char = string.charCodeAt(i);
hash = ((hash << 5) - hash) + char;
hash = hash & hash;
}
return hash;
}
// String printing in hash
let gfg = "GeeksforGeeks"
console.log(stringToHash(gfg));
Using crypto.createHash() method
The crypto.createHash() method is used to create a Hash object that can be used to create hash digests by using the stated algorithm.
Syntax:
crypto.createHash( algorithm, options )
Example: In this example, we will create a hash from a string in Javascript.
JavaScript
// Importing 'crypto' module
const crypto = require('crypto'),
// Returns the names of
// supported hash algorithms
// such as SHA1,MD5
hash = crypto.getHashes();
// Create hash of SHA1 type
x = "Geek"
// 'digest' is the output
// of hash function containing
// only hexadecimal digits
hashPwd = crypto.createHash('sha1')
.update(x).digest('hex');
console.log(hashPwd);
Output321cca8846c784b6f2d6ba628f8502a5fb0683ae
Using JavaScript String's reduce() Method
The reduce() method in JavaScript applies a function to each element of the array (or in this case, each character of the string) to reduce the array to a single value. In this method, we can accumulate a hash value by iteratively processing each character's Unicode code point and incorporating it into the hash.
Syntax:
string.split('').reduce((hash, char) => {
return char.charCodeAt(0) + (hash << 6) + (hash << 16) - hash;
}, 0);
Example:
JavaScript
function stringToHash(string) {
return string.split('').reduce((hash, char) => {
return char.charCodeAt(0) + (hash << 6) + (hash << 16) - hash;
}, 0);
}
let gfg = "GeeksforGeeks";
console.log(stringToHash(gfg));
Using bitwise XOR operation
Using a bitwise XOR operation to generate a hash from a string. It iterates over each character, XORs its Unicode value with the current hash, updating it. This approach offers simplicity and efficiency in creating a unique hash.
Example: In this example we are using above-explained approach.
JavaScript
function stringToHash(string) {
let hash = 0;
if (string.length === 0) return hash;
for (const char of string) {
hash ^= char.charCodeAt(0); // Bitwise XOR operation
}
return hash;
}
// String printing in hash
const gfg = "GeeksforGeeks";
console.log(stringToHash(gfg));
Approach: Using Crypto library's createHash() method with SHA-256 algorithm
The Crypto library in Node.js provides a createHash() method that allows generating hash digests using various algorithms, including SHA-256. This method takes the algorithm name as an argument and returns a Hash object, which can then be used to update the hash with data and obtain the hash digest.
Example:
JavaScript
const crypto = require('crypto');
function createSHA256Hash(inputString) {
const hash = crypto.createHash('sha256');
hash.update(inputString);
return hash.digest('hex');
}
// Example usage
const inputString = "Hello, World!";
const hashValue = createSHA256Hash(inputString);
console.log(hashValue); // Output: 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
Output:
2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
JavaScript Interview Questions and Answers JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
React Tutorial React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable.Applications are built using reusable compon
8 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read