Search code examples
javascriptnode.jsencryptionpaddingdes

Loss of data when passing it to Cipher.update while using DES (Node.js)


Here's the deal:

I have a Buffer of data structured like this:

[39 bytes of header] + [body] + [padding] (calculated by me). If I save it to a file, I can actually recognize the structure, and everything seems fine.

Then, I have to DES-CBC encrypt this buffer, and what I do is

a) Instantiate the DES wrapper, which has a key, and calculates a new IV (autoPadding: false on the Cipher object it creates, too)
b) Pass the buffer to the DES wrapper
c) The buffer then gets encrypted as follows: (data is the buffer, en is the Cipher object)

var buf1 = en.update(data);

When I output buf1 on a file (and then, in my case, on a socket) and retrieve it's bytes, then decrypt it I obtain the following structure: [header][body] But when I output data on a file and retrieve it's bytes, I get the starting structure. I know I should also append en.final() to buf1, but in my case I don't need those values, also with autoPadding being false it would just throw an error.


Solution

  • The API provides you with a contract. One of the properties of the contract is that you need to call Cipher#final([output_encoding]) when you finished encrypting. Even if the padding doesn't need to be handled by the Cipher instance, the code is written for re-usability and therefore expects to be used in the same way regardless of padding options.