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.

GoSecurity Boundaries

Code

gosnippet
43 lines
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

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:`.