4

I'm trying to decrypt data using a key and the AES-JS library. Whenever I put a 16 bytes key I get the following error:

Error: "invalid ciphertext size (must be 16 bytes)"

I already tried to change the key to non-16 bytes value but then I get this error:

Error: "invalid key size (must be 16, 24 or 32 bytes)"

Here is my code so far :

export const getEventBlockData = (cm, eventBlockData) => {
  const encryptedBlockBuf = Buffer.from(eventBlockData, 'base64');
  const aes = new aesjs.AES(aesjs.utils.utf8.toBytes('1111111111111111'));
  const decryptedBlockBuffer = new Buffer(aes.decrypt(encryptedBlockBuf));
};

The part that generates an error is the last line with aes.decrypt(...

NB : the cm var is supposed to be the key but for testing purposes i replaced it by a string "1111111111111111" and the eventBlockData is the buffer i'm trying to decrypt, he has the following form :

Event Block Data :{"type":"Buffer","data":[49,56,53,50,55,51,53,49,50,50,48,48,48,49,48,48,48,48,49]} cm-service.js:61
Encrypted Block buff :{"type":"Buffer","data":[49,56,53,50,55,51,53,49,50,50,48,48,48,49,48,48,48,48,49]}

Thanks for your time! :)

cнŝdk
  • 31,391
  • 7
  • 56
  • 78
Quentin_otd
  • 233
  • 1
  • 3
  • 16

1 Answers1

2

Actually the error says invalid ciphertext size (must be 16 bytes), so the problem is not with your key and changing the key length, like you said you did in your post, won't resolve the problem as it doesn't concern the key.

It's a common and known issue that concerns the length of plaintext in CBC and it occurs when you use a cipher text with length other than a multiple of 16 bytes.

To solve this you need to add a padding for your encrypted text, for further details you can read Why must all inputs to AES be multiples of 16?.

cнŝdk
  • 31,391
  • 7
  • 56
  • 78
  • Thanks for your answer, i'v read the padding wikipedia page but i'm still a bit lost on how to do it. If i understood correctly i need to add bytes to my buffer : "Encrypted Block buff :{"type":"Buffer","data":[215,206,118,239,126,117,219,109,52,211,93,52,211,77]}" in order to make it a multiple of 16. But i dont know where to start or which pattern to use for the bytes. Thanks :) – Quentin_otd Jan 16 '19 at 14:02
  • @Quentin_otd I am sorry, I don't really have a better knowledge on this issue with `aesjs`, I encountred the same thing when I was writing it in Java, and I tried to provide an answer based on the few articles I read. – cнŝdk Jan 16 '19 at 15:10
  • Not really. Any valid AES-CBC ciphertext will have length that is a multiple of 16 bytes. Therefore his ciphertext is corrupted in some way. It has nothing to do with padding. – President James K. Polk Jan 16 '19 at 20:41