Last active
January 5, 2022 07:32
-
-
Save heineiuo/1d2e5939ce503faa6b69f4c991810e01 to your computer and use it in GitHub Desktop.
Generate SHA-256 of File/Blob 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
import CryptoJS from 'crypto-js' | |
function byteArrayToWordArray(ba: Uint8Array) { | |
const wa: number[] = [] | |
for (let i = 0; i < ba.length; i++) { | |
wa[(i / 4) | 0] |= ba[i] << (24 - 8 * i) | |
} | |
return CryptoJS.lib.WordArray.create(wa, ba.length) | |
} | |
export async function generateHash(file: File | Blob) { | |
const hash256 = CryptoJS.algo.SHA256.create() | |
const ab = await file.arrayBuffer() | |
const ba = new Uint8Array(ab) | |
hash256.update(byteArrayToWordArray(ba)) | |
return hash256.finalize().toString() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment