MbedTLS rsa encryption/decryption errors

matas_s
Posts: 3
Joined: Sun Dec 10, 2023 10:11 am

MbedTLS rsa encryption/decryption errors

Postby matas_s » Sun Dec 10, 2023 10:25 am

On the ESP32-C3-Mini I'd like to use mbed tls library to encrypt and decrypt data with RSA-2048 algorithm. However I encounter many bugs.

Describe the bug
When using MbedTLS library

Code: Select all

mbedtls_pk_encrypt
and

Code: Select all

mbedtls_pk_decrypt
functions I get errors (0x44A0 or 0x3E80), even though its an example code from https://mbed-tls.readthedocs.io/en/late ... -with-rsa/ website. I can't figure it out how to perform RSA operations on ESP32 with this library. Any chance anyone had success?

To Reproduce:

Code: Select all

int ret = 0;
    mbedtls_pk_context pk;
    mbedtls_ctr_drbg_context ctr_drbg;
    mbedtls_pk_init(&pk);
    mbedtls_ctr_drbg_init(&ctr_drbg);
    /*
     * Read the RSA public key
     */
    if ((ret = mbedtls_pk_parse_public_key(&pk, ConstParams::RSA_PUB_KEY, 452)) != 0)
    {
        printf(" failed\n  ! mbedtls_pk_parse_public_keyfile returned -0x%04x\n", -ret);
    }

    unsigned char buf[MBEDTLS_MPI_MAX_SIZE];
    size_t olen = 0;

    /*
     * Calculate the RSA encryption of the data.
     */
    printf("\n  . Generating the encrypted value");
    const unsigned char to_encrypt[] = "Hello World!";
    const size_t to_encrypt_len = sizeof(to_encrypt);
    if ((ret = mbedtls_pk_encrypt(&pk, to_encrypt, to_encrypt_len + 1,
                                  buf, &olen, sizeof(buf),
                                  mbedtls_ctr_drbg_random, &ctr_drbg)) != 0)
    {

        printf(" failed\n  ! mbedtls_pk_encrypt returned %d\n", -ret);
    }
    ESP_LOG_BUFFER_HEX("encrypted", buf, olen);
   

Code: Select all

ConstParams::RSA_PUB_KEY
holds public key in string format.

Expected behavior
Correct encryption and decryption of any given input.

ESP_harshal
Posts: 24
Joined: Wed Jul 06, 2022 8:36 am

Re: MbedTLS rsa encryption/decryption errors

Postby ESP_harshal » Mon Dec 11, 2023 10:37 am

Hello @matas_s,

You could refer to their (mbedtls's) test as an example of the usage of those APIs. https://github.com/Mbed-TLS/mbedtls/blo ... _encrypt.c

We also have a test (ref: https://github.com/espressif/esp-idf/bl ... #L463-L468) in ESP-IDF that performs RSA encryption and decryption operations and thus can also be helpful to you.

MicroController
Posts: 1708
Joined: Mon Oct 17, 2022 7:38 pm
Location: Europe, Germany

Re: MbedTLS rsa encryption/decryption errors

Postby MicroController » Mon Dec 11, 2023 1:18 pm

mbedtls_strerror(...) may also be helpful.

Who is online

Users browsing this forum: Majestic-12 [Bot] and 112 guests