Created
October 26, 2022 20:20
-
-
Save matiasmicheletto/2b1a6ed89f21158a7aac38ef4e13f93b to your computer and use it in GitHub Desktop.
Compute base64 SHA-256 hash in browser
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
const hash = message => { | |
return new Promise((resolve, reject) => { | |
const msgBuffer = new TextEncoder().encode(message); | |
crypto.subtle.digest('SHA-256', msgBuffer) | |
.then(hashBuffer => { | |
const hashArray = Array.from(new Uint8Array(hashBuffer)); | |
const hexString = hashArray.map(b => b.toString(16).padStart(2, '0')).join(''); | |
const str = hexString | |
.replace(/\r|\n/g, "") | |
.replace(/([\da-fA-F]{2}) ?/g, "0x$1 ") | |
.replace(/ +$/, "") | |
.split(" "); | |
const b64 = btoa(String.fromCharCode.apply(null, str)); // Polyfill may be required | |
resolve(b64); | |
}) | |
.catch(reject); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment