Last active
August 4, 2017 16:35
-
-
Save angel333/4045e080c57cad3ede4ac42e036bccac to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Simple hash function that uses Web Cryptography API | |
* @param {string} algo - SHA-1/SHA-256/SHA-384/SHA-512 | |
* @param {string} text - text to compute digest from | |
* @return {Promise} - A promise returning text. | |
*/ | |
function hash (algo, text) { | |
const encoded = new TextEncoder().encode(text); | |
return window.crypto.subtle.digest(algo, encoded) | |
.then(result => | |
Array.from(new Uint8Array(result)) // => [ 123, 80, 44, 58, ... ] | |
.map(char => char.toString(16)) // => [ '7b', '50', '2c', '3a', ... ] | |
.join('') // => '7b502c3a...' | |
); | |
} | |
// Example | |
hash('SHA-1', 'Hello world').then(console.log) | |
// Prints out 7b502c3a1f48c8609ae212cdfb639dee39673f5e |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment