Reputation: 30611
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:
Upvotes: 0
Views: 5434
Reputation: 101493
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.
Upvotes: 5