In some cases you only have the base values for RSA at your disposal and want to use those within mbed TLS. mbed TLS, or specifically the mbedtls_rsa_context structure, requires more than the base values in order to perform optimized operations for RSA.

Luckily, you are able to extract those other values if you have access to your E, P and Q! In most cases you alread have your N, so you can skip the next section.

For the following example, we assume that you have already correctly initialized the RSA context named ctx and loaded the values for P, Q and E into the mbedtls_rsa_context.

Getting the modulus (N)

Calculating the modulus (N) is done as follows:

MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &ctx.N, &ctx.P, &ctx.Q ) );

Fill the context

In order to fill all the other values within the context you can use the following sequence of function calls. You will have to define and initialize the appropriate variables such as P1.

MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &P1, &ctx.P, 1 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &Q1, &ctx.Q, 1 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &H, &P1, &Q1 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( &ctx.D , &ctx.E, &H  ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &ctx.DP, &ctx.D, &P1 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &ctx.DQ, &ctx.D, &Q1 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( &ctx.QP, &ctx.Q, &ctx.P ) );

And finally, we set the length field in the mbedtls_rsa_context:

ctx.len = mbedtls_mpi_size( &ctx.N );

Check RSA key consistency

If you want to check correctness of all values in your context, use mbedtls_rsa_check_privkey().

Did this help?