Clean code

This commit is contained in:
Adria Navarro 2023-06-12 17:49:12 +01:00
parent 92a8c97aba
commit ded738a566
1 changed files with 15 additions and 8 deletions

View File

@ -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( export async function decryptFile(
inputPath: string, inputPath: string,
outputPath: string, outputPath: string,
secret: string secret: string
) { ) {
const inputFile = fs.createReadStream(inputPath) const { salt, iv } = await getSaltAndIV(inputPath)
const outputFile = fs.createWriteStream(outputPath) const inputFile = fs.createReadStream(inputPath, {
start: SALT_LENGTH + IV_LENGTH,
})
const salt = await readBytes(inputFile, SALT_LENGTH) const outputFile = fs.createWriteStream(outputPath)
const iv = await readBytes(inputFile, IV_LENGTH)
const stretched = stretchString(secret, salt) const stretched = stretchString(secret, salt)
const decipher = crypto.createDecipheriv(ALGO, stretched, iv) const decipher = crypto.createDecipheriv(ALGO, stretched, iv)
fs.createReadStream(inputPath, { start: SALT_LENGTH + IV_LENGTH }) inputFile.pipe(decipher).pipe(outputFile)
.pipe(decipher)
.pipe(outputFile)
return new Promise<void>(r => { return new Promise<void>(r => {
outputFile.on("finish", () => { outputFile.on("finish", () => {
inputFile.close()
outputFile.close() outputFile.close()
r() r()
}) })