When working on the task "Encrypt / decrypt file (CryptoJS.AES)" I encountered a problem: the official documentation is not described the process of encrypting and decrypting files.
The problem was that after decryption the file was corrupted. This was due to improper decoding of the decrypt files. After decryption it is necessary to execute the code:
decryptFile.toString(CryptoJS.enc.Utf8);
I want to share with you my decision:
import CryptoJS from 'crypto-js';
import fs from "fs";
const key = 'SECRET_KEY',
iv = '9De0DgMTCDFGNokdEEial'; // You must dynamically create
const encrypt = (filePath)=> {
const dataFile = fs.readFileSync(filePath),
dataBase64 = dataFile.toString('base64'),
encryptFile = CryptoJS.AES.encrypt(dataBase64, key, {iv: iv}),
buffer = new Buffer(encryptFile.toString(), 'base64');
fs.writeFileSync(filePath, buffer);
}
const decrypt = (filePath, fileType)=> {
const dataFile = fs.readFileSync(filePath);
const decryptFile = CryptoJS.AES.decrypt(dataFile.toString('base64'),
key, {iv: iv});
// Return data: URL
return 'data:' + fileType + ';base64,' +
decryptFile.toString(CryptoJS.enc.Utf8);
// Or save decrypt file
// const result = decryptFile.toString(CryptoJS.enc.Utf8);
// const buffer = new Buffer(result, 'base64');
// fs.writeFileSync(filePath, buffer);
}