I am creating a Node.js application that can encrypt and decrypt image files. However when my code is run I get varying results: Sometimes the decrypted image looks like the original at the top but the bottom half looks corrupted, sometimes the decrypted image is completely there but looks like it was heavily compressed and sometimes the decrypted image is too corrupt to open. Here is an image that demonstrates this. The only thing these results have in common is the encrypted and decrypted images are double the file size of the original image.
const fs = require('fs');
const crypto = require('crypto');
var path = 'C:\\Users\\' + windowsUserName + '\\Desktop\\image';
var fileExtension = '.jpg';
var password = '1234';
var algorithm = 'aes-256-cbc';
var image = fs.createReadStream(path + fileExtension);
var encryptedImage = fs.createWriteStream(path + ' encrypted' + fileExtension);
var decryptedImage = fs.createWriteStream(path + ' decrypted' + fileExtension);
var encrypt = crypto.createCipher(algorithm, password);
var decrypt = crypto.createDecipher(algorithm, password);
image.pipe(encrypt).pipe(encryptedImage);
image.pipe(encrypt).pipe(decrypt).pipe(decryptedImage);
How do I fix the image corruption and file size doubling?
createCipherIvnotcreateCipher."it is important that an initialization vector is never reused under the same key". If I were to change my current code to usecreateCipherIvinstead ofcreateCipherwouldn't I be reusing the IV all the time?