Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
136
rated 0 times [  140] [ 4]  / answers: 1 / hits: 39752  / 14 Years ago, thu, february 24, 2011, 12:00:00

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.


More From » hash

 Answers
9

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)




[#93594] Wednesday, February 23, 2011, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
chyanne

Total Points: 208
Total Questions: 120
Total Answers: 110

Location: Colombia
Member since Mon, May 2, 2022
2 Years ago
;