Crypto-js decrypt file encrypted with crypto

Viewed 311

I encrypt a file using crypto on a node.js server. When a client then downloads the file and tries to decrypt it using crypto-js, the output is not correct.

This is the code I use to encrypt:

var fileName = 'test.txt';
var key = Buffer.from(KEY_STRING, "utf8");
var iv = Buffer.from(IV_STRING, "utf8");
var cipher = crypto.createCipheriv('aes-256-cbc', key, iv);
var input = fs.createReadStream(fileName);
var output = fs.createWriteStream(fileName + '.enc');

input.pipe(cipher).pipe(output);

The client downloads test.txt.enc, reads its content into a string (fileContent in the following code) and decrypts:

var decrypted = CryptoJS.AES.decrypt(
    fileContent,
    CryptoJS.enc.Utf8.parse(KEY_STRING),
    {
        iv: CryptoJS.enc.Utf8.parse(IV_STRING),
        mode: CryptoJS.mode.CBC
    }
);

var cleartext = CryptoJS.enc.Utf8.stringify(decrypted);

When the client converts the WordArray back to the utf-8 text it gets an "Error: Malformed UTF-8 data" message. The file is received correctly because I use the hash to check.

EDIT: Filling of fileContent

fs.readFile('test.txt.enc', readContent); 
function readContent (err, data) { 
    err ? Function("error","throw error")(err) : fileContent = data.toString(); 
}; 
0 Answers
Related