RSA-512 Encryption Problem on ESP32 (RSA - Bad input parameters to function)

mbedtls_mpi E, P, Q, N, H, D, X, Y, Z;
int ret;
mbedtls_rsa_context rsa;
char *plainText = “Tech tutorials x”;

mbedtls_rsa_init( &rsa , MBEDTLS_RSA_PKCS_V15, 0);
const char *modulus_N = “1dc34e114f973dd34484d1021270298f51d3b54256e4b3815e82c55fedbc1329ad130c7a661e797fe9143e7bfdbeab99d26c03959f2c5fad6b5cee0f35f1c32e5”;
const char *publicExponent_E = “010001”;
const char *privateExponent_D = “1c3488d818e01024158bf4728d3ca3f6012aab5cc9f20436f674e14d4e836c79693474b16af5a659077cd8da8f088d4483df2a970bc8f93e9db59e4965493c2e5”;
const char *prime1_P = “11ecc037f9c9fcf6756287576f47e038f60b4c1f602d65798530e594452edc6b7”;
const char *prime2_Q = “1a91204665eb8fcff5413e4a645dce5edf9e72df4ee0af6cb0eb83438e56f5743”;
mbedtls_mpi_init(&N); mbedtls_mpi_init(&P); mbedtls_mpi_init(&Q); mbedtls_mpi_init(&D); mbedtls_mpi_init(&E);
(mbedtls_mpi_read_string(&N, 16, modulus_N));
(mbedtls_mpi_read_string(&E, 16, publicExponent_E));
(mbedtls_mpi_read_string(&D, 16, privateExponent_D));
(mbedtls_mpi_read_string(&P, 16, prime1_P));
(mbedtls_mpi_read_string(&Q, 16, prime2_Q));

if ((ret = mbedtls_rsa_import(&rsa, &N, &P, &Q, &D, &E)) != 0) Serial.print(“1”);
if ((ret = mbedtls_rsa_complete(&rsa)) != 0) Serial.print(“2”);
if ((ret = mbedtls_rsa_check_privkey(&rsa)) != 0) Serial.print(“3”);
if ((ret = mbedtls_rsa_check_pubkey(&rsa)) != 0) Serial.print(“4”);
if ((ret = mbedtls_rsa_validate_params(&N, &P, &Q, &D, &E, NULL, NULL)) != 0) Serial.print(“5”);

unsigned char* out;
// invalid here
ret = mbedtls_rsa_pkcs1_encrypt(&rsa, NULL, NULL, 0, (size_t) strlen(plainText), (const unsigned char*)plainText , (unsigned char * ) out);
if (ret != 0)
char buf[1024];
mbedtls_strerror(ret, buf, sizeof buf);
Serial.printf(“result: %s\n”, buf);

  • Function mbedtls_rsa_pkcs1_encrypt() Always return -0x4080 (RSA - Bad input parameters to function) I’m new. What did I do wrong?. Thanks in advance .

Hi @jirawin9
In addition to the fact that you are using an unitialized out parameter to mbedtls_rsa_pkcs1_encrypt(), the root cause for your failure is becuase you are sending a NULL f_rng funciton:

        if( f_rng == NULL )
            return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );

As documented in the function description:

 * \param f_rng    The RNG to use. It is mandatory for PKCS#1 v2.1 padding
 *                 encoding, and for PKCS#1 v1.5 padding encoding when used
 *                 with \p mode set to #MBEDTLS_RSA_PUBLIC.

Mbed TLS Team member