ECDH with X509 certificate and private key

Target: Establish shared secret key between PC application (master) and (various, different, but always limited to 1 at a time) devices.

Each device contains:

  • Device specific ECC 256-bit private key, in PEM format, well parsed with mbedtls_pk_parse_key function
  • Device specific certificate that belongs to the private key. Certificate is signed by the TrustCA. Parsing works well with mbedtls_x509_crt_parse
  • TrustCA’s certificate, used to validate the master device during communication

PC application contains:

  • Master Certificate, signed by TrustCA
  • Private key of the PC application
  • TrustCA’s certificate, used to validate slave’s certificate during communication

Aim is to establish AES shared secret, by doing:

  • Slave sends certificate to master
  • Master authenticates the slave with challenge/response mechanism + authenticates the certificate if valid & signed with their private key…
  • At this point, master holds slave’s certificate
  • Master sends its certificate to the slave, now both hold X509 certificates.
  • A computation with its respective private key is needed on both sides, and we have shared secret.

What is the correct way in mbedTLS, to get public key from X509, that can be used in the ECDH module?

The way ECDH module inside mbedTLS is designed, there is no straight-forward way to export X5090’s public key, get its parameters and use in ECDH module. Instead, ECDH expects that random keypair will be generated every-time we want key exchange. Doing this, we risk man in the middle attack, since other party doesn’t know where is actually key coming from.

For the moment, the solution I see (which is not THAT elegant, or is it?), and to avoid man in the middle attack::

  • Devices still exchange certificates, but only for authentication reason
  • Every message that is sent between devices (for instance public keys exchange), must also be hashed & signed, so that another party can be sure message is coming from the device which shared the certificate just before (and certificate is signed by TrustCA)
  • We need one more step before we establish shared secret.

Is this the proposed solution in this case? Is there more elegant solution with mbedTLS library for this problem?

Thanks