Created
February 19, 2021 11:56
-
-
Save n1ru4l/b768f4f9cd5921a7b3869b2d587fd425 to your computer and use it in GitHub Desktop.
Create SHA-256 of file in browser (with http fallback)
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
// window.crypto.subtle is undefined on page served via http :( | |
const crypto: null | SubtleCrypto = window?.crypto?.subtle ?? null; | |
const i2hex = (i: number): string => { | |
return ("00" + i.toString(16)).slice(-2); | |
}; | |
const generateHexFromUint8Array = (arr: Uint8Array) => | |
Array.prototype.map.call(arr, i2hex).join(""); | |
const generateSHA256HashNative = async ( | |
crypto: SubtleCrypto, | |
arrayBuffer: ArrayBuffer | |
) => { | |
const buf = await crypto.digest("SHA-256", arrayBuffer); | |
return new Uint8Array(buf); | |
}; | |
const generateSHA256HashFallback = async (arrayBuffer: ArrayBuffer) => { | |
// npm install -E -D [email protected] | |
const { hash } = await import("fast-sha256"); | |
return hash(new Uint8Array(arrayBuffer)); | |
}; | |
export const generateSHA256FileHash = async (file: File): Promise<string> => { | |
const arrayBuffer = await file.arrayBuffer(); | |
const rawHash = await (crypto | |
? generateSHA256HashNative(crypto, arrayBuffer) | |
: generateSHA256HashFallback(arrayBuffer)); | |
return generateHexFromUint8Array(rawHash); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment