Skip to content

Instantly share code, notes, and snippets.

@heineiuo
Last active January 5, 2022 07:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save heineiuo/1d2e5939ce503faa6b69f4c991810e01 to your computer and use it in GitHub Desktop.
Save heineiuo/1d2e5939ce503faa6b69f4c991810e01 to your computer and use it in GitHub Desktop.
Generate SHA-256 of File/Blob in browser
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