Skip to content
Public-Key Cryptography

Public-Key Cryptography

Public-key (asymmetric) cryptography uses pairs of keys: a public key for encryption or verification and a private key for decryption or signing. It lets parties who share no secret establish one, and lets anyone check a signature made by the holder of a private key.

The examples on these pages show the library calls. They are not complete protocols: a real design also has to authenticate keys, bind context into key derivation and handle errors.

Available Algorithms

X25519

Key exchange on Curve25519 (RFC 7748)

  • Diffie-Hellman key agreement
  • About 128-bit security strength
  • 32-byte keys and shared secret
  • Specified for TLS 1.3 and used by WireGuard

Use X25519 for:

  • Establishing shared secrets over insecure channels
  • Forward secrecy in communication protocols
  • Key exchange ahead of symmetric encryption

Ed25519

EdDSA signatures on Curve25519 (RFC 8032, FIPS 186-5)

  • About 128-bit security strength
  • 32-byte keys, 64-byte signatures
  • Deterministic signatures

RSA

Public-key encryption and signatures (RFC 8017)

  • Widely supported
  • Large keys (2048 bits and up)
  • OAEP for encryption, PSS for signatures

ElGamal

Discrete-logarithm public-key encryption

  • Built on the Diffie-Hellman problem
  • Ciphertext is twice the modulus size
  • Encrypts one short message, such as a symmetric key

ECDSA

Elliptic Curve Digital Signature Algorithm (FIPS 186-5)

  • NIST curves (P-256, P-384, P-521) and others
  • Used in X.509 certificates and TLS
  • Deterministic variant (RFC 6979) available

ECDH

Elliptic Curve Diffie-Hellman key exchange (NIST SP 800-56A)

  • NIST curves (P-256, P-384, P-521) and others
  • Used in TLS and many other protocols

Quick Comparison

AlgorithmTypePublic keySecurity strengthTypical use
X25519Key exchange32 bytesAbout 128 bitsGeneral key exchange
Ed25519Signature32 bytesAbout 128 bitsGeneral signatures
ECDH P-256Key exchange65 bytes uncompressed128 bitsNIST curve requirements
ECDSA P-256Signature65 bytes uncompressed128 bitsNIST curve requirements, X.509
RSA-2048Encryption and signature256-byte modulus112 bitsInteroperability
RSA-3072Encryption and signature384-byte modulus128 bitsInteroperability

All of these would be broken by a sufficiently large quantum computer. See Post-Quantum Cryptography.

Key Exchange vs Signatures

Key Exchange (X25519, ECDH)

Purpose: Establish shared secret between two parties

// Alice generates a key pair and sends alicePublic to Bob
x25519 kex;
SecByteBlock alicePrivate(32), alicePublic(32);
kex.GenerateKeyPair(rng, alicePrivate, alicePublic);

// Alice checks the length of the public key Bob sent, then combines it
// with her private key
if (bobPublic.size() != x25519::PUBLIC_KEYLENGTH)
    throw std::runtime_error("X25519: wrong public key length");

SecByteBlock sharedSecret(32);
if (!kex.Agree(sharedSecret, alicePrivate, bobPublic))
    throw std::runtime_error("X25519: the other public key was rejected");

// Bob does the same with his private key and alicePublic.
// Both now hold the same shared secret; derive keys from it with HKDF.

Use for:

  • Session keys for a secure channel
  • Forward secrecy, with a new key pair per session
  • Any case where two parties need a shared symmetric key

Digital Signatures (Ed25519, ECDSA, RSA-PSS)

Purpose: Prove authenticity and integrity

// Signer creates signature
ed25519::Signer signer(privateKey);
byte signature[ed25519::Signer::SIGNATURE_LENGTH];
signer.SignMessage(NullRNG(),
    (const byte*)message.data(), message.size(), signature);

// Verifier checks signature
ed25519::Verifier verifier(publicKey);
bool valid = verifier.VerifyMessage(
    (const byte*)message.data(), message.size(),
    signature, sizeof(signature));

if (valid) {
    // The message was signed by the holder of the private key
    // and has not been changed
}

Use for:

  • Software and firmware signing
  • Document signing
  • Certificates
  • Authenticating a key exchange

Security Best Practices

1. Choose the Algorithm by Requirement

// Free choice: Curve25519
x25519 kex;                    // Key exchange
ed25519::Signer signer(rng);   // Signatures

// NIST curves required
ECDH<ECP>::Domain dh(ASN1::secp256r1());

// RSA required by the other party
RSA::PrivateKey rsaKey;
rsaKey.Initialize(rng, 3072);

2. Use Adequate Key Sizes

AlgorithmMinimumFor 128-bit strengthNotes
X25519/Ed25519FixedFixed32-byte keys
RSA2048 bits3072 bitsLarger is slower
ECDSA/ECDHP-256P-256P-384 and P-521 for higher strengths

3. Validate Public Keys

// theirPublic has already been checked to be kex.PublicKeyLength() bytes.
// Agree() validates the other public key by default; check its result
if (!kex.Agree(shared, myPrivate, theirPublic))
    throw std::runtime_error("The other public key was rejected");

Do not pass false as the fourth argument for keys received from another party.

4. Use Ephemeral Keys for Forward Secrecy

Generate a new key-exchange key pair for each session and discard the private key when the session ends. If one long-term key pair is used for every session, its compromise exposes all of them.

5. Combine Key Exchange with Signatures

A bare key exchange does not tell either side who it is talking to, so an attacker in the middle can run a separate exchange with each. Authenticate the exchange, for example by signing the exchanged public keys with a long-term Ed25519 key that the other side already trusts, or use an established protocol such as TLS or Noise that does this.

When to Use Public-Key Cryptography

Use public-key cryptography for:

  1. Key exchange - Establish a shared secret (X25519, ECDH)
  2. Digital signatures - Prove who produced data (Ed25519, ECDSA, RSA-PSS)
  3. Certificates - RSA and ECDSA keys in X.509
  4. First contact - Parties with no shared secret

Don’t use public-key cryptography for:

  1. Bulk encryption - Use symmetric encryption (AES-GCM) under an exchanged or transported key
  2. Message authentication between parties who share a key - Use a MAC such as HMAC; use signatures when the verifier must not be able to forge

Hybrid Encryption

Public-key operations establish a key; a symmetric cipher encrypts the data. To encrypt to a recipient’s X25519 public key, the sender generates an ephemeral key pair, agrees a shared secret with the recipient’s public key, derives a symmetric key with HKDF, encrypts with an authenticated cipher and sends the ephemeral public key with the ciphertext. See the complete example on the X25519 page for the agreement and derivation steps and AES-GCM for the encryption step.

Thread Safety

Public-key objects are not thread-safe. Use separate objects in each thread, or synchronise access.

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

See Also