Skip to content

ECDH

Header: #include <cryptopp/eccrypto.h> and #include <cryptopp/oids.h> | Namespace: CryptoPP Since: Crypto++ 3.0

ECDH (Elliptic Curve Diffie-Hellman) is a key agreement scheme: two parties exchange public keys and each computes the same shared secret. It reaches a given security strength with much smaller keys than finite-field Diffie-Hellman. ECDH by itself does not authenticate the other party.

Quick Example

#include <cryptopp/eccrypto.h>
#include <cryptopp/osrng.h>
#include <cryptopp/oids.h>
#include <cryptopp/secblock.h>
#include <iostream>

int main() {
    using namespace CryptoPP;

    AutoSeededRandomPool rng;

    // Create ECDH domain with P-256 curve
    ECDH<ECP>::Domain dh(ASN1::secp256r1());

    // Alice generates her key pair
    SecByteBlock alicePrivate(dh.PrivateKeyLength());
    SecByteBlock alicePublic(dh.PublicKeyLength());
    dh.GenerateKeyPair(rng, alicePrivate, alicePublic);

    // Bob generates his key pair
    SecByteBlock bobPrivate(dh.PrivateKeyLength());
    SecByteBlock bobPublic(dh.PublicKeyLength());
    dh.GenerateKeyPair(rng, bobPrivate, bobPublic);

    // Alice computes shared secret
    SecByteBlock aliceShared(dh.AgreedValueLength());
    if (!dh.Agree(aliceShared, alicePrivate, bobPublic)) {
        std::cerr << "Alice: Key agreement failed!" << std::endl;
        return 1;
    }

    // Bob computes shared secret
    SecByteBlock bobShared(dh.AgreedValueLength());
    if (!dh.Agree(bobShared, bobPrivate, alicePublic)) {
        std::cerr << "Bob: Key agreement failed!" << std::endl;
        return 1;
    }

    // Both parties now hold the same shared secret
    bool same = (aliceShared == bobShared);
    std::cout << "Shared secrets match: " << (same ? "YES" : "NO") << std::endl;
    std::cout << "Shared secret size: " << aliceShared.size() << " bytes" << std::endl;

    return same ? 0 : 1;
}

Usage Guidelines

Do:

  • Use P-256 (secp256r1) for general purpose, P-384 or P-521 where a higher strength is required
  • Derive working keys from the shared secret with a KDF such as HKDF
  • Use ephemeral keys where forward secrecy matters
  • Check the return value of Agree(), and leave its public-key validation on
  • Authenticate the exchange when the peer’s identity matters

Avoid:

  • Using the shared secret directly as an encryption key
  • Passing validateOtherPublicKey = false for keys received from another party

Supported Curves

The NIST prime curves most often used, with the sizes this library reports for them:

CurveOIDSecurity strengthPrivate keyPublic keyShared secret
P-256 (secp256r1)ASN1::secp256r1()128 bits32 bytes65 bytes32 bytes
P-384 (secp384r1)ASN1::secp384r1()192 bits48 bytes97 bytes48 bytes
P-521 (secp521r1)ASN1::secp521r1()256 bits66 bytes133 bytes66 bytes

The public key is the uncompressed point encoding: a 0x04 byte followed by the x and y coordinates. The shared secret is the x coordinate of the agreed point. oids.h declares many other curves, including the Brainpool and binary-field (EC2N) curves.

Class: ECDH::Domain

ECDH key agreement domain for elliptic curves.

ECDH<EC>::Domain is a typedef for DH_Domain<DL_GroupParameters_EC<EC>, COFACTOR_OPTION>. EC is ECP for prime-field curves or EC2N for binary-field curves.

Constructor

ECDH<ECP>::Domain dh(oid);     // const OID&
ECDH<ECP>::Domain dh(params);  // const DL_GroupParameters_EC<ECP>&

Parameters:

  • oid - Curve OID (e.g., ASN1::secp256r1())
  • params - Curve parameters object

Example:

// Using curve OID (recommended)
ECDH<ECP>::Domain dh(ASN1::secp256r1());

// Using P-384
ECDH<ECP>::Domain dh384(ASN1::secp384r1());

Methods

GenerateKeyPair()

void GenerateKeyPair(RandomNumberGenerator& rng,
                     byte* privateKey,
                     byte* publicKey) const;

Generate a key pair into the caller’s buffers.

Parameters:

  • rng - Random number generator
  • privateKey - Output buffer for private key
  • publicKey - Output buffer for public key

Example:

ECDH<ECP>::Domain dh(ASN1::secp256r1());

SecByteBlock privateKey(dh.PrivateKeyLength());
SecByteBlock publicKey(dh.PublicKeyLength());

dh.GenerateKeyPair(rng, privateKey, publicKey);

Agree()

bool Agree(byte* agreedValue,
           const byte* privateKey,
           const byte* otherPublicKey,
           bool validateOtherPublicKey = true) const;

Compute shared secret from private key and other party’s public key.

Parameters:

  • agreedValue - Output buffer for shared secret
  • privateKey - Your private key
  • otherPublicKey - Other party’s public key, exactly PublicKeyLength() bytes. The function takes no length, so check the length of a received key first
  • validateOtherPublicKey - Check that the public key is a valid point on the curve (default: true)

Returns: true on success, false if the other public key cannot be decoded or fails validation

Example:

// theirPublic arrived from the other party: check its length before use
if (theirPublic.size() != dh.PublicKeyLength())
    throw std::runtime_error("ECDH: wrong public key length");

SecByteBlock sharedSecret(dh.AgreedValueLength());

if (!dh.Agree(sharedSecret, myPrivate, theirPublic))
    throw std::runtime_error("ECDH: the other public key was rejected");

PrivateKeyLength()

unsigned int PrivateKeyLength() const;

Returns: Size of private key in bytes

PublicKeyLength()

unsigned int PublicKeyLength() const;

Returns: Size of public key in bytes

AgreedValueLength()

unsigned int AgreedValueLength() const;

Returns: Size of shared secret in bytes

Complete Example: Deriving a Key with HKDF

#include <cryptopp/eccrypto.h>
#include <cryptopp/osrng.h>
#include <cryptopp/oids.h>
#include <cryptopp/hkdf.h>
#include <cryptopp/sha.h>
#include <cryptopp/secblock.h>
#include <iostream>

int main() {
    using namespace CryptoPP;

    AutoSeededRandomPool rng;
    ECDH<ECP>::Domain dh(ASN1::secp256r1());

    // Each side generates an ephemeral key pair and sends its public key
    SecByteBlock alicePrivate(dh.PrivateKeyLength()), alicePublic(dh.PublicKeyLength());
    SecByteBlock bobPrivate(dh.PrivateKeyLength()), bobPublic(dh.PublicKeyLength());
    dh.GenerateKeyPair(rng, alicePrivate, alicePublic);
    dh.GenerateKeyPair(rng, bobPrivate, bobPublic);

    // Each side combines its private key with the other's public key
    SecByteBlock aliceShared(dh.AgreedValueLength()), bobShared(dh.AgreedValueLength());
    if (!dh.Agree(aliceShared, alicePrivate, bobPublic) ||
        !dh.Agree(bobShared, bobPrivate, alicePublic)) {
        std::cerr << "Key agreement failed" << std::endl;
        return 1;
    }

    // Bind both public keys into the derivation, in an order both sides agree on
    SecByteBlock info(alicePublic.size() + bobPublic.size());
    std::memcpy(info, alicePublic, alicePublic.size());
    std::memcpy(info + alicePublic.size(), bobPublic, bobPublic.size());

    // Each side derives a 32-byte key from the shared secret
    SecByteBlock aliceKey(32), bobKey(32);
    HKDF<SHA256> hkdf;
    hkdf.DeriveKey(aliceKey, aliceKey.size(), aliceShared, aliceShared.size(),
                   NULLPTR, 0, info, info.size());
    hkdf.DeriveKey(bobKey, bobKey.size(), bobShared, bobShared.size(),
                   NULLPTR, 0, info, info.size());

    bool same = (aliceKey == bobKey);
    std::cout << "Derived keys match: " << (same ? "YES" : "NO") << std::endl;

    return same ? 0 : 1;
}

This shows the API calls only. A real protocol also authenticates the public keys.

ECDH vs X25519

FeatureECDH P-256X25519
Public key65 bytes uncompressed32 bytes
Private key32 bytes32 bytes
Shared secret32 bytes32 bytes
Security strength128 bitsAbout 128 bits
SpecificationNIST SP 800-56A, SEC 1RFC 7748
Higher-strength optionsP-384, P-521X448 (not in this library)

Use ECDH when a protocol, a peer or a policy requires the NIST curves. Where either is acceptable, X25519 has smaller public keys and a simpler interface. cryptest b measures both on your own hardware.

Security

Security Properties

  • Security level: Depends on the curve (128 bits for P-256)
  • Forward secrecy: Achieved with ephemeral keys
  • Key validation: Agree() validates the other public key by default
  • Standards: NIST SP 800-56A, SEC 1, ANSI X9.63

Security Notes

  • Derive keys with a KDF: Do not use the raw shared secret as an encryption key. Pass it through HKDF or another KDF.
  • Ephemeral keys: Use new keys for each session to achieve forward secrecy.
  • Public key validation: Keep the default validation in Agree() for keys received from another party.
  • Context binding: Include both public keys in the HKDF info parameter to bind the derived keys to the exchange.
  • Static keys: One side may use a long-term key pair so the other can recognise it, but sessions under that key lose forward secrecy if it is compromised.

When to Use ECDH

Use ECDH for:

  1. NIST curve requirements - Policies or certifications that specify P-256, P-384 or P-521
  2. Interoperability - Protocols and peers that negotiate the NIST curves, such as TLS
  3. Higher strengths - P-384 and P-521 where more than 128 bits is required

Don’t use ECDH for:

  1. Digital signatures - Use ECDSA or Ed25519
  2. Encryption by itself - ECDH produces a shared secret; a cipher does the encryption
  3. Authentication by itself - Combine it with signatures or another authenticated protocol

Thread Safety

Not thread-safe. Use a separate Domain object in each thread.

Exceptions

  • UnknownOID - The constructor was given an OID that is not a recognised curve

A public key that cannot be decoded or fails validation is reported by Agree() returning false, not by an exception.

See Also

  • X25519 - Key exchange on Curve25519
  • ECDSA - Signatures with same curves
  • HKDF - Key derivation for shared secrets
  • AES-GCM - Authenticated encryption

References

  1. NIST SP 800-56A Revision 3: Recommendation for Pair-Wise Key-Establishment Schemes Using Discrete Logarithm Cryptography
  2. SEC 1: Elliptic Curve Cryptography, Version 2.0
  3. NIST SP 800-186: Recommendations for Discrete Logarithm-based Cryptography: Elliptic Curve Domain Parameters
  4. NIST SP 800-57 Part 1 Revision 5: Recommendation for Key Management