# Guide: Migrate Go TLS 1.3 & Key Encapsulation to ML-KEM-768 (Prototype Draft)

Standards referenced:
- **NIST FIPS 203** — Module-Lattice-Based Key-Encapsulation Mechanism Standard (ML-KEM-768)
- **NIST FIPS 204** — Module-Lattice-Based Digital Signature Standard (ML-DSA, native in Go 1.27 `crypto/mldsa`)
- **NIST SP 800-227** — Recommendations for Key-Encapsulation Mechanisms (hybrid KEM combiners)
- **IETF RFC 10024** — Hybrid TLS 1.3 key exchange `X25519MLKEM768` (`0x11EC`), `SecP256r1MLKEM768` (`0x11EB`), `SecP384r1MLKEM1024` (`0x11ED`)
- **NIST IR 8547** — Transition to Post-Quantum Cryptography Standards (final, 27 October 2026)

Human-readable page: `/guide/go-tls-mlkem/`

## Why this migration comes first

TLS traffic encrypted with classical ECDHE (`X25519` or `P-256`) can be
recorded in transit today and decrypted once a cryptanalytically relevant
quantum computer exists ("harvest now, decrypt later"). Migrating TLS 1.3 key
exchange to the hybrid group `X25519MLKEM768` closes this exposure immediately
while remaining secure if either X25519 or ML-KEM-768 holds.

## Prerequisites

- **Go 1.24+** — introduces `crypto/mlkem` and enables `tls.X25519MLKEM768` by default in `crypto/tls`.
- **Go 1.25+** — exposes `tls.ConnectionState.CurveID` so tests and telemetry can verify the negotiated group directly.
- **Go 1.26+** — enables `tls.SecP256r1MLKEM768` and `tls.SecP384r1MLKEM1024` by default (controlled by `GODEBUG=tlssecpmlkem=0`), adds `crypto/mlkem/mlkemtest` for derandomized KAT testing, and adds stdlib `crypto/hpke` (`hpke.MLKEM768X25519()`, `hpke.MLKEM768P256()`, `hpke.MLKEM1024P384()`).
- **Go 1.27+ (recommended)** — adds native `crypto/mldsa` (FIPS 204), `crypto/x509` ML-DSA certificate support, and TLS 1.3 signature schemes `tls.MLDSA44`, `tls.MLDSA65`, and `tls.MLDSA87`.

## Step 1: Audit `go.mod` and every `tls.Config`

Search the repository for:
- `go ` version directive in `go.mod` and CI/Dockerfile toolchains.
- Every `&tls.Config{...}` literal (both **servers** and **outbound `http.Client` / `tls.Dial` clients**).
- Hardcoded certificate or SPKI pins (CA rotation off ECDSA P-256 before 15 March 2027 will break pinned clients).
- Any `GODEBUG` setting containing `tlsmlkem=0` or `tlssecpmlkem=0` (disables ML-KEM hybrid groups when `CurvePreferences` is `nil`; note that starting in Go 1.27, an explicit `CurvePreferences` list overrides these `GODEBUG` flags).

Watch for the two most common silent blockers in Go codebases:
1. **Pinned `CurvePreferences`:** Setting `CurvePreferences: []tls.CurveID{tls.X25519, tls.CurveP256}`
   overrides Go 1.24+'s default and **silently turns off `tls.X25519MLKEM768`** (and Go 1.26+'s `SecP256r1MLKEM768` / `SecP384r1MLKEM1024`).
2. **TLS 1.2 ceiling:** `X25519MLKEM768` requires TLS 1.3. Any `MaxVersion: tls.VersionTLS12`
   prevents post-quantum negotiation.

## Step 2: Update `crypto/tls` configuration

### Before (classical only — vulnerable to harvest-now, decrypt-later)

```go
tlsConfig := &tls.Config{
    MinVersion: tls.VersionTLS12,
    CurvePreferences: []tls.CurveID{
        tls.X25519,
        tls.CurveP256,
    },
}
```

### After (recommended — unpinned defaults, preserves TLS 1.2 fallback)

Leave `CurvePreferences: nil` so Go 1.24–1.27+ automatically enables `tls.X25519MLKEM768` first alongside Go 1.26+'s `tls.SecP256r1MLKEM768` / `tls.SecP384r1MLKEM1024` and classical fallbacks (`X25519`, `P-256`, `P-384`, `P-521`), while keeping `MinVersion: tls.VersionTLS12` so existing TLS 1.2 clients do not break (only raise `MinVersion` to `tls.VersionTLS13` in controlled environments where no TLS 1.2 peers exist):

```go
tlsConfig := &tls.Config{
    MinVersion: tls.VersionTLS12, // Keep TLS 1.2 for compatibility; TLS 1.3 is negotiated by default
    // CurvePreferences left nil: Go 1.24+ automatically prefers X25519MLKEM768,
    // Go 1.26+ adds SecP256r1MLKEM768 & SecP384r1MLKEM1024, plus classical fallbacks.
}
```

If compliance requires an explicit allowlist, keep **all** standard hybrid groups plus classical fallbacks. Note that Go `crypto/tls` **ignores the slice order** of `CurvePreferences` and selects from the set using its fixed internal order (`X25519MLKEM768`, `SecP256r1MLKEM768`, `SecP384r1MLKEM1024`, [`MLKEM1024` in Go 1.27 if opted in], then `X25519`, `CurveP256`, `CurveP384`, `CurveP521`). If policy requires `CurveP384` (or `SecP384r1MLKEM1024`) to be chosen ahead of 256-bit curves, omit the 256-bit groups from the allowlist rather than reordering the slice:

```go
tlsConfig := &tls.Config{
    MinVersion: tls.VersionTLS12,
    CurvePreferences: []tls.CurveID{
        tls.X25519MLKEM768,    // RFC 10024 browser default (0x11EC)
        tls.SecP256r1MLKEM768,  // RFC 10024 NIST P-256 hybrid (0x11EB, Go 1.26+)
        tls.SecP384r1MLKEM1024, // RFC 10024 Level 5 / CNSA-aligned hybrid (0x11ED, Go 1.26+)
        tls.X25519,             // Classical fallback for legacy peers
        tls.CurveP256,          // Classical fallback for legacy FIPS/TLS 1.2 peers
        tls.CurveP384,          // Classical interim fallback
    },
}
```

Note on packet sizes: RFC 10024 `X25519MLKEM768` sends a 1,216-byte client key
share (1,184-byte ML-KEM-768 encapsulation key + 32-byte X25519 key) and a
1,120-byte server key share (1,088-byte ciphertext + 32-byte X25519 key).
Verify that any middleboxes, firewalls, or custom TLS parsers in front of the
service handle multi-packet TLS ClientHello messages cleanly.

## Step 3: Replace application-level classical key wrapping with `crypto/mlkem`

Where application code uses classical ECDH or RSA-OAEP to establish a shared
symmetric key (for example, wrapping an AES-256-GCM data encryption key), use
Go's standard library `crypto/mlkem` (FIPS 203 ML-KEM-768):

- Encapsulation (public) key: `1,184` bytes (`mlkem.EncapsulationKeySize768`)
- Ciphertext: `1,088` bytes (`mlkem.CiphertextSize768`)
- Shared secret: `32` bytes (`mlkem.SharedKeySize`)
- Decapsulation (secret) key seed: `64` bytes (`mlkem.SeedSize`) — persist the
  64-byte seed (`dk.Bytes()`) securely rather than expanding the full 2,400-byte
  internal representation.

```go
package pqc

import (
    "crypto/mlkem"
    "fmt"
)

func WrapKey(recipientPubKey []byte) (sharedKey, ciphertext []byte, err error) {
    ek, err := mlkem.NewEncapsulationKey768(recipientPubKey)
    if err != nil {
        return nil, nil, fmt.Errorf("invalid ML-KEM-768 encapsulation key: %w", err)
    }
    sharedKey, ciphertext = ek.Encapsulate()
    return sharedKey, ciphertext, nil
}

func UnwrapKey(dk *mlkem.DecapsulationKey768, ciphertext []byte) ([]byte, error) {
    sharedKey, err := dk.Decapsulate(ciphertext)
    if err != nil {
        return nil, fmt.Errorf("ML-KEM-768 decapsulation failed: %w", err)
    }
    return sharedKey, nil
}
```

> **Critical FIPS 203 caveat (implicit rejection):** `dk.Decapsulate(ciphertext)`
> only returns an error if `len(ciphertext) != mlkem.CiphertextSize768` (1,088 bytes).
> For any valid-length tampered ciphertext, it returns `err == nil` with a
> pseudorandom key. **Never** rely on `err != nil` for tamper detection—always
> authenticate wrapped payloads with an AEAD cipher (such as AES-256-GCM or
> ChaCha20-Poly1305) keyed from the derived secret.
>
> **Do not invent a custom hybrid KEM combiner.** Never ad-hoc concatenate or
> hash `sharedKey` with classical ECDH yourself (naive combiners without binding
> public keys and ciphertexts break security proofs and cause cross-implementation
> mismatches). If you need hybrid application-layer key wrapping, use a
> standardized construction per **NIST SP 800-227**—in **Go 1.26+**, use stdlib
> `crypto/hpke` (`hpke.MLKEM768X25519()`, `hpke.MLKEM768P256()`,
> `hpke.MLKEM1024P384()`), or **X-Wing** (`draft-connolly-cfrg-xwing-kem`), CFRG
> hybrid KEMs (`draft-irtf-cfrg-hybrid-kems`), or **HPKE** (RFC 9180 +
> `draft-ietf-hpke-pq`) backed by published test vectors.

## Step 4: Verify the migration

Commit permanent tests (do not delete temporary verification tests) and inspect
complete, non-truncated test output before reporting done:

1. **Automated Go handshake & default-offer test (Go 1.25+):**
   Connect a default client (without forcing `CurvePreferences`) to your
   `httptest.NewUnstartedServer` configured with your production `tls.Config`
   (and test outbound clients against a PQ test server) to prove `X25519MLKEM768`
   is negotiated **by default**:

   ```go
   state := resp.TLS
   if state.Version != tls.VersionTLS13 {
       t.Fatalf("got TLS %x, want TLS 1.3", state.Version)
   }
   if state.CurveID != tls.X25519MLKEM768 {
       t.Fatalf("got CurveID %v, want X25519MLKEM768", state.CurveID)
   }
   ```

2. **Verify classical backward compatibility (TLS 1.3 and TLS 1.2):**
   Run explicit fallback tests using (a) a classical TLS 1.3 client (`CurvePreferences: []tls.CurveID{tls.X25519, tls.CurveP256}`) and (b) a TLS 1.2 client (`MaxVersion: tls.VersionTLS12`) if your service keeps `MinVersion: tls.VersionTLS12`.
3. **Cross-implementation / KAT & negative-input tests for `crypto/mlkem` (and `crypto/mldsa`):**
   Do not rely solely on a local `Decapsulate(Encapsulate(pk))` round-trip.
   Validate against **NIST ACVP / KAT vectors** (`crypto/mlkem/mlkemtest` in Go 1.26+ provides derandomized encapsulation for KAT testing) or an independent implementation
   (e.g., OpenSSL 3.5+/4.x), and add negative tests confirming wrong-length keys and
   ciphertexts are rejected, tampered 1,088-byte ciphertexts fail AEAD
   decryption, and (when adding `crypto/mldsa`) empty, truncated, extended, or
   mutated signatures are rejected.
4. **Check `GODEBUG`:** Confirm `tlsmlkem=0` and `tlssecpmlkem=0` are absent from environment files,
   systemd units, Dockerfiles, and Kubernetes manifests.
5. **Live handshake verification (OpenSSL 3.5+ — run both probes):**
   ```sh
   # 1) Confirm hybrid PQ negotiation (also test SecP384r1MLKEM1024 / SecP256r1MLKEM768 separately if enabled)
   openssl s_client -connect <host>:443 -servername <host> -tls1_3 -groups X25519MLKEM768 -brief </dev/null
   # 2) Confirm classical TLS 1.3 fallback still connects for non-PQ peers
   openssl s_client -connect <host>:443 -servername <host> -tls1_3 -groups X25519:prime256v1 -brief </dev/null
   ```
   Expected output for probe 1 includes `Protocol version: TLSv1.3` and `Negotiated TLS1.3 group: X25519MLKEM768`; probe 2 must complete cleanly over classical TLS 1.3.
6. **Verify storage, serialization, and CLI paths end to end:** Ensure database
   columns, JSON/PEM/DER/wire codecs, hardcoded byte-length checks, and CLI
   commands handle 1,184-byte public keys and 1,088-byte ciphertexts cleanly.

## What this guide does NOT finish

- **Public WebPKI certificates:** Public CAs and browsers are transitioning to
  **Merkle Tree Certificates (MTCs)** targeting ~2027 rather than X.509 ML-DSA
  chains. Enabling `X25519MLKEM768` secures session confidentiality today, but
  check that your current CA chain does **not** rely on an ECDSA P-256 CA
  (distrusted by Chrome and Edge on 15 March 2027; use P-384 or RSA-3072+
  interim chains).
- **Private PKI & application digital signatures (JWTs, webhooks, release signing):**
  With Go 1.27+, you can migrate private PKI and application signing directly
  using stdlib `crypto/mldsa` (FIPS 204 `ML-DSA-65`: public key 1,952 bytes,
  signature 3,309 bytes) and `tls.MLDSA44/65/87`, or use FIPS 205 `SLH-DSA`,
  with dual-verification cutover windows.
