Post-quantum cryptography
suggest changeA large enough quantum computer would break the public key algorithms in use today: RSA, ECDSA, Ed25519, and (EC)DH key exchange such as X25519. No such computer exists yet. The threat is already real for encryption, though, because of "harvest now, decrypt later": an attacker can record TLS traffic today and decrypt it once quantum computers arrive. Signatures have less urgency. A forged signature only matters once someone can forge it.
Symmetric cryptography (AES, ChaCha20, SHA-2, SHA-3, HMAC) is not seriously affected. AES-256 and SHA-256 remain fine.
NIST standardized replacements in 2024, and Go added them to the standard library:
| Go | addition |
|---|---|
| 1.24 | crypto/mlkem: ML-KEM (FIPS 203) key encapsulation |
| 1.24 | TLS uses the hybrid X25519MLKEM768 key exchange by default |
| 1.26 | crypto/hpke: Hybrid Public Key Encryption (RFC 9180) with post-quantum KEMs |
| 1.26 | crypto.Encapsulator and crypto.Decapsulator interfaces |
| 1.26 | TLS also enables SecP256r1MLKEM768 and SecP384r1MLKEM1024 by default |
| 1.27 | crypto/mldsa: ML-DSA (FIPS 204) signatures, supported in crypto/x509 and crypto/tls |
In short:
- ML-KEM (formerly Kyber) replaces Diffie-Hellman key exchange. It is a key encapsulation mechanism: it creates a shared secret that only the holder of the private key can recover.
- HPKE is the high-level API you use to encrypt data to someone's public key.
- ML-DSA (formerly Dilithium) replaces RSA, ECDSA and Ed25519 signatures.
For symmetric encryption see Encryption and decryption with AES GCM.
TLS is already post-quantum
If you use crypto/tls or net/http with Go 1.24 or later, your connections are already protected against "harvest now, decrypt later". Go negotiates a hybrid key exchange: X25519 combined with ML-KEM-768. The connection stays secure as long as either of the two algorithms is unbroken. That's a hedge against a flaw in the new and less-studied ML-KEM.
ConnectionState.CurveID (Go 1.25) tells you which key exchange was used. The name refers to elliptic curves for historical reasons. ConnectionState.HelloRetryRequest (Go 1.26) reports whether the server had to ask the client for a different key share, which costs an extra round trip.
The following program starts a TLS server on a random local port with a self-signed certificate and connects to it with different settings:
package main
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"fmt"
"log"
"math/big"
"time"
)
// selfSigned creates an ECDSA certificate for "localhost"
func selfSigned() (tls.Certificate, *x509.CertPool) {
key, err := ecdsa.GenerateKey(elliptic.P256(), nil)
if err != nil {
log.Fatal(err)
}
tmpl := &x509.Certificate{
SerialNumber: big.NewInt(1),
Subject: pkix.Name{CommonName: "localhost"},
DNSNames: []string{"localhost"},
NotBefore: time.Now().Add(-time.Hour),
NotAfter: time.Now().Add(24 * time.Hour),
}
der, err := x509.CreateCertificate(nil, tmpl, tmpl, &key.PublicKey, key)
if err != nil {
log.Fatal(err)
}
leaf, _ := x509.ParseCertificate(der)
pool := x509.NewCertPool()
pool.AddCert(leaf)
return tls.Certificate{Certificate: [][]byte{der}, PrivateKey: key}, pool
}
// handshake runs a TLS server on a random port and connects to it once
func handshake(serverCfg, clientCfg *tls.Config) {
ln, err := tls.Listen("tcp", "127.0.0.1:0", serverCfg)
if err != nil {
log.Fatal(err)
}
defer ln.Close()
go func() {
c, err := ln.Accept()
if err != nil {
return
}
defer c.Close()
c.(*tls.Conn).Handshake()
}()
conn, err := tls.Dial("tcp", ln.Addr().String(), clientCfg)
if err != nil {
fmt.Println(" error:", err)
return
}
defer conn.Close()
st := conn.ConnectionState()
fmt.Printf(" key exchange: %v, HelloRetryRequest: %v\n", st.CurveID, st.HelloRetryRequest)
}
func main() {
cert, roots := selfSigned()
server := &tls.Config{Certificates: []tls.Certificate{cert}}
client := &tls.Config{RootCAs: roots, ServerName: "localhost"}
fmt.Println("defaults on both sides:")
handshake(server, client)
fmt.Println("client limited to classical X25519:")
classic := client.Clone()
classic.CurvePreferences = []tls.CurveID{tls.X25519, tls.CurveP256}
handshake(server, classic)
fmt.Println("server requires SecP256r1MLKEM768:")
strict := server.Clone()
strict.CurvePreferences = []tls.CurveID{tls.SecP256r1MLKEM768}
handshake(strict, client)
fmt.Println("pure ML-KEM-1024 on both sides:")
s1024 := server.Clone()
s1024.CurvePreferences = []tls.CurveID{tls.MLKEM1024}
c1024 := client.Clone()
c1024.CurvePreferences = []tls.CurveID{tls.MLKEM1024}
handshake(s1024, c1024)
fmt.Println("server requires ML-KEM, client is classical:")
handshake(strict, classic)
}
defaults on both sides:
key exchange: X25519MLKEM768, HelloRetryRequest: false
client limited to classical X25519:
key exchange: X25519, HelloRetryRequest: false
server requires SecP256r1MLKEM768:
key exchange: SecP256r1MLKEM768, HelloRetryRequest: true
pure ML-KEM-1024 on both sides:
key exchange: MLKEM1024, HelloRetryRequest: false
server requires ML-KEM, client is classical:
error: remote error: tls: handshake failure
What this shows:
- with default settings, two Go 1.24+ programs agree on
X25519MLKEM768. Chrome, Firefox, Safari, Cloudflare and most large sites support it too, so the same happens when a Go client talks to them. - a peer that doesn't support ML-KEM falls back to plain
X25519. Nothing breaks, you just don't get quantum protection. - the client sends a key share for its most preferred group. When the server only accepts a different one, it asks for it with a HelloRetryRequest. The connection still works, with one extra round trip.
tls.MLKEM1024(Go 1.27) is pure ML-KEM with no classical part. It's supported but not enabled by default. Some government profiles (CNSA 2.0) require it.- if you restrict the server to post-quantum groups only, old clients can't connect at all.
CurvePreferences sets which key exchanges are allowed. The order of the list is ignored: Go always prefers the hybrid post-quantum groups when both sides support them.
The defaults are all you need for most programs. You don't have to set CurvePreferences to get post-quantum TLS. If a buggy middlebox chokes on the larger ClientHello (the ML-KEM key share adds about 1.2 KB), you can turn the hybrids off without changing code:
GODEBUG=tlsmlkem=0 # no ML-KEM hybrids at all (pre-Go 1.24 behavior)
GODEBUG=tlssecpmlkem=0 # keep X25519MLKEM768, drop the P-256/P-384 hybrids (pre-Go 1.26)
Running the program above with GODEBUG=tlsmlkem=0:
defaults on both sides:
key exchange: X25519, HelloRetryRequest: false
Checking from an HTTP handler
In an HTTPS server, r.TLS is the ConnectionState of the request's connection. On the client side, resp.TLS has the same information. This lets you log or monitor what fraction of your clients use post-quantum key exchange:
package main
import (
"crypto/tls"
"fmt"
"io"
"log"
"net/http"
"net/http/httptest"
)
func handler(w http.ResponseWriter, r *http.Request) {
// r.TLS is set for HTTPS requests
fmt.Fprintf(w, "you connected with %v", r.TLS.CurveID)
}
func main() {
// HTTPS server on a random local port with a test certificate
srv := httptest.NewTLSServer(http.HandlerFunc(handler))
defer srv.Close()
// srv.Client() trusts the test certificate
for _, curves := range [][]tls.CurveID{nil, {tls.X25519}} {
client := srv.Client()
tr := client.Transport.(*http.Transport)
tr.TLSClientConfig.CurvePreferences = curves
resp, err := client.Get(srv.URL)
if err != nil {
log.Fatal(err)
}
body, _ := io.ReadAll(resp.Body)
resp.Body.Close()
fmt.Printf("client: %v, server says: %s\n", resp.TLS.CurveID, body)
tr.CloseIdleConnections()
}
}
client: X25519MLKEM768, server says: you connected with X25519MLKEM768
client: X25519, server says: you connected with X25519
CloseIdleConnections forces the second request to open a new connection. Otherwise the client would reuse the first one along with its key exchange.
For setting up a real HTTPS server see Create an HTTPS server. Nothing about it changes for post-quantum key exchange.
ML-KEM: key encapsulation
Outside of TLS you can use ML-KEM directly with crypto/mlkem. A KEM works differently from Diffie-Hellman:
- the receiver generates a key pair: a secret decapsulation key and a public encapsulation key
- the sender calls
Encapsulateon the public key. It returns a random 32-byte shared key plus a ciphertext - the sender transmits the ciphertext; the receiver calls
Decapsulateon it and gets the same 32-byte shared key
The sender doesn't choose the shared key. It is random, and you use it as a key for symmetric encryption.
package main
import (
"bytes"
"crypto/mlkem"
"fmt"
"log"
)
func main() {
// receiver: generate a key pair and publish the encapsulation key
dk, err := mlkem.GenerateKey768()
if err != nil {
log.Fatal(err)
}
ekBytes := dk.EncapsulationKey().Bytes()
fmt.Println("encapsulation key:", len(ekBytes), "bytes")
// sender: parse the public key and encapsulate a fresh shared key
ek, err := mlkem.NewEncapsulationKey768(ekBytes)
if err != nil {
log.Fatal(err)
}
senderKey, ciphertext := ek.Encapsulate()
fmt.Println("ciphertext: ", len(ciphertext), "bytes")
fmt.Println("shared key: ", len(senderKey), "bytes")
// receiver: recover the same shared key from the ciphertext
receiverKey, err := dk.Decapsulate(ciphertext)
if err != nil {
log.Fatal(err)
}
fmt.Println("keys match:", bytes.Equal(senderKey, receiverKey))
// encapsulating again gives a different key and ciphertext
senderKey2, ciphertext2 := ek.Encapsulate()
fmt.Println("second key differs:", !bytes.Equal(senderKey, senderKey2))
fmt.Println("second ct differs: ", !bytes.Equal(ciphertext, ciphertext2))
}
encapsulation key: 1184 bytes
ciphertext: 1088 bytes
shared key: 32 bytes
keys match: true
second key differs: true
second ct differs: true
There are two parameter sets: ML-KEM-768 (GenerateKey768, NewEncapsulationKey768...) and ML-KEM-1024 (GenerateKey1024...). Use 768 unless a standard requires 1024. Note the sizes: an X25519 public key is 32 bytes, an ML-KEM-768 one is 1184.
Storing keys and invalid ciphertexts
The private key serializes to a 64-byte seed, and the full key is expanded from it:
package main
import (
"bytes"
"crypto/mlkem"
"fmt"
"log"
)
func main() {
dk, err := mlkem.GenerateKey768()
if err != nil {
log.Fatal(err)
}
// the private key is stored as a 64-byte seed
seed := dk.Bytes()
fmt.Println("seed:", len(seed), "bytes")
// later: re-create the same key from the seed
dk2, err := mlkem.NewDecapsulationKey768(seed)
if err != nil {
log.Fatal(err)
}
same := bytes.Equal(dk.EncapsulationKey().Bytes(), dk2.EncapsulationKey().Bytes())
fmt.Println("same public key:", same)
key, ct := dk.EncapsulationKey().Encapsulate()
// a ciphertext of the wrong length is an error
_, err = dk2.Decapsulate(ct[:100])
fmt.Println("short ciphertext:", err)
// a modified ciphertext is NOT an error: you get a different key
ct[0] ^= 1
bad, err := dk2.Decapsulate(ct)
fmt.Println("tampered err:", err)
fmt.Println("tampered key matches:", bytes.Equal(key, bad))
}
seed: 64 bytes
same public key: true
short ciphertext: mlkem: invalid ciphertext length
tampered err: <nil>
tampered key matches: false
The last part is important. Per FIPS 203, a corrupted ciphertext of the right length doesn't produce an error ("implicit rejection"). Decapsulate returns a pseudo-random key that doesn't match the sender's. You only find out when the symmetric decryption with that key fails. That's why a KEM is always paired with an authenticated cipher like AES-GCM, which is exactly what HPKE does.
The seed is the secret key. Protect it like any other private key, e.g. encrypt it at rest and don't log it.
crypto.Encapsulator and crypto.Decapsulator
Go 1.26 added two small interfaces to the crypto package so code can work with any KEM key, the same way crypto.Signer abstracts over signing keys:
type Encapsulator interface {
Bytes() []byte
Encapsulate() (sharedKey, ciphertext []byte)
}
type Decapsulator interface {
Encapsulator() Encapsulator
Decapsulate(ciphertext []byte) (sharedKey []byte, err error)
}
The mlkem encapsulation keys implement Encapsulator and the decapsulation keys implement Decapsulator. A key stored in a hardware security module can implement Decapsulator without exposing the secret.
Here's a minimal "KEM + AEAD" construction that works with either ML-KEM size. It uses the 32-byte shared key as an AES-256 key:
package main
import (
"crypto"
"crypto/aes"
"crypto/cipher"
"crypto/mlkem"
"fmt"
"log"
)
// seal works with any KEM public key: ML-KEM-768, ML-KEM-1024
// or a key that lives in a hardware module
func seal(pub crypto.Encapsulator, msg []byte) (kemCT, sealed []byte, err error) {
sharedKey, kemCT := pub.Encapsulate()
block, err := aes.NewCipher(sharedKey) // 32 bytes: AES-256
if err != nil {
return nil, nil, err
}
aead, err := cipher.NewGCMWithRandomNonce(block)
if err != nil {
return nil, nil, err
}
return kemCT, aead.Seal(nil, nil, msg, nil), nil
}
func open(priv crypto.Decapsulator, kemCT, sealed []byte) ([]byte, error) {
sharedKey, err := priv.Decapsulate(kemCT)
if err != nil {
return nil, err
}
block, err := aes.NewCipher(sharedKey)
if err != nil {
return nil, err
}
aead, err := cipher.NewGCMWithRandomNonce(block)
if err != nil {
return nil, err
}
return aead.Open(nil, nil, sealed, nil)
}
func main() {
dk768, _ := mlkem.GenerateKey768()
dk1024, _ := mlkem.GenerateKey1024()
for _, dk := range []crypto.Decapsulator{dk768, dk1024} {
// the public half, as a crypto.Encapsulator
pub := dk.Encapsulator()
kemCT, sealed, err := seal(pub, []byte("attack at dawn"))
if err != nil {
log.Fatal(err)
}
msg, err := open(dk, kemCT, sealed)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%T: public key %d, kem ct %d, sealed %d: %q\n",
pub, len(pub.Bytes()), len(kemCT), len(sealed), msg)
}
}
*mlkem.EncapsulationKey768: public key 1184, kem ct 1088, sealed 42: "attack at dawn"
*mlkem.EncapsulationKey1024: public key 1568, kem ct 1568, sealed 42: "attack at dawn"
cipher.NewGCMWithRandomNonce (Go 1.24) generates the nonce and stores it in the output, so the 14-byte message grows by 12 bytes of nonce plus 16 bytes of tag.
This works, but it's a homemade protocol: there's no domain separation, no binding to an application context, and only ML-KEM, no hybrid. Use it to understand KEMs. For real code use HPKE, which solves all of these and is an interoperable standard.
HPKE: encrypting to a public key
HPKE (Hybrid Public Key Encryption, RFC 9180) is the standard way to encrypt a message so that only the owner of a private key can read it. It's used by TLS Encrypted Client Hello, MLS (Messaging Layer Security) and Oblivious HTTP. "Hybrid" here means public key plus symmetric encryption. It isn't about post-quantum, although crypto/hpke also offers post-quantum and hybrid post-quantum KEMs.
An HPKE ciphersuite has three parts, and both sides must use the same ones:
- KEM: how the shared secret is established, e.g.
hpke.MLKEM768X25519() - KDF: how keys are derived from it, e.g.
hpke.HKDFSHA256() - AEAD: how data is encrypted, e.g.
hpke.AES256GCM()orhpke.ChaCha20Poly1305()
For a single message use hpke.Seal and hpke.Open:
package main
import (
"crypto/hpke"
"fmt"
"log"
)
func main() {
// the ciphersuite: KEM + KDF + AEAD. Both sides must agree on it.
kem := hpke.MLKEM768X25519() // X-Wing: hybrid ML-KEM-768 + X25519
kdf := hpke.HKDFSHA256()
aead := hpke.AES256GCM()
fmt.Printf("suite: kem=0x%04x kdf=0x%04x aead=0x%04x\n", kem.ID(), kdf.ID(), aead.ID())
// recipient: generate a key pair, publish the public key
priv, err := kem.GenerateKey()
if err != nil {
log.Fatal(err)
}
pubBytes := priv.PublicKey().Bytes()
fmt.Println("public key:", len(pubBytes), "bytes")
// sender: parse the public key and encrypt
pub, err := kem.NewPublicKey(pubBytes)
if err != nil {
log.Fatal(err)
}
info := []byte("example.com file encryption v1")
plaintext := []byte("the eagle lands at midnight")
ct, err := hpke.Seal(pub, kdf, aead, info, plaintext)
if err != nil {
log.Fatal(err)
}
fmt.Println("plaintext: ", len(plaintext), "bytes")
fmt.Println("ciphertext:", len(ct), "bytes")
// recipient: decrypt with the private key
msg, err := hpke.Open(priv, kdf, aead, info, ct)
if err != nil {
log.Fatal(err)
}
fmt.Printf("decrypted: %q\n", msg)
// a different info string fails
_, err = hpke.Open(priv, kdf, aead, []byte("other app"), ct)
fmt.Println("wrong info:", err)
// so does a modified ciphertext
ct[len(ct)-1] ^= 1
_, err = hpke.Open(priv, kdf, aead, info, ct)
fmt.Println("tampered: ", err)
}
suite: kem=0x647a kdf=0x0001 aead=0x0002
public key: 1216 bytes
plaintext: 27 bytes
ciphertext: 1163 bytes
decrypted: "the eagle lands at midnight"
wrong info: cipher: message authentication failed
tampered: cipher: message authentication failed
Things to notice:
Sealreturns the encapsulated key (1120 bytes for X-Wing) followed by the encrypted message and the 16-byte tag: 1120 + 27 + 16 = 1163.infobinds the ciphertext to your application. Use a fixed string that names the application, the purpose and a version. A ciphertext created for one purpose can't be opened for another.- tampering and a wrong key or info are all reported as an authentication failure. You don't get the silent wrong key that raw ML-KEM gives you.
MLKEM768X25519(also known as X-Wing) is the hybrid of ML-KEM-768 and X25519, the same combination TLS uses. It's a good default for new designs.- HPKE provides confidentiality, not sender authentication. Anyone with the public key can encrypt to it. If the recipient must know who sent the message, sign it with ML-DSA as well (see below).
Keys and multiple messages
hpke.Seal does a new, expensive encapsulation for every call and adds over a kilobyte to each message. To send several messages to the same recipient, create a Sender once. It returns enc, the encapsulated key, which you send to the recipient once:
package main
import (
"bytes"
"crypto/hpke"
"fmt"
"log"
)
func main() {
kem := hpke.MLKEM768X25519()
kdf := hpke.HKDFSHA256()
aead := hpke.ChaCha20Poly1305()
info := []byte("chat v1")
priv, err := kem.GenerateKey()
if err != nil {
log.Fatal(err)
}
// save the private key and load it back
privBytes, err := priv.Bytes()
if err != nil {
log.Fatal(err)
}
fmt.Println("private key:", len(privBytes), "bytes")
priv, err = kem.NewPrivateKey(privBytes)
if err != nil {
log.Fatal(err)
}
// sender: one encapsulation, many messages
enc, sender, err := hpke.NewSender(priv.PublicKey(), kdf, aead, info)
if err != nil {
log.Fatal(err)
}
fmt.Println("enc:", len(enc), "bytes")
var sealed [][]byte
for i, m := range []string{"hello", "how are you?", "bye"} {
aad := fmt.Appendf(nil, "msg #%d", i) // authenticated, not encrypted
ct, err := sender.Seal(aad, []byte(m))
if err != nil {
log.Fatal(err)
}
sealed = append(sealed, ct)
}
// recipient: needs enc once, then opens messages in order
recipient, err := hpke.NewRecipient(enc, priv, kdf, aead, info)
if err != nil {
log.Fatal(err)
}
for i, ct := range sealed {
aad := fmt.Appendf(nil, "msg #%d", i)
m, err := recipient.Open(aad, ct)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%d: %q (%d bytes)\n", i, m, len(ct))
}
// both sides can derive extra shared secrets
k1, _ := sender.Export("session id", 16)
k2, _ := recipient.Export("session id", 16)
fmt.Printf("exported: %x equal=%v\n", k1, bytes.Equal(k1, k2))
}
private key: 32 bytes
enc: 1120 bytes
0: "hello" (21 bytes)
1: "how are you?" (28 bytes)
2: "bye" (19 bytes)
exported: d0c169027c308f9abad1f1510ad5e420 equal=true
- each message now costs only its length plus 16 bytes.
SenderandRecipientkeep a message counter that is used as the nonce. Messages must be opened in the same order they were sealed. If you open message 2 before message 1,Openfails with an authentication error. For unordered delivery (UDP, message queues) use one-shotSeal/Openper message.aadis additional authenticated data: it's not encrypted, but it must match on both sides. Headers and message IDs are typical.Exportderives more secrets from the shared key, e.g. a key for a different cipher or a session identifier.- the X-Wing private key serializes to a 32-byte seed.
KEM.NewPrivateKeyreversesPrivateKey.Bytes.
Choosing a KEM
crypto/hpke supports classical, post-quantum and hybrid KEMs. They differ a lot in size:
| KEM | constructor | ID | public key | enc |
|---|---|---|---|---|
| DHKEM(X25519) | hpke.DHKEM(ecdh.X25519()) |
0x0020 | 32 | 32 |
| DHKEM(P-256) | hpke.DHKEM(ecdh.P256()) |
0x0010 | 65 | 65 |
| ML-KEM-768 | hpke.MLKEM768() |
0x0041 | 1184 | 1088 |
| MLKEM768-X25519 | hpke.MLKEM768X25519() |
0x647a | 1216 | 1120 |
| MLKEM768-P256 | hpke.MLKEM768P256() |
0x0050 | 1249 | 1153 |
| MLKEM1024-P384 | hpke.MLKEM1024P384() |
0x0051 | 1665 | 1665 |
Pick MLKEM768X25519 unless you need P-256 for compliance (MLKEM768P256) or interoperability with a peer that only supports classical HPKE. If the ciphersuite is only known at runtime (e.g. read from a message header), hpke.NewKEM, hpke.NewKDF and hpke.NewAEAD construct the parts from their IDs.
If you already have an *mlkem.DecapsulationKey768 and an *ecdh.PrivateKey, or a key in hardware, hpke.NewHybridPrivateKey(pq, t) and hpke.NewHybridPublicKey wrap them. They take a crypto.Decapsulator and crypto.Encapsulator, which is why those interfaces exist.
ML-DSA: signatures
crypto/mldsa (Go 1.27) implements ML-DSA, the post-quantum replacement for RSA, ECDSA and Ed25519 signatures:
package main
import (
"bytes"
"crypto/mldsa"
"fmt"
"log"
)
func main() {
params := mldsa.MLDSA44()
priv, err := mldsa.GenerateKey(params)
if err != nil {
log.Fatal(err)
}
pub := priv.PublicKey()
fmt.Println("parameters: ", pub.Parameters())
fmt.Println("private seed:", len(priv.Bytes()), "bytes")
fmt.Println("public key: ", len(pub.Bytes()), "bytes")
msg := []byte("release v1.2.3, sha256=9f86d0...")
// the rand argument is ignored; nil opts means no context
sig, err := priv.Sign(nil, msg, nil)
if err != nil {
log.Fatal(err)
}
fmt.Println("signature: ", len(sig), "bytes")
// verifier: has only the public key bytes
pub2, err := mldsa.NewPublicKey(params, pub.Bytes())
if err != nil {
log.Fatal(err)
}
fmt.Println("valid: ", mldsa.Verify(pub2, msg, sig, nil))
msg[0] = 'R'
fmt.Println("modified: ", mldsa.Verify(pub2, msg, sig, nil))
msg[0] = 'r'
// signatures are randomized by default...
sig2, _ := priv.Sign(nil, msg, nil)
fmt.Println("same sig twice:", bytes.Equal(sig, sig2))
// ...unless you ask for a deterministic one
d1, _ := priv.SignDeterministic(msg, nil)
d2, _ := priv.SignDeterministic(msg, nil)
fmt.Println("deterministic: ", bytes.Equal(d1, d2))
// restore the private key from its 32-byte seed
priv2, err := mldsa.NewPrivateKey(params, priv.Bytes())
if err != nil {
log.Fatal(err)
}
fmt.Println("restored equal:", priv.Equal(priv2))
}
parameters: ML-DSA-44
private seed: 32 bytes
public key: 1312 bytes
signature: 2420 bytes
valid: <nil>
modified: mldsa: invalid signature
same sig twice: false
deterministic: true
restored equal: true
Things to notice:
- ML-DSA signs the message itself. Don't hash it first: pass the whole message, just like with Ed25519.
- the parameter set is part of the key. When you store a public key, also store which parameter set it uses, because
NewPublicKeyandNewPrivateKeyneed it. Verifyreturns anerror.nilmeans the signature is valid.- the
io.Readerargument ofSignis ignored. Randomness always comes from the system's secure source. SignDeterministicproduces the same signature for the same key and message. Randomized signing (the default) is recommended because it's more resistant to fault and side-channel attacks. Use deterministic signatures only if you need reproducible output, e.g. in test vectors.
The three parameter sets trade size for security margin:
| parameters | public key | signature | Ed25519 for comparison |
|---|---|---|---|
mldsa.MLDSA44() |
1312 | 2420 | 32 / 64 |
mldsa.MLDSA65() |
1952 | 3309 | |
mldsa.MLDSA87() |
2592 | 4627 |
The package docs recommend ML-DSA-44 for most applications. The sizes are the biggest practical cost: a signature is almost 40 times larger than an Ed25519 one. Plan for it in database columns, tokens and network protocols with size limits.
Context strings and crypto.Signer
mldsa.Options.Context binds a signature to a purpose, like info in HPKE. A signature made for one context doesn't verify in another. *mldsa.PrivateKey also implements crypto.Signer, so it works with code written for other signature algorithms:
package main
import (
"crypto"
"crypto/ed25519"
"crypto/mldsa"
"fmt"
"log"
)
// signAny works with any crypto.Signer: Ed25519, ECDSA, RSA, ML-DSA
func signAny(s crypto.Signer, msg []byte) []byte {
sig, err := crypto.SignMessage(s, nil, msg, crypto.Hash(0))
if err != nil {
log.Fatal(err)
}
return sig
}
func main() {
priv, _ := mldsa.GenerateKey(mldsa.MLDSA65())
msg := []byte("transfer $100 to bob")
// a context string binds the signature to a purpose
opts := &mldsa.Options{Context: "payments-v1"}
sig, _ := priv.Sign(nil, msg, opts)
fmt.Println("same context: ", mldsa.Verify(priv.PublicKey(), msg, sig, opts))
fmt.Println("no context: ", mldsa.Verify(priv.PublicKey(), msg, sig, nil))
other := &mldsa.Options{Context: "audit-log-v1"}
fmt.Println("other context:", mldsa.Verify(priv.PublicKey(), msg, sig, other))
// *mldsa.PrivateKey is a crypto.Signer
_, edPriv, _ := ed25519.GenerateKey(nil)
for _, s := range []crypto.Signer{edPriv, priv} {
sig := signAny(s, msg)
fmt.Printf("%-20T signature %4d bytes\n", s, len(sig))
}
}
same context: <nil>
no context: mldsa: invalid signature
other context: mldsa: invalid signature
ed25519.PrivateKey signature 64 bytes
*mldsa.PrivateKey signature 3309 bytes
crypto.SignMessage (Go 1.25) calls SignMessage on signers that implement crypto.MessageSigner. Otherwise it hashes the message with opts.HashFunc() and calls Sign. crypto.Hash(0) means "no pre-hashing", which is what Ed25519 and ML-DSA need: both sign the full message. For RSA or ECDSA you'd pass e.g. crypto.SHA256 instead.
The context must be at most 255 bytes and is empty by default. Two systems that sign with the same key, e.g. a release signer and an API token issuer, should use different contexts so that a signature from one can never be replayed in the other.
ML-DSA certificates in TLS
In Go 1.27 crypto/x509 can create and parse certificates with ML-DSA keys, x509.MarshalPKCS8PrivateKey and x509.ParsePKCS8PrivateKey handle ML-DSA private keys, and crypto/tls can authenticate with them. This is end-to-end post-quantum TLS: post-quantum key exchange and post-quantum authentication.
package main
import (
"crypto/mldsa"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"fmt"
"log"
"math/big"
"time"
)
func main() {
// 1. an ML-DSA key and a self-signed certificate
key, err := mldsa.GenerateKey(mldsa.MLDSA44())
if err != nil {
log.Fatal(err)
}
tmpl := &x509.Certificate{
SerialNumber: big.NewInt(1),
Subject: pkix.Name{CommonName: "localhost"},
DNSNames: []string{"localhost"},
NotBefore: time.Now().Add(-time.Hour),
NotAfter: time.Now().Add(24 * time.Hour),
}
der, err := x509.CreateCertificate(nil, tmpl, tmpl, key.PublicKey(), key)
if err != nil {
log.Fatal(err)
}
// 2. PEM files, as you would write them to disk
certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der})
pkcs8, err := x509.MarshalPKCS8PrivateKey(key)
if err != nil {
log.Fatal(err)
}
keyPEM := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: pkcs8})
fmt.Printf("cert.pem: %d bytes, key.pem: %d bytes\n", len(certPEM), len(keyPEM))
// 3. load them back like tls.LoadX509KeyPair would
cert, err := tls.X509KeyPair(certPEM, keyPEM)
if err != nil {
log.Fatal(err)
}
roots := x509.NewCertPool()
roots.AppendCertsFromPEM(certPEM)
// 4. TLS server on a random port
ln, err := tls.Listen("tcp", "127.0.0.1:0", &tls.Config{Certificates: []tls.Certificate{cert}})
if err != nil {
log.Fatal(err)
}
defer ln.Close()
go func() {
c, err := ln.Accept()
if err != nil {
return
}
defer c.Close()
c.Write([]byte("hello"))
}()
// 5. the client verifies the ML-DSA certificate chain as usual
conn, err := tls.Dial("tcp", ln.Addr().String(), &tls.Config{RootCAs: roots, ServerName: "localhost"})
if err != nil {
log.Fatal(err)
}
defer conn.Close()
buf := make([]byte, 5)
conn.Read(buf)
st := conn.ConnectionState()
leaf := st.PeerCertificates[0]
fmt.Println("got: ", string(buf))
fmt.Println("key exchange: ", st.CurveID)
fmt.Println("public key alg: ", leaf.PublicKeyAlgorithm)
fmt.Println("signature alg: ", leaf.SignatureAlgorithm)
fmt.Printf("public key type: %T\n", leaf.PublicKey)
}
cert.pem: 5340 bytes, key.pem: 128 bytes
got: hello
key exchange: X25519MLKEM768
public key alg: ML-DSA
signature alg: ML-DSA-44
public key type: *mldsa.PublicKey
The code is identical to what you'd write for an ECDSA certificate. Only the key type changed. The TLS signature schemes tls.MLDSA44, tls.MLDSA65 and tls.MLDSA87 are enabled by default.
Don't switch public servers to ML-DSA certificates yet, though:
- browsers don't accept ML-DSA certificates, and public CAs don't issue them yet.
- the self-signed ML-DSA certificate is 5340 bytes in PEM, compared to 469 bytes for an equivalent ECDSA P-256 one. A real chain with intermediates adds several more kilobytes to every handshake.
- quantum forgery of signatures is not a "harvest now" threat. You can switch authentication later, once the ecosystem is ready.
ML-DSA certificates make sense today for internal services and mutual TLS between your own Go programs, where you control both ends and the CA.
Testing
Post-quantum operations are randomized, which makes golden-file tests hard. Go provides deterministic variants for tests:
crypto/mlkem/mlkemtest(Go 1.26) hasEncapsulate768(ek, random)andEncapsulate1024that take the 32 bytes of randomness as an argument. Use them to check your code against published test vectors. Don't use them outside tests.mlkem.NewDecapsulationKey768(seed),mldsa.NewPrivateKey(params, seed)andKEM.DeriveKeyPair(ikm)in HPKE create keys from fixed bytes.PrivateKey.SignDeterministicinmldsagives reproducible signatures.
Things to keep in mind
- TLS needs no action. Go 1.24+ already uses hybrid post-quantum key exchange. Check
ConnectionState.CurveIDif you want to verify or monitor it. - Prefer hybrids.
X25519MLKEM768in TLS andMLKEM768X25519in HPKE stay secure as long as either the classical or the post-quantum half holds. - Use HPKE, not raw ML-KEM, to encrypt data. Raw ML-KEM returns a wrong key instead of an error for corrupted input, and you'd have to design the key derivation and context binding yourself.
- Use
info,aadandContextstrings to bind ciphertexts and signatures to their purpose and version. - Budget for size. Public keys, ciphertexts and signatures are 1 to 5 KB instead of 32 to 64 bytes.
- FIPS 140-3: ML-KEM is available in all versions of the Go Cryptographic Module. ML-DSA requires module v1.26.0 or later; with the frozen v1.0.0 module,
mldsafunctions return an error. - Upgrade encryption first, signatures later. Encrypted data recorded today can be decrypted in the future. A signature only needs to resist forgery during its validity period.
Summary
| task | API |
|---|---|
| check TLS key exchange | conn.ConnectionState().CurveID, r.TLS.CurveID, resp.TLS.CurveID |
| restrict TLS key exchange | tls.Config.CurvePreferences, GODEBUG=tlsmlkem=0 |
| raw key encapsulation | mlkem.GenerateKey768, EncapsulationKey768.Encapsulate, DecapsulationKey768.Decapsulate |
| generic KEM keys | crypto.Encapsulator, crypto.Decapsulator |
| encrypt to a public key | hpke.Seal / hpke.Open with hpke.MLKEM768X25519() |
| many messages to one recipient | hpke.NewSender / hpke.NewRecipient |
| sign and verify | mldsa.GenerateKey, PrivateKey.Sign, mldsa.Verify |
| ML-DSA certificates | x509.CreateCertificate, x509.MarshalPKCS8PrivateKey, tls.X509KeyPair |