ECDH compute shared key length

Hi,

I’m trying to generate a key using ECDH key exchange for my AES-GCM encryption. I found out that ECDH generates keys with length of 254, 255 or 256 bits. AES-GCM only accepts 128, 192, 256.

Is the ECDH supposed to generate keys < 256bits? Or should i just use these smaller keys as “256” bit keys?

Thanks!

Hi @larjae
Thank you for your question and for your interest in Mbed TLS!

Please note that ECDH is not a key generation function, but a scheme to exchange secrets.

If you wish to generate a key locally, I suggest you follow the instructions in Generating an AES key — Mbed TLS documentation.

If you wish to share a key between your application and a remote peer ( e.g. client - server ), you should use ECDH key exchange algorithm, to exchange a key material, out of which your AES key should be derived using an agreed Key Derivation Function( KDF ) , which the key material would be given as input.
See code in TLS stack, for example:

Does this make sense?
Regards,
Mbed TLS Team member
Ron

Hey Ron,

Thanks for your answer.

I am indeed sharing a key between server and client. I think I got the KDF wrong. I generated a shared key? using mbedtls_ecdh_compute_shared . I am extracting the shared secret MPI (z) using mbedtls_mpi_write_binary. I guess I need to use mbedtls_ecdh_calc_secret instead. Is this correct?

Thanks!
Lars

Hi Lars,
Yes, for calculating the secret, you should be calling mbedtls_ecdh_calc_secret().

please loook at the example programs for dh_client and dh_server key exchange. Although this is for DHM algorithm, and not ECDH, the flow is similar.
You can also look at the ecdh test suite to understand what the client and server do in ecdh.
I hope this helps.
Regards,
Ron

Hi Lars,
One comment, you can use mbedtls_ecdh_compute_shared() to compute the shared secret as well.
Anyway, the shared secret is an MPI, and not a cipher key. This MPI should be used to derive the cipher key.
Regards,
Ron

Hey Ron,

Thanks! I will try that!

Lars