RSA encryption/decryption works in Mbed TLS when using separate buffers where plainText, cipherText, and decryptedText (i.e. the content of plainText and decryptedText) are the same.
However, it does not when using just one buffer to perform in-place encryption/decryption. In that case I get gibberish/not correctly encrypted data. Is that just a general limitation or is my code wrong?
It says here that "In place cipher is allowed in Mbed TLS, unless specified otherwise." I'm not sure if they are talking about AES or RSA though. I didn't see any remark indicating "otherwise" for OAEP encryption/decryption so I presumed it should work.
Code:
size_t sizeDecrypted;
unsigned char plainText[15000] = "yxcvbnm";
unsigned char cipherText[15000];
unsigned char decryptedText[15000];
rtn = mbedtls_rsa_rsaes_oaep_encrypt(&rsa, mbedtls_ctr_drbg_random, &ctr_drbg, NULL, 0, sizeof("yxcvbnm"), &plainText, &cipherText);
rtn = mbedtls_rsa_rsaes_oaep_decrypt(&rsa, mbedtls_ctr_drbg_random, &ctr_drbg, NULL, 0, &sizeDecrypted, &cipherText, &decryptedText, 15000);
//decryptedText afterwards contains the correctly decrypted text just like plainText
//sizeDecrypted is 8 (because of the binary zero at the end of the string)
unsigned char text[15000] = "yxcvbnm";
rtn = mbedtls_rsa_rsaes_oaep_encrypt(&rsa, mbedtls_ctr_drbg_random, &ctr_drbg, NULL, 0, sizeof("yxcvbnm"), &text, &text);
rtn = mbedtls_rsa_rsaes_oaep_decrypt(&rsa, mbedtls_ctr_drbg_random, &ctr_drbg, NULL, 0, &sizeDecrypted, &text, &text, 15000);
//someText afterwards doesn't contain the correctly decrypted text/has a different content than plainText
//rtn is always 0, i.e. no error is returned
//sizeDecrypted is 8
No, this will not work.
From the repo https://github.com/Mbed-TLS/mbedtls we look at
library/rsa.cto get the body ofmbedtls_rsa_rsaes_oaep_encrypt:Note the following:
After some initial integrity checks, we have:
If
output == input, this trashes the input buffer (or portion thereof) before the input buffer is examined.So, the buffers must be distinct and non-overlapping.