Skip to main content

ECDH key exchange

The two main components of ECDH (and finite-field Diffie-Hellman) are:

  1. Send the public key to the other party.

  2. Compute the copy of a shared secret from the private key using the other party’s public key.

To handle the first component, your application may obtain the size of the public key by calling:

CRYPTO_INTERFACE_EC_getPointByteStringLenAux(pMyKey, &pubKeyLen);

Then, with a buffer pBuffer of pubKeyLen bytes, obtain the public key by calling:

CRYPTO_INTERFACE_EC_writePublicKeyToBufferAux(pMyKey, pBuffer, pubKeyLen);

The form of the public key is the standard serialized forms. For prime field curves, the form is an 0x04 byte followed by the x-coordinate, and then the y-coordinate in big-endian. For the Edward’s curves, this is the usual compressed form (see RFC 7748).

To compute the shared secret, call:

CRYPTO_INTERFACE_ECDH_generateSharedSecretFromPublicByteStringAux(pMyKey, pOtherPubKey, otherPubKeyLen, &pSharedSecret, &sharedSecretLen, 1, NULL);

where pMyKey is the private key still in ECCKey structure form, but pOtherPubKey is the other party’s public key in a serialized form. The pointer pSharedSecret is set to the location of an allocated buffer holding the resulting secret, and sharedSecretLen is set to its length in bytes. The flag 1 instructs the method to perform just the usual x-coordinate shared secret calculation, and the last parameter is an unused placeholder for a future key derivation function (KDF) callback.


The shared secret should never be used directly by an application, but should instead be digested or input into a KDF scheme to obtain usable key material.

Complete example

A complete example and use of the alternate API to generate shared secret from keys may be found at: