Created
August 3, 2020 18:19
-
-
Save marco-souza/939bad273c75133bb7f7f20efefe644a to your computer and use it in GitHub Desktop.
JS/TS Async SHA-256
This file contains hidden or 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
async function sha256(message: string): Promise<string> { | |
// encode as UTF-8 | |
const msgBuffer = new TextEncoder().encode(message); | |
// hash the message | |
const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer); | |
// convert ArrayBuffer to Array | |
const hashArray = Array.from(new Uint8Array(hashBuffer)); | |
// convert bytes to hex string | |
const hashHex = hashArray.map(b => ('00' + b.toString(16)).slice(-2)).join(''); | |
return hashHex; | |
} | |
export default sha256 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment