Created
December 5, 2019 17:15
-
-
Save cvan/a5251c53e640a21cb0789abced1d753c to your computer and use it in GitHub Desktop.
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
// Source: adapted from https://stackoverflow.com/a/48161723 | |
// This returns a SHA-256-hashed string. | |
function sha256(message) { | |
// Encode as UTF-8. | |
const msgBuffer = new TextEncoder('utf-8').encode(message); | |
if (typeof window !== 'object' || !window.crypto) { | |
return Promise.resolve(null); | |
} | |
// Hash the message. | |
return window.crypto.subtle.digest('SHA-256', msgBuffer).then(hashBuffer => { | |
// 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; | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment