0

I am looking for a way to covert a given string into an alphanumeric hash. The code will be executed on the client-side and must be entirely in vanilla JS or jQuery at the most.

Is there, however, also a non-cryptographic hash, i.e. just a string of alphanumerics that does not require crypto and Promises? I need both, i.e. a cryptographic as well as a non-cryptographic hash.

The second hash can be an ordinary string of alphanumerics, say 10 characters long. It should be recoverable, i.e. the same hash should be recreated always for a given string. It would be better if this second hash is not generated asynchronously (i.e. using Promises). I intend to use it as a key for a boolean in window.localStorage (for many different strings).

Final answers:

Yash Sampat
  • 30,051
  • 12
  • 94
  • 120

1 Answers1

5

Modern browsers provide cryptographic algorithms implementation via window.crypto object. You can look at what "modern" means in this case by this link (at the bottom). If you are fine with supported browsers list, then you can reach your goal for example like this:

async function hash(target){
   var buffer = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(target));
   var chars = Array.prototype.map.call(new Uint8Array(buffer), ch => String.fromCharCode(ch)).join('');
   return btoa(chars);
};

It will hash your string (bytes of its utf-8 encoding) with SHA-256 and then convert result to base64.

Note that if you don't need cryptographically strong hash (you didn't clarify the purpose) - then there might be better (faster) alternatives.

Evk
  • 98,527
  • 8
  • 141
  • 191
  • And what properties do you need from such hash, what's a usage? – Evk May 08 '18 at 10:25
  • Maybe then just use a library such as CryptoJS (https://github.com/brix/crypto-js)? Then you can use something like `CryptoJS.MD5("your string")`, and no promises. Or you may look at this question: https://stackoverflow.com/q/16225632/5311735 – Evk May 08 '18 at 10:38
  • No vanilla JS like in your first answer ? :) – Yash Sampat May 08 '18 at 10:40
  • Well this answer: https://stackoverflow.com/q/14733374/5311735 has some copy-pastable MD5 implementations, you might consider them. – Evk May 08 '18 at 10:41