Skip to content

Instantly share code, notes, and snippets.

@cxmeel
Last active August 11, 2020 15:02
Show Gist options
  • Select an option

  • Save cxmeel/cf241b1b2d433b583eb5d60ce572504f to your computer and use it in GitHub Desktop.

Select an option

Save cxmeel/cf241b1b2d433b583eb5d60ce572504f to your computer and use it in GitHub Desktop.
Native SHA hashing in Chrome/Chromium simplified using ES6 Promises
// https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest
function hash(message = "", algorithm = hash.sha256) {
return new Promise((resolve, reject) => {
const textEncoder = new TextEncoder()
const encodedData = textEncoder.encode(message)
crypto.subtle.digest(algorithm, encodedData)
.then(arrayBuffer => {
const hashArray = Array.from(new Uint8Array(arrayBuffer))
const hashHex = hashArray.map(byte => byte.toString(16).padStart(2, 0)).join("")
return hashHex
})
.then(resolve)
.catch(reject)
})
}
hash.sha1 = "SHA-1"
hash.sha256 = "SHA-256"
hash.sha384 = "SHA-384"
hash.sha512 = "SHA-512"
export default hash
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment