ML-KEM Encapsulate Decapsulate
Generate an ML-KEM key pair, encapsulate a shared secret, decapsulate it with the private key, and round-trip the public key.
Code
package main
import (
"bytes"
"crypto/mlkem"
"fmt"
)
func main() {
// the receiver holds a decapsulation key and publishes the encapsulation key
dk, err := mlkem.GenerateKey768()
if err != nil {
fmt.Println("keygen failed:", err)
return
}
ek := dk.EncapsulationKey()
fmt.Println("encapsulation key bytes:", len(ek.Bytes()))
fmt.Println("decapsulation key bytes:", len(dk.Bytes()))
// the sender creates a ciphertext and a shared secret
ciphertext, senderSecret, err := mlkem.Encapsulate(ek)
if err != nil {
fmt.Println("encapsulate failed:", err)
return
}
fmt.Println("ciphertext bytes:", len(ciphertext))
// only the holder of the decapsulation key can recover that secret
receiverSecret, err := mlkem.Decapsulate(dk, ciphertext)
if err != nil {
fmt.Println("decapsulate failed:", err)
return
}
fmt.Println("shared secrets match:", bytes.Equal(senderSecret, receiverSecret))
// importing the published bytes reproduces the same encapsulation key
roundTrip, err := mlkem.NewEncapsulationKey768(ek.Bytes())
if err != nil {
fmt.Println("import failed:", err)
return
}
fmt.Println("public key roundtrip:", bytes.Equal(roundTrip.Bytes(), ek.Bytes()))
}What the code does
ML-KEM Encapsulate Decapsulate is built around the function main.
Nothing falls through silently — 4 checkpoints test err != nil on the way through.
Using it
The run emits 9 labeled sections — keygen failed:, encapsulation key bytes:, decapsulation key bytes:, encapsulate failed:, ciphertext bytes:, decapsulate failed:, shared secrets match:, import failed:, public key roundtrip: — one per step.
Key statements
if err != nil {
fmt.Println("keygen failed:", err)
return
}
if err != nil {
fmt.Println("encapsulate failed:", err)
return
}
if err != nil {
fmt.Println("decapsulate failed:", err)
return
}
Interactive Tools for This Topic
HMAC GeneratorCompute an HMAC-SHA-256, SHA-384, or SHA-512 signature for a message and key using the Web Crypto API, with hex and Base64 output.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.SHA-256 Hash GeneratorGenerate SHA-256 cryptographic hashes from text input using the Web Crypto API. Compare hashes and verify data integrity with hexadecimal digest output.JWT Signature InspectorInspect a JWT signature: decode the header and payload, show the algorithm and signature bytes, and verify HS256/384/512 HMAC signatures with a secret.
FAQ
- What does ML-KEM Encapsulate Decapsulate print when run?
- Run it as a complete program — the output lines carry labels such as `keygen failed:`, `encapsulation key bytes:`, `decapsulation key bytes:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.