-
-
Save iahu/82a18a9347acc2ac2405bbad9f65c6ef 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.
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
/** | |
* 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().encode(message); // encode as (utf-8) Uint8Array | |
const hashBuffer = await crypto.subtle.digest('SHA-256', msgUint8); // hash the message | |
const hashArray = Array.from(new Uint8Array(hashBuffer)); // convert buffer to byte array | |
const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).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