2

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(); 
}; 
Topaco
  • 40,594
  • 4
  • 35
  • 62
Emonale
  • 513
  • 2
  • 7
  • 22
  • What exactly does `fileContent` contain, can you post the filling (I could swear that you originally posted this (`function readFileContent`), but I can't find it in the history either)? – Topaco Jul 29 '20 at 11:40
  • Yes, I removed it because I thought it was not significant. fileContent contains unreadable stuff like this: ���LkB.���}� S�}� ��h�}" ud�����D���@HSV��3�ɹy5�xP�����N�_5�_��RB���b㸫�M%�Ź������e� – Emonale Jul 29 '20 at 11:45
  • I suspect that a part of the bug is there. That's why I'd advise you to add it again. – Topaco Jul 29 '20 at 11:54
  • fs.readFile('test.txt.enc', readContent); function readContent (err, data) { err ? Function("error","throw error")(err) : fileContent = data.toString()); }; – Emonale Jul 29 '20 at 12:19
  • You should definitely complete your question about the used Node-RED environment and give more information about the content and format of `msg.payload`. Also check which data is contained in `msg.payload` (or in `data`) and if the content matches the content of `test.txt.enc`. The goal should be to create a buffer that contains _exactly_ the data from `test.txt.enc`. Such a buffer can then be easily converted with `toString('base64')` into a Base64 encoded string that can be processed _directly_ by `CryptoJS.AES.decrypt`. I have deleted my answer, as it does not help here. – Topaco Jul 29 '20 at 18:43

0 Answers0