cmbedtls

How does mbedtls_pk_encrypt dispatch to RSA?


I am using mbedtls v 2.28.1 and trying to encrypt a message with a PK, obtained by parsing a DER encoded certificate ( using mbedtls_x509_crt_parse_der() ) function. As a result, i have a valid mbedtls_pk_context populated.

Now, if i use the mbdetls_pk_encrypt(), passing it among other params the previously obtained mbedtls_pk_context, i notice that the underlying encryption routine rsa_encrypt_wrap() ends up converting a mbdetls_pk_context into an mbedtls_rsa_context (mbedtls_rsa_context * rsa = (mbedtls_rsa_context *) ctx) However, these are very different objects ...

Is that a bug ? or am i missing something ? Thanks, Jacque


Solution

  • mbedtls_pk_encrypt uses ctx->pk_info as a method table, where *ctx is the mbedtls_pk_context object. It passes the data part of the context to the method: ctx->pk_info->encrypt_func( ctx->pk_ctx, … ). rsa_encrypt_wrap is the encryption method for RSA keys. What it receives as its ctx argument is the pk_ctx field of the mbedtls_pk_context object, not a pointer to the mbedtls_pk_context object.

    When the mbedtls_pk_context contains an RSA key, the pk_ctx field is a pointer to an mbedtls_rsa_context.