Skip to content

Instantly share code, notes, and snippets.

@marco-souza
Created August 3, 2020 18:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marco-souza/939bad273c75133bb7f7f20efefe644a to your computer and use it in GitHub Desktop.
Save marco-souza/939bad273c75133bb7f7f20efefe644a to your computer and use it in GitHub Desktop.
JS/TS Async SHA-256
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