suculent / thinx-aes-lib

AES wrapper for ESP8266/ESP32/Arduino/nRF5x
Other
117 stars 38 forks source link

Cannot generate correct cipher #41

Closed klack closed 3 years ago

klack commented 3 years ago

I have been trying to use this library but cannot get the same result as my python code. They use the same IV and Key.

Arduino Code:

#include <AESLib.h>
AESLib aesLib;

byte aes_key[] = { 0x06,0xa9,0x21,0x40,0x36,0xb8,0xa1,0x5b,0x51,0x2e,0x03,0xd5,0x34,0x12,0x00,0x06 };

char cleartext[256];
char ciphertext[512];

String encrypt(char * msg, byte iv[]) {
  int msgLen = strlen(msg);
  char encrypted[2 * msgLen];
  aesLib.encrypt64(msg, msgLen, encrypted, aes_key, sizeof(aes_key), iv);
  return String(encrypted);
}

void setup() {
  Serial.begin(9600);
}

void loop() {
  sprintf(cleartext, "Single block msg");

  aesLib.set_paddingmode(paddingMode::ZeroLength);

  // Encrypt Data
  byte enc_iv[N_BLOCK] = { 0x3d,0xaf,0xba,0x42,0x9d,0x9e,0xb4,0x30,0xb4,0x22,0xda,0x80,0x2c,0x9f,0xac,0x41 };
  String encrypted = encrypt(cleartext, enc_iv);
  sprintf(ciphertext, "%s", encrypted.c_str());
  Serial.print("Base64 encoded Ciphertext: ");
  Serial.println(encrypted);
}

Output: Base64 encoded Ciphertext: D9lURiJvj46w14X/1dYlEWf3tkHEaNrfgBrV733sCcQ=

Python:

import base64
from Cryptodome.Cipher import AES
from Cryptodome.Util.Padding import pad

str = "Single block msg"
print(f"Input string: {str}")
print(f"String length: {len(str)}")
key = bytearray.fromhex('06a9214036b8a15b512e03d534120006')
print(f"Key length: {len(key)}")
iv = bytearray.fromhex('3dafba429d9eb430b422da802c9fac41')
print(f"IV length: {len(iv)}")
cipher = AES.new(key, AES.MODE_CBC, iv)
ct_bytes = cipher.encrypt(str.encode())
print(f"Cipher: {ct_bytes.hex()}")
base64_bytes = base64.b64encode(ct_bytes)
print(f"Base64: {base64_bytes.decode()}")

Output: Base64: 41N3nBB5rrgnCJQtvncYGg==

suculent commented 3 years ago

How do you set padding in Python? It seems to have no padding whatsoever (given the length of resulting base64 data).

Try to change aesLib.set_paddingmode(paddingMode::ZeroLength); to aesLib.set_paddingmode(paddingMode::CMS);

It seems the ZeroLength padding is something else than what does the default Cryptodome AES use.

Also, don't use the encrypt64 and decrypt64 methods, those should apparently have been already deprecated.

klack commented 3 years ago

Hey suclent. Thanks for the reply. I am not setting any padding at the moment, however if there was padding, the first bytes would be the same: 41N3nBB5rrgnCJQtvncYGg==

klack commented 3 years ago

I am using the test vectors, case 1 published here:

https://tools.ietf.org/html/rfc3602#page-6

suculent commented 3 years ago

I guess you should not use deprecated encrypt64 function.

klack commented 3 years ago

I am using your provided example in the examples directory. I don't have time to go back and try it again, so I will close this.