Skip to main content

Diffie-Hellman key exchange

The process for Diffie-Hellman key exchange in Crypto Interface is analogous to that for ECDH key exchange, except the domain parameters define a cyclic group in a finite field rather than on an elliptic curve. The domain parameters may be set by choosing one of the predefined built-in safe groups (see, for example, RFC5114, RFC3526, or RFC7919), or by setting the domain parameters directly in the context.


The word “context” rather than “key” is used with respect to Diffie-Hellman, but those two words are essentially interchangeable.

The following methods may be used to allocate a context:


  • CRYPTO_INTERFACE_DH_allocateServer

  • CRYPTO_INTERFACE_DH_allocateClientAux

The first API, CRYPTO_INTERFACE_DH_allocate, does not set any domain parameters.

The other two APIs, CRYPTO_INTERFACE_DH_allocateServer and CRYPTO_INTERFACE_DH_allocateClientAux, take in a groupNum parameter from the header ${MSS_SRC_PKG}/src/dh.h. In addition, the allocateServer API generates a private/public key pair, while the allocate client API generates only the private key. For example, if a server is used to perform allocation and key generation on the 2048-bit group known as group 14, call:

CRYPTO_INTERFACE_DH_allocateServer (g_pRandomContext, &pMyNewPrivCtx, DH_GROUP_14);

To obtain the public key to send to the client, call:

CRYPTO_INTERFACE_DH_getPublicKey (pMyNewPrivCtx, &pMyPubKey, &myPubLen);

A buffer is allocated to hold “my private key” (pMyNewPrivCtx) in big-endian byte array form, and pMyPubKey is set to its location. Once the client’s (i.e., other party’s) public key is obtained, a copy of the shared secret may be generated by calling:

CRYPTO_INTERFACE_DH_computeKeyExchangeEx(pMyNewPrivCtx, NULL, pOtherPublicKey, otherPubLen, &pSharedSecret, &sharedSecretLen);

pMyNewPrivCtx is still in diffieHellmanContext form, but the other party’s public key is in big-endian byte array form. A buffer to hold the resulting shared secret is allocated, and pSharedSecret is set to its location. To perform exponent blinding for a higher security but lower performance trade-off, a non-NULL RNG pRandomContext may be passed for the second parameter.


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 using alternative APIs may be found at:


To perform asymmetric key clean up and free memory allocated for a key, call the appropriate method:





However, for a key stored inside an AsymmetricKey structure, use the CRYPTO_uninitAsymmetricKey API instead to free all memory associated with the underlying key.