use stream for generating hash

This commit is contained in:
Rushikesh Tote 2022-05-18 13:19:50 +05:30
parent f49b53db0f
commit 272c7966f9
2 changed files with 13 additions and 12 deletions

View file

@ -200,8 +200,7 @@ export async function encryptWithRecoveryKey(key: string) {
export default CryptoWorker; export default CryptoWorker;
export async function getFileHash(file: File | ElectronFile) { export async function getFileHash(file: File | ElectronFile) {
const hash = await cryptoGenericHash( const stream = await file.stream();
new Uint8Array(await file.arrayBuffer()) const hash = await cryptoGenericHash(stream);
);
return hash; return hash;
} }

View file

@ -252,7 +252,7 @@ export async function hash(input: string) {
); );
} }
export async function cryptoGenericHash(data: Uint8Array) { export async function cryptoGenericHash(stream: ReadableStream) {
await sodium.ready; await sodium.ready;
const state = sodium.crypto_generichash_init( const state = sodium.crypto_generichash_init(
@ -260,15 +260,17 @@ export async function cryptoGenericHash(data: Uint8Array) {
sodium.crypto_generichash_BYTES_MAX sodium.crypto_generichash_BYTES_MAX
); );
let bytesRead = 0; const reader = stream.getReader();
while (bytesRead < data.length) {
const chunkSize = Math.min( let isDone = false;
ENCRYPTION_CHUNK_SIZE, while (!isDone) {
data.length - bytesRead const { done, value: chunk } = await reader.read();
); if (done) {
const buffer = data.slice(bytesRead, bytesRead + chunkSize); isDone = true;
break;
}
const buffer = Uint8Array.from(chunk);
sodium.crypto_generichash_update(state, buffer); sodium.crypto_generichash_update(state, buffer);
bytesRead += chunkSize;
} }
const hash = sodium.crypto_generichash_final( const hash = sodium.crypto_generichash_final(