Reputation: 234
I have a js script that crypt and decrypt a file using these two functions
Encryption
function encryptFile(fileName) {
const input = fs.createReadStream(fileName);
const output = fs.createWriteStream(fileName + '.crypt');
var aes = crypto.createCipheriv(algorithm, Buffer.from(key), initVect);
input
.pipe(aes)
.pipe(output)
.on('finish', function () {
console.log('FILE ENCRYPTED!');
}).on('error', error => {
console.log(error);
});
}
Decryption
function decryptFile(fileName) {
const input = fs.createReadStream(fileName);
const output = fs.createWriteStream(fileName + '.clear');
const decipher = crypto.createDecipheriv(algorithm, Buffer.from(key), initVect);
input
.pipe(decipher)
.pipe(output)
.on('finish', () => {
console.log('FILE DECRYPTED!');
})
.on('error', error => {
console.log(error);
});
}
Some assumption:
aes-256-cbc
as algorithminitVect
is a crypto.randomBytes(16)
;Using these two function to crypt and decrypt a file I obtain a bad decryption. No error while execution but when I open the decrypted file the firsts 9 characters is still encrypted. Indeed, if I insert at the begin of my file 9 random charachters, the whole content of my file was decrypted correctly but there are the firsts chars encrypted.
Any solution?
UPDATE
I also use these two function passing them the content of the file
Encryption
function encrypt(text) {
const cipher = crypto.createCipheriv(algorithm, Buffer.from(key), initVect);
let encrypted = cipher.update(text, 'utf8', 'base64')
encrypted += cipher.final('base64');
return encrypted;
};
Decryption
function decrypt(crypted_text) {
const decipher = crypto.createDecipheriv(algorithm, Buffer.from(key), initVect);
let decrypted = decipher.update(crypted_text, 'base64');
decrypted += decipher.final();
return decrypted;
}
Using simple string these function work fine, saving the crypted
(return of encrypt()) in a file, reading it and decrypt it the result decrypted
(return of decrypt()) has the same problem.
Upvotes: 0
Views: 1238