Skip to content

Instantly share code, notes, and snippets.

@matiasmicheletto
Created October 26, 2022 20:20
Show Gist options
  • Save matiasmicheletto/2b1a6ed89f21158a7aac38ef4e13f93b to your computer and use it in GitHub Desktop.
Save matiasmicheletto/2b1a6ed89f21158a7aac38ef4e13f93b to your computer and use it in GitHub Desktop.
Compute base64 SHA-256 hash in browser
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