Skip to content

X25519

Header: #include <cryptopp/xed25519.h> | Namespace: CryptoPP Since: Crypto++ 8.0

X25519 is the Diffie-Hellman function on Curve25519, specified in RFC 7748. Two parties exchange 32-byte public keys and each computes the same 32-byte shared secret. X25519 by itself does not authenticate the other party; a protocol that needs to know who it is talking to must add signatures or another form of authentication.

Quick Example

#include <cryptopp/xed25519.h>
#include <cryptopp/osrng.h>
#include <cryptopp/misc.h>
#include <iostream>
#include <stdexcept>

int main() {
    using namespace CryptoPP;

    AutoSeededRandomPool rng;

    // Alice generates her key pair
    x25519 alice;
    SecByteBlock alicePrivate(x25519::SECRET_KEYLENGTH);
    SecByteBlock alicePublic(x25519::PUBLIC_KEYLENGTH);
    alice.GenerateKeyPair(rng, alicePrivate, alicePublic);

    // Bob generates his key pair
    x25519 bob;
    SecByteBlock bobPrivate(x25519::SECRET_KEYLENGTH);
    SecByteBlock bobPublic(x25519::PUBLIC_KEYLENGTH);
    bob.GenerateKeyPair(rng, bobPrivate, bobPublic);

    // Both compute the same shared secret
    SecByteBlock aliceShared(x25519::SHARED_KEYLENGTH);
    SecByteBlock bobShared(x25519::SHARED_KEYLENGTH);

    if (!alice.Agree(aliceShared, alicePrivate, bobPublic))
        throw std::runtime_error("Alice's key agreement failed");

    if (!bob.Agree(bobShared, bobPrivate, alicePublic))
        throw std::runtime_error("Bob's key agreement failed");

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

    return same ? 0 : 1;
}

Usage Guidelines

Do:

  • Generate keys with AutoSeededRandomPool
  • Check the return value of Agree(); it returns false when the other party’s public key has small order
  • Derive working keys from the shared secret with a KDF such as HKDF
  • Use a fresh (ephemeral) key pair per session where forward secrecy matters
  • Authenticate the exchange (for example with Ed25519 signatures) when the peer’s identity matters

Avoid:

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

Class: x25519

Elliptic curve Diffie-Hellman key exchange using Curve25519. The key-agreement functions take the keys as arguments, so one x25519 object can serve any number of key pairs.

Constants

static const int SECRET_KEYLENGTH = 32;  // Private key size (256 bits)
static const int PUBLIC_KEYLENGTH = 32;  // Public key size (256 bits)
static const int SHARED_KEYLENGTH = 32;  // Shared secret size (256 bits)

Constructors

Default Constructor

x25519();

Create an X25519 object that holds no key pair. This is enough for GenerateKeyPair() and Agree(), which work on caller-supplied buffers.

Example:

x25519 kex;

Constructor with RNG

x25519(RandomNumberGenerator& rng);

Create an X25519 object that holds a newly generated key pair. The object can then save the pair with Save() or check it with Validate().

Parameters:

  • rng - Random number generator (use AutoSeededRandomPool)

Example:

AutoSeededRandomPool rng;
x25519 kex(rng);  // Holds a new key pair

Constructor with Private Key

x25519(const byte x[SECRET_KEYLENGTH]);

Create X25519 object from existing private key. Public key is computed.

Parameters:

  • x - 32-byte private key

Example:

SecByteBlock privateKey(x25519::SECRET_KEYLENGTH);
// ... load the 32 key bytes into privateKey ...
x25519 kex(privateKey);  // Public key computed from private

Constructor with Both Keys

x25519(const byte y[PUBLIC_KEYLENGTH], const byte x[SECRET_KEYLENGTH]);

Create X25519 object from existing key pair.

Parameters:

  • y - 32-byte public key
  • x - 32-byte private key

Note: The constructor does not check the keys. Call Validate() on keys from outside sources.

Example:

SecByteBlock publicKey(x25519::PUBLIC_KEYLENGTH), privateKey(x25519::SECRET_KEYLENGTH);
// ... load keys ...
x25519 kex(publicKey, privateKey);

Methods

GenerateKeyPair()

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

Generate a new key pair into the caller’s buffers. The private key is clamped.

Parameters:

  • rng - Random number generator
  • privateKey - Output buffer (32 bytes)
  • publicKey - Output buffer (32 bytes)

Example:

AutoSeededRandomPool rng;
SecByteBlock privateKey(x25519::SECRET_KEYLENGTH);
SecByteBlock publicKey(x25519::PUBLIC_KEYLENGTH);

x25519 kex;
kex.GenerateKeyPair(rng, privateKey, publicKey);

GeneratePrivateKey()

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

Generate a new private key only.

Parameters:

  • rng - Random number generator
  • privateKey - Output buffer (32 bytes)

Example:

AutoSeededRandomPool rng;
SecByteBlock privateKey(x25519::SECRET_KEYLENGTH);

x25519 kex;
kex.GeneratePrivateKey(rng, privateKey);

GeneratePublicKey()

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

Derive public key from private key.

Parameters:

  • rng - Random number generator (not used; the interface requires it)
  • privateKey - 32-byte private key
  • publicKey - Output buffer (32 bytes)

Example:

AutoSeededRandomPool rng;
SecByteBlock privateKey(x25519::SECRET_KEYLENGTH);
SecByteBlock publicKey(x25519::PUBLIC_KEYLENGTH);

x25519 kex;
kex.GeneratePrivateKey(rng, privateKey);
kex.GeneratePublicKey(rng, privateKey, publicKey);

Agree()

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

Perform key exchange to compute shared secret.

Parameters:

  • agreedValue - Output shared secret (32 bytes)
  • privateKey - Your private key (32 bytes)
  • otherPublicKey - Other party’s public key, exactly 32 bytes. The function takes no length, so check the length of a received key first
  • validateOtherPublicKey - Reject public keys of small order (default: true)

Returns: true on success. With validation on, false if otherPublicKey is one of the small-order points; the output buffer is then not written.

Important: Always check the return value. A small-order public key forces the shared secret to a value an attacker knows.

Contributory behaviour: RFC 7748 section 6.1 allows a protocol to check the shared secret for the all-zero value and abort. Keep validation on. Where the protocol requires contributory behaviour, also compare the shared secret with 32 zero bytes in constant time after Agree() succeeds, and abort on a match.

Example:

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

SecByteBlock sharedSecret(x25519::SHARED_KEYLENGTH);

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

// Use sharedSecret with HKDF to derive encryption keys

ClampKey()

void ClampKey(byte x[SECRET_KEYLENGTH]) const;

Clamp a private key as RFC 7748 section 5 describes.

Parameters:

  • x - Private key to clamp (modified in-place)

Details: Clears the three low bits of the first byte, clears the top bit of the last byte and sets the next bit: x[0] &= 248, x[31] &= 127, x[31] |= 64

Note: Keys generated by the library are already clamped.

Example:

SecByteBlock privateKey(x25519::SECRET_KEYLENGTH);
// ... load 32 random bytes into privateKey ...

x25519 kex;
kex.ClampKey(privateKey);

IsClamped()

bool IsClamped(const byte x[SECRET_KEYLENGTH]) const;

Check if a private key is properly clamped.

Parameters:

  • x - Private key to check

Returns: true if key is clamped, false otherwise

IsSmallOrder()

bool IsSmallOrder(const byte y[PUBLIC_KEYLENGTH]) const;

Check whether a public key is one of the known small-order points.

Parameters:

  • y - Public key to check

Returns: true if the key has small order and must be rejected, false otherwise

Note: Agree() makes this check itself when validateOtherPublicKey is true.

Validate()

bool Validate(RandomNumberGenerator& rng, unsigned int level) const;

Validate the key pair held by the object.

Parameters:

  • rng - Random number generator (not used)
  • level - Validation level, 0 to 3

Returns: true if the keys pass. Level 1 checks that the private key is clamped, level 2 adds the small-order check on the public key, and level 3 adds a check that the public key matches the private key.

Complete Example: Deriving a Key with HKDF

#include <cryptopp/xed25519.h>
#include <cryptopp/osrng.h>
#include <cryptopp/hkdf.h>
#include <cryptopp/sha.h>
#include <cryptopp/misc.h>
#include <cstring>
#include <iostream>

int main() {
    using namespace CryptoPP;

    AutoSeededRandomPool rng;
    x25519 kex;

    // Each side generates an ephemeral key pair and sends its public key
    SecByteBlock alicePrivate(x25519::SECRET_KEYLENGTH), alicePublic(x25519::PUBLIC_KEYLENGTH);
    SecByteBlock bobPrivate(x25519::SECRET_KEYLENGTH), bobPublic(x25519::PUBLIC_KEYLENGTH);
    kex.GenerateKeyPair(rng, alicePrivate, alicePublic);
    kex.GenerateKeyPair(rng, bobPrivate, bobPublic);

    // Each side combines its private key with the other's public key
    SecByteBlock aliceShared(x25519::SHARED_KEYLENGTH), bobShared(x25519::SHARED_KEYLENGTH);
    if (!kex.Agree(aliceShared, alicePrivate, bobPublic) ||
        !kex.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 = VerifyBufsEqual(aliceKey, bobKey, aliceKey.size());
    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.

Security

Security Properties

  • Security level: about 128 bits
  • Key size: 256 bits (32 bytes)
  • Shared secret size: 256 bits (32 bytes)
  • Algorithm: Elliptic Curve Diffie-Hellman on Curve25519
  • Standard: RFC 7748

Security Best Practices

  1. Keep public-key validation on:

    // theirPublic has already been checked to be kex.PublicKeyLength() bytes.
    // Validates by default
    if (!kex.Agree(shared, myPrivate, theirPublic))
        throw std::runtime_error("X25519: the other public key was rejected");
  2. Derive keys with a KDF. Pass the shared secret through HKDF, as in the complete example above, instead of using it as a cipher key.

  3. Use ephemeral keys for forward secrecy. Generate a new key pair for each session and discard the private key when the session ends. A long-term key pair used for every session exposes all of them if it is ever compromised.

  4. Keep private keys in SecByteBlock:

    SecByteBlock privateKey(x25519::SECRET_KEYLENGTH);  // Wiped on destruction
    

Test Vector (RFC 7748 Section 6.1)

#include <cryptopp/xed25519.h>
#include <cryptopp/misc.h>
#include <iostream>

int main() {
    using namespace CryptoPP;

    const byte alicePrivate[32] = {
        0x77, 0x07, 0x6d, 0x0a, 0x73, 0x18, 0xa5, 0x7d,
        0x3c, 0x16, 0xc1, 0x72, 0x51, 0xb2, 0x66, 0x45,
        0xdf, 0x4c, 0x2f, 0x87, 0xeb, 0xc0, 0x99, 0x2a,
        0xb1, 0x77, 0xfb, 0xa5, 0x1d, 0xb9, 0x2c, 0x2a
    };

    const byte bobPublic[32] = {
        0xde, 0x9e, 0xdb, 0x7d, 0x7b, 0x7d, 0xc1, 0xb4,
        0xd3, 0x5b, 0x61, 0xc2, 0xec, 0xe4, 0x35, 0x37,
        0x3f, 0x83, 0x43, 0xc8, 0x5b, 0x78, 0x67, 0x4d,
        0xad, 0xfc, 0x7e, 0x14, 0x6f, 0x88, 0x2b, 0x4f
    };

    const byte expectedShared[32] = {
        0x4a, 0x5d, 0x9d, 0x5b, 0xa4, 0xce, 0x2d, 0xe1,
        0x72, 0x8e, 0x3b, 0xf4, 0x80, 0x35, 0x0f, 0x25,
        0xe0, 0x7e, 0x21, 0xc9, 0x47, 0xd1, 0x9e, 0x33,
        0x76, 0xf0, 0x9b, 0x3c, 0x1e, 0x16, 0x17, 0x42
    };

    x25519 kex;
    byte sharedSecret[32];
    bool ok = kex.Agree(sharedSecret, alicePrivate, bobPublic) &&
              VerifyBufsEqual(sharedSecret, expectedShared, 32);

    std::cout << (ok ? "MATCH" : "MISMATCH") << std::endl;

    return ok ? 0 : 1;
}

Sizes

AlgorithmPublic keyShared secretSecurity strength
X2551932 bytes32 bytesAbout 128 bits
ECDH P-25665 bytes uncompressed, 33 compressed32 bytes128 bits
Finite-field DH, 2048-bit256 bytes256 bytes112 bits

cryptest b measures key-agreement speed on your own hardware.

When to Use X25519

Use X25519 for:

  1. Key exchange - Establishing a shared secret between two parties
  2. Forward secrecy - Ephemeral key pairs are cheap to generate
  3. Protocols that specify it - For example TLS 1.3 and WireGuard

Don’t use X25519 for:

  1. Digital signatures - Use Ed25519 instead
  2. Encryption by itself - X25519 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 x25519 object in each thread.

void threadFunc() {
    AutoSeededRandomPool rng;
    x25519 kex(rng);  // One per thread
    // ... use kex ...
}

Exceptions

  • BERDecodeErr - A DER-encoded key passed to Load() or the BufferedTransformation constructor could not be parsed

A rejected public key is reported by Agree() returning false, not by an exception.

Algorithm Details

  • Curve: Curve25519 (Montgomery curve)
  • Field: Prime field with p = 2^255 - 19
  • Cofactor: 8
  • Standard: RFC 7748
  • Implementation: Based on curve25519-donna by Andrew Moon

See Also

References

  1. RFC 7748: Elliptic Curves for Security
  2. Curve25519: new Diffie-Hellman speed records (Bernstein)
  3. RFC 8410: Algorithm Identifiers for Ed25519, Ed448, X25519, and X448 for Use in the Internet X.509 Public Key Infrastructure