Skip to content

Instantly share code, notes, and snippets.

@cvan
Created December 5, 2019 17:15
Show Gist options
  • Save cvan/a5251c53e640a21cb0789abced1d753c to your computer and use it in GitHub Desktop.
Save cvan/a5251c53e640a21cb0789abced1d753c to your computer and use it in GitHub Desktop.
// 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