Skip to content

Instantly share code, notes, and snippets.

@eyecatchup
Forked from chrisveness/crypto-sha.js
Created March 13, 2019 19:53
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 eyecatchup/e19c533a65324b4944de4ad952dbea87 to your computer and use it in GitHub Desktop.
Save eyecatchup/e19c533a65324b4944de4ad952dbea87 to your computer and use it in GitHub Desktop.
Uses the SubtleCrypto interface of the Web Cryptography API to hash a message using SHA-256.
/**
* Returns SHA-256 hash from supplied message.
*
* @param {String} message.
* @returns {String} hash as hex string.
*
* @example
* sha256('abc').then(hash => console.log(hash));
* const hash = await sha256('abc');
*/
async function sha256(message) {
const msgUint8 = new TextEncoder('utf-8').encode(message); // encode as UTF-8
const hashBuffer = await crypto.subtle.digest('SHA-256', msgUint8); // hash the message
const hashArray = Array.from(new Uint8Array(hashBuffer)); // convert hash to byte array
const hashHex = hashArray.map(b => ('00' + b.toString(16)).slice(-2)).join(''); // convert bytes to hex string
return hashHex;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment