I'd like to be able to create unique tokens* for users based on a hashed string. I know I could, for example, use a md5() library but as the purpose is not cryptographic I was wondering if there was anything I could use "out of the box." Are there any one-way hashing functions available in native JavaScript?
*I realize these won't be strictly unique. I'm ok with a small chance of hashing collision.
Definition of JavaScript hash() Hash function in Javascript is any function that takes input as arbitrary size data and produces output as fixed-size data. Normally, the returned value of the hash function is called hash code, hash, or hash value.
A hash function is a versatile one-way cryptographic algorithm that maps an input of any size to a unique output of a fixed length of bits. The resulting output, which is known as a hash digest, hash value, or hash code, is the resulting unique identifier we mentioned earlier.
jshashes is lightweight library implementing the most extended cryptographic hash function algorithms in pure JavaScript (ES5 compliant).
Some of the major types of hash functions are: Mid Square Hash Function. Division Hash Function. Folding Hash Function.
In 2020, there is a native API:
SubtleCrypto.digest()
https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest
example:
crypto.subtle .digest("SHA-256", new TextEncoder().encode("hello")) .then(console.log);
hex string conversion:
const digest = async ({ algorithm = "SHA-256", message }) => Array.prototype.map .call( new Uint8Array( await crypto.subtle.digest(algorithm, new TextEncoder().encode(message)) ), (x) => ("0" + x.toString(16)).slice(-2) ) .join(""); digest({message: "hello"}).then(console.log)
JavaScript does not have native hashing, but there are many libraries.
I recommend crypto-js: https://code.google.com/p/crypto-js/
For example, to use SHA1, you simply:
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/sha1.js"></script> <script> var hash = CryptoJS.SHA1("Message"); </script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With