Page 1 of 1

Sample code to encrypt string using AES TLS library in esp32

Posted: Wed Dec 29, 2021 4:51 pm
by tsctrl
Hi all,

anyone have sample code how to encrypt string in esp32?

i have this currently working but is not recommended approach and is only able to encrypt 16 characters

mbedtls_aes_context aes;

char * key = "abcdefghijklmnop";
char *input = "abcdefghijklmnop";
unsigned char output[16];

mbedtls_aes_init(&aes);
mbedtls_aes_setkey_enc(&aes, (const unsigned char*) key, strlen(key) * 8);
mbedtls_aes_crypt_ecb(&aes, MBEDTLS_AES_ENCRYPT, (const unsigned char*)input, output);
mbedtls_aes_free(&aes);

char result[50];
result[0] = '\0';
for (int i = 0; i < 32; i++) {
char str[3];
sprintf(str, "%02x", (int)output);
strlcat(result, str, sizeof(result));
Serial.print(str);
}
Serial.print(result);

thank you

Re: Sample code to encrypt string using AES TLS library in esp32

Posted: Wed Dec 29, 2021 6:16 pm
by chegewara

Re: Sample code to encrypt string using AES TLS library in esp32

Posted: Thu Dec 30, 2021 3:09 pm
by tsctrl
thanks, i have see that and try before. but the example is using empty iv where i cant use it. the empty iv did work but i did not successfully get it to work with some iv value set to the encryption.

did you try using the random iv to encrypt then decrypt?

i am using esp_random() to generate the iv but no success. the result generated after the decryption is unreadable character.
the issue is in the iv generated from bytes. the text can be decrypted but with non readable content.

i am using 128 ctr.

Re: Sample code to encrypt string using AES TLS library in esp32

Posted: Thu Dec 30, 2021 6:27 pm
by chegewara
Im guessing you made common mistake, which i did when i made that example too.
Then IV is changed during encryption/decryption by code, which means you cant use the same char array to do both in the same code.
Best way is to keep 1 copy as const char array, then before encrypt/decrypt copy it into arrays used in process.

Re: Sample code to encrypt string using AES TLS library in esp32

Posted: Thu Dec 30, 2021 6:58 pm
by tsctrl
that why i wondering why there is two variable of vi in your example. not really get what does the iv change during the encrypt and decrypt. did you print the iv value after encrypt and saw the value was changed?

probably is this why my iv to hex value was wrong it the other question i posted? i use the iv to encrypt then convert it to hex but the value from it was wrong.

thanks!

Re: Sample code to encrypt string using AES TLS library in esp32

Posted: Fri Dec 31, 2021 2:21 am
by tsctrl
thank you @chegewara for pointing it out, indeed the libs change the iv value last bytes and after i use two iv variable the decode looks correct!

thanks again!