简体   繁体   中英

Are there any one-way hashing functions available in native JavaScript?

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.

not that I'm aware of.

however, you could always use a JavaScript implementation of MD5

http://pajhome.org.uk/crypt/md5/

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>

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)

Nothing is available in native JavaScript. You could use something like Murmurhash . There's a JavaScript implementation here: https://github.com/garycourt/murmurhash-js . I haven't used it though so can't vouch for it.

Update: now there are multiple Murmurhash3 implementations available in JavaScript. However, many of them have problems encoding strings to bytes and can produce different results compared to the reference C++ implementation. You can read an analysis on this here , the murmurhash3js-revisited library implements all three variants of the function and conforms to the reference.

Over the horizon, this may be possible with the currently experimental Web Crypto API

https://developer.mozilla.org/en-US/docs/Web/API/Web_Crypto_API

https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto

Granted, at the time of this writing it is unrealistic to use in a production environment and will likely be a moving target. However, come 5 years who knows?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM