Last active
August 11, 2020 15:02
-
-
Save cxmeel/cf241b1b2d433b583eb5d60ce572504f to your computer and use it in GitHub Desktop.
Native SHA hashing in Chrome/Chromium simplified using ES6 Promises
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
| // 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