From ded738a56607b0c2135894152231db70ac1fdd54 Mon Sep 17 00:00:00 2001 From: Adria Navarro Date: Mon, 12 Jun 2023 17:49:12 +0100 Subject: [PATCH] Clean code --- .../backend-core/src/security/encryption.ts | 23 ++++++++++++------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/packages/backend-core/src/security/encryption.ts b/packages/backend-core/src/security/encryption.ts index e4d4048590..22a747ac30 100644 --- a/packages/backend-core/src/security/encryption.ts +++ b/packages/backend-core/src/security/encryption.ts @@ -96,27 +96,34 @@ export async function encryptFile( }) } +async function getSaltAndIV(path: string) { + const fileStream = fs.createReadStream(path) + + const salt = await readBytes(fileStream, SALT_LENGTH) + const iv = await readBytes(fileStream, IV_LENGTH) + fileStream.close() + return { salt, iv } +} + export async function decryptFile( inputPath: string, outputPath: string, secret: string ) { - const inputFile = fs.createReadStream(inputPath) - const outputFile = fs.createWriteStream(outputPath) + const { salt, iv } = await getSaltAndIV(inputPath) + const inputFile = fs.createReadStream(inputPath, { + start: SALT_LENGTH + IV_LENGTH, + }) - const salt = await readBytes(inputFile, SALT_LENGTH) - const iv = await readBytes(inputFile, IV_LENGTH) + const outputFile = fs.createWriteStream(outputPath) const stretched = stretchString(secret, salt) const decipher = crypto.createDecipheriv(ALGO, stretched, iv) - fs.createReadStream(inputPath, { start: SALT_LENGTH + IV_LENGTH }) - .pipe(decipher) - .pipe(outputFile) + inputFile.pipe(decipher).pipe(outputFile) return new Promise(r => { outputFile.on("finish", () => { - inputFile.close() outputFile.close() r() })