Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 742
buley Avatar asked Feb 24 '11 22:02

buley


People also ask

Is there a hash function in JavaScript?

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.

Are hashing functions one-way?

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.

What JavaScript library provides a hashing function?

jshashes is lightweight library implementing the most extended cryptographic hash function algorithms in pure JavaScript (ES5 compliant).

What are different hashing functions available?

Some of the major types of hash functions are: Mid Square Hash Function. Division Hash Function. Folding Hash Function.


2 Answers

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)
like image 85
Weihang Jian Avatar answered Oct 16 '22 00:10

Weihang Jian


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> 
like image 30
Tero Niemi Avatar answered Oct 16 '22 02:10

Tero Niemi