Compare public keys (Public key pinning)

Given a mbedtls_x509_crt certificate (in a verify callback) and a mbedtls_pk_context public key - is there an API to check whether the certificate’s public key matches the given public key? To realize public key pinning.

Of course both public keys could be serialized to DER format and perform a byte-wise memory comparison - but I would like to avoid the overhead and temporary buffer allocation.

Hi @nthuemmel
Unfortunately, there isn’t an API to compare two mbedtls_pk_context structs.
However, instead of serializing to DER, and doing a memcmp, you could consider calling mbedtls_pk_get_type() to check if it is same (although MBEDTLS_PK_ECKEY, MBEDTLS_PK_ECKEY_DH and MBEDTLS_PK_ECDSA can be same public key ), and if the types are the same, you should call mbedtls_ecp_point_cmp() for ECC key and mbedtls_mpi_cmp_mpi() for RSA on the internal public key member of the context.
This is not ideal, as I wouldn’t recommend accessing internal members of structures, but this is what currently available

Mbed TLS Team member

Hi Ron,

Thank you very much for your answer! I just wanted to make sure I haven’t missed any public API in this regard. Thank you for providing a more efficient solution, I will try it.