rweather / arduinolibs

Arduino Cryptography Library
444 stars 212 forks source link

AES with CTR/CBC mode #51

Closed sairathb closed 4 years ago

sairathb commented 4 years ago

Hi, thanks for the library, it is a big help in my project. I am trying to perform a AES256 encryption and exchange data with a mobile app build using react native and I tried just AES256, CTR and CBC. The AES256 is able to encrypt and decrypt a block properly. However, when I am trying the same block with CTR/CBC mode, the decryption is not returning the same plain text. The code I am using is as follows:

  CBC<AES256> crypto;
  byte key[]  = {0xCB, 0xC0, 0x8B, 0xEF, 0x8E, 0xEF, 0x3C, 0xBE, 0x8E, 0x21, 0xA1, 0x96, 0x6A, 0x44, 0xDE, 0xD5, 0x3A, 0x35, 0x3B, 0xBC, 0x08, 0xB4, 0x08, 0xB1, 0xF0, 0xDD, 0xCB, 0x84, 0x77, 0x24, 0xAD, 0x1E};
  byte iv[] = {0x70, 0x97, 0xDD, 0xEE, 0xA3, 0xB6, 0xEF, 0x48, 0x0E, 0x0F, 0xA5, 0xBA, 0x27, 0x5B, 0xC1, 0x15};
  byte bMsg[] = {0x48, 0x45, 0x4C, 0x4C, 0x4F, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04}; //HELLO
  byte cipher[cipherLen];
  byte plain[cipherLen];
  crypto.setKey(key, 32);
  crypto.setIV(iv, 16);
  // crypto.setCounterSize(4);
  crypto.encrypt(cipher, bMsg, cipherLen);
  crypto.decrypt(plain, cipher, cipherLen);
  dumpByteArray(bMsg, cipherLen);
  dumpByteArray(cipher, cipherLen);
  dumpByteArray(plain, cipherLen);

The CBC code is not directly in this repo, but I found the .cpp and .h file in the documentation. I copied them and tried to use it. Can you please guide me in this issue. Please let me know if you need more input from my end.

Thanks

rweather commented 4 years ago

It is necessary to call setIV() again to reset the initialisation vector back to the state at the start of the packet before calling decrypt(). Otherwise it will decrypt starting with the IV state at the end of the packet.

The CBC code is in the CryptoLegacy library. I moved it out of the core Crypto library because CBC isn't recommended for modern designs.