Explain Codes LogoExplain Codes Logo

Generate a Hash from string in Javascript

javascript
hashmap
functions
callbacks
Nikita BarsukovbyNikita Barsukov·Feb 7, 2025
TLDR

Utilize the SubtleCrypto.digest() method from the Web Crypto API in JavaScript, to hash a string with SHA-256:

async function getSHA256Hash(str) { const buf = new TextEncoder().encode(str); const digest = await crypto.subtle.digest('SHA-256', buf); return Array.from(new Uint8Array(digest)).map(b => b.toString(16).padStart(2, '0')).join(''); } // Example call: getSHA256Hash('example').then(console.log); // Prints the unique hash of 'example'

This short piece of code encodes a string, calculates its SHA-256 hash, and formats it as a hexadecimal string.

Client-side methods for hashing

While SubtleCrypto.digest() is highly effective, other solutions might be necessary for tasks such as consistent string transformation or simple checksums that don't require cryptographic security. Below are many alternatives for client-side hashing:

Using String.prototype.hashCode

This is a simple method designed for client-side implementation, producing fairly unique hash values from a given string:

String.prototype.hashCode = function() { let hash = 0; for (let i = 0; i < this.length; i++) { const chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; // As an example: console.log("Answer42".hashCode()); // Prints: 7291972; Douglas Adams fans, rejoice!

Keep in mind that this approach does not ensure cryptographic security and should not be used for sensitive data.

Utilizing BigInt and Math.imul

By employing BigInt and Math.imul, the generation of the hashes can become more varied, while increasing the range of potential hash values. Math.imul provides efficient multiplication, which is crucial for hash calculation:

function bigIntHash(str, seed = 0) { const prime = 31n; let hash = BigInt(seed); for (let i = 0; i < str.length; i++) { const charCode = BigInt(str.charCodeAt(i)); hash = hash * prime + charCode; } return hash.toString(); } // Try it with your name! console.log(bigIntHash("YourNameHere")); // Whoa, that's big!

Though BigInt operations can be slower, they can enhance the scope of hash outputs.

Leveraging FNV-1a hash function

The FNV-1a hashing algorithm is genuinely a "Goldilocks" solution for obtaining a balance between even distribution and performance:

function fnv1aHash(str) { const prime = 0x811C9DC5; let hash = prime; for (let i = 0; i < str.length; i++) { hash ^= str.charCodeAt(i); hash += (hash << 1) + (hash << 4) + (hash << 7) + (hash << 8) + (hash << 24); } return hash >>> 0; // Get a non-negative number. } // Roll the dice! console.log(fnv1aHash("NowIsTheTime")); // All eyes on the console!

Proficient hashing: less is more

Obtaining an efficient and practical hashing mechanism requires careful selection of techniques:

  • Convert characters to ASCII values: It's a simple and effective method found within several hashing algorithms.
  • Use reduce function: Reduce provides a neat way to process hash computations involving arrays or strings, leading to efficient hashing.
  • Array processing: Try to work with byte arrays for as long as possible, instead of converting binary data to a hex string immediately, to limit overhead.

Here's an exemplar code snippet utilising JavaScript's reduce function:

function reducedHash(str) { return str.split("").reduce((acc, char) => { return ((acc << 5) - acc) + char.charCodeAt(0); }, 0); } // The secret code is... console.log(reducedHash("reducedHash")); // Await in awe!

Prudent considerations for optimized hashing

Constructing hash functions in JavaScript? Here's what you need to keep in top of mind:

  • Browser compatibility: Ensure your chosen hashing method is universally supported across browsers – yes, that includes Internet Explorer, too...
  • Avalanche effect: The most potent hash functions bear the "avalanche effect" – a minor tweak in input churns out a vastly different result.
  • Hash seeds: Vary your seeds to distill alternative outputs from identical input, making sure the results stay unique.

Playing safe with hashes

  • Client-side constraints: There are limitations to client-side hashing when it comes to security. Opt for server-side hashing for sensitive data.
  • Irreversible: For essential security hashes, opt for algorithms which are non-reversible to ensure they're not prone to snooping.
  • Server-side independence: While hashing client-side might be lucrative due to its independence from server-side dependencies, it comes with its share of security considerations which should be addressed head-on.