I'm using this library: https://tls.mbed.org/download with an Espressif ESP32. The goal is to encrypt some data using AES-CTR then decrypt the cypher-text back to the original plain-text. I am getting incorrect result after I've decrypted.
Since we're using CTR mode, we don't need to have a separate "decrypt" function; We can just call the encrypt function once to encrypt then call the same function one more time and it should decrypt. At least, that's what most sources say and that was the case with this other implementation: https://github.com/kokke/tiny-AES-c
I tried using the same nonce, same stream-block, different nonces, different stream-blocks, set the key before each of the function calls, etc.
mbedtls_aes_context aes;
unsigned char key[16];
size_t plainText_len = 64;
unsigned int nc_off = 0;
unsigned char nonce_counter[16] = {0};
unsigned char stream_block[16] = {0};
unsigned char plainText[64] = {0x48, 0x45, 0x4c, 0x4c, 0x4f};
unsigned char encryptText[64];
unsigned char decryptText[64];
memcpy(key, key_128, 16); //key_128 comes from a different file
//Print Key
printf("aes Key: \n");
for(int i = 0; i < 16; i++){
printf("%x",key[i]);
}
printf("\n");
//Print plain-text
printf("aes plainText: \n");
for(int i = 0; i < 5; i++){
printf("%x",plainText[i]);
}
printf("\n");
esp_aes_init(&aes); //context is initialized
esp_aes_setkey(&aes, key, 128); //key is associated to context
esp_aes_crypt_ctr(&aes, plainText_len, &nc_off, nonce_counter, stream_block, plainText, encryptText); //encrypt
//Print encrypt-text
printf("aes encryptText: \n");
for(int i = 0; i < 5; i++){
printf("%x",encryptText[i]);
}
printf("\n");
esp_aes_crypt_ctr(&aes, plainText_len, &nc_off, nonce_counter, stream_block, encryptText, decryptText); //decrypt
//Print decrypt-text
printf("aes decrypt: \n");
for(int i = 0; i < 5; i++){
printf("%x",decryptText[i]);
}
printf("\n");
After the encrypt function is called a second time the resulting decryptText should be the same as the original plain-text, however, at the moment plainText =/= decryptText.
This is what my monitor is printing:
aes key: 7d3043fb95355e6ccd850ad8debc279
aes plainText: 48454c4c4f
aes encryptText: 852b97da59
aes decryptText: 814268329f
As you can see, I'm missing something that'll properly decrypt the encryptText!