sodium_crypto_kem_*

sodium_crypto_kem_enc(string $public_key): array

Post-quantum key encapsulation (new in PHP 8.6, Sodium): an X-Wing hybrid family (ML-KEM-768 + X25519) and a pure-PQ ML-KEM-768 family (FIPS 203) with identical workflows — enc produces [ciphertext, shared secret], dec recovers the same secret.

C C23

C23
#include <stdio.h>
#include <string.h>
#include "sha256.h" /* vendored SHA-256 stands in for the KDF step */

#define SS_BYTES 32

/* FIPS 203 ML-KEM-768 wire sizes — what a real implementation (liboqs) would fill */
#define MLKEM768_EK_BYTES 1184
#define MLKEM768_DK_BYTES 2400
#define MLKEM768_CT_BYTES 1088

static void kdf(const BYTE *a, size_t alen, const BYTE *b, size_t blen, BYTE out[SHA256_BLOCK_SIZE]) {
    SHA256_CTX ctx;
    sha256_init(&ctx);
    sha256_update(&ctx, a, alen);
    sha256_update(&ctx, b, blen);
    sha256_final(&ctx, out);
}

int main(void) {
    /* No KEM primitive in the C stdlib — production C calls liboqs. Below, the
       KEM data flow in toy form (a KDF instead of lattice math, so NOT secure):
       keypair from a fixed seed, encapsulate -> (ct, ss) on the sender side,
       decapsulate(dk, ct) -> the same ss on the receiver side. */
    BYTE seed[SS_BYTES] = {0};
    seed[0] = 0x9d; /* fixed seed keeps the demo output stable */
    BYTE ek[SS_BYTES], ss_sender[SS_BYTES];
    kdf((const BYTE *)"ek", 2, seed, SS_BYTES, ek);      /* keypair: ek travels, seed = dk */
    kdf((const BYTE *)"ss", 2, ek, SS_BYTES, ss_sender); /* encapsulate: sender secret */
    /* receiver side: rebuild ek from dk, derive the same secret, ciphertext travels */
    BYTE ek2[SS_BYTES], ss_receiver[SS_BYTES];
    kdf((const BYTE *)"ek", 2, seed, SS_BYTES, ek2);
    kdf((const BYTE *)"ss", 2, ek2, SS_BYTES, ss_receiver);
    printf("shared secrets match: %s\n", memcmp(ss_sender, ss_receiver, SS_BYTES) == 0 ? "true" : "false");
    printf("FIPS 203 ML-KEM-768 sizes: ek %d, dk %d, ct %d, ss %d\n",
           MLKEM768_EK_BYTES, MLKEM768_DK_BYTES, MLKEM768_CT_BYTES, SS_BYTES);
    return 0;
}
Output
shared secrets match: true
FIPS 203 ML-KEM-768 sizes: ek 1184, dk 2400, ct 1088, ss 32

C++ C++26

C++26
#include <cstdio>
#include <cstring>
#include "sha256.h" // vendored SHA-256 stands in for the KDF step

#define SS_BYTES 32
// FIPS 203 ML-KEM-768 wire sizes — what a real implementation (liboqs) would fill
#define MLKEM768_EK_BYTES 1184
#define MLKEM768_CT_BYTES 1088

static void kdf(const BYTE *a, size_t alen, const BYTE *b, size_t blen, BYTE out[SHA256_BLOCK_SIZE]) {
    SHA256_CTX ctx;
    sha256_init(&ctx);
    sha256_update(&ctx, a, alen);
    sha256_update(&ctx, b, blen);
    sha256_final(&ctx, out);
}

int main() {
    // No KEM primitive in the C++ stdlib either — production C++ calls liboqs.
    // Toy data flow below (KDF instead of lattice math, NOT secure): sender and
    // receiver each derive the same shared secret from a shared root.
    BYTE seed[SS_BYTES] = {0};
    seed[0] = 0x9d; // fixed seed keeps the demo output stable
    BYTE ek[SS_BYTES], ss_sender[SS_BYTES];
    kdf((const BYTE *)"ek", 2, seed, SS_BYTES, ek);      // keypair
    kdf((const BYTE *)"ss", 2, ek, SS_BYTES, ss_sender); // encapsulate: sender secret
    BYTE ek2[SS_BYTES], ss_receiver[SS_BYTES];
    kdf((const BYTE *)"ek", 2, seed, SS_BYTES, ek2);     // decapsulate: rebuild ek
    kdf((const BYTE *)"ss", 2, ek2, SS_BYTES, ss_receiver);
    printf("shared secrets match: %s\n", memcmp(ss_sender, ss_receiver, SS_BYTES) == 0 ? "true" : "false");
    printf("FIPS 203 ML-KEM-768 sizes: ek %d, dk 2400, ct %d, ss %d\n", MLKEM768_EK_BYTES, MLKEM768_CT_BYTES, SS_BYTES);
    return 0;
}
Output
shared secrets match: true
FIPS 203 ML-KEM-768 sizes: ek 1184, dk 2400, ct 1088, ss 32

C# v11.0.100

v11.0.100
using System.Security.Cryptography;

// .NET ships ML-KEM (FIPS 203) since 10/11, but its OpenSSL-backed availability
// varies by platform (see notes) — so this demo sticks to a fact that is
// identical on every platform: a Diffie-Hellman KEM-style exchange, the
// classical half of any post-quantum hybrid
using ECDiffieHellman a = ECDiffieHellman.Create(ECCurve.NamedCurves.nistP256);
using ECDiffieHellman b = ECDiffieHellman.Create(ECCurve.NamedCurves.nistP256);
byte[] ssA = a.DeriveKeyMaterial(b.PublicKey); // "encapsulate" against the peer key
byte[] ssB = b.DeriveKeyMaterial(a.PublicKey); // peer derives the same secret
Console.WriteLine($"shared secrets match: {ssA.AsSpan().SequenceEqual(ssB)}");
Console.WriteLine($"shared secret bytes: {ssA.Length}");
Output
shared secrets match: True
shared secret bytes: 32

Go v1.27.4

v1.27.4
package main

import (
	"bytes"
	"crypto/mlkem"
	"fmt"
)

func main() {
	// Go 1.24+ standard library: crypto/mlkem implements FIPS 203 ML-KEM
	sk, err := mlkem.GenerateKey768()
	if err != nil {
		panic(err)
	}
	ek := sk.EncapsulationKey()
	// encapsulate returns (sharedKey, ciphertext) — shared key comes first
	ssSender, ct := ek.Encapsulate()
	ssReceiver, err := sk.Decapsulate(ct)
	if err != nil {
		panic(err)
	}
	fmt.Printf("shared secrets match: %v\n", bytes.Equal(ssSender, ssReceiver))
	fmt.Printf("ciphertext bytes: %d, encapsulation key bytes: %d\n", len(ct), len(ek.Bytes()))
}
Output
shared secrets match: true
ciphertext bytes: 1088, encapsulation key bytes: 1184

Java v27.0.1

v27.0.1
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.util.Arrays;
import javax.crypto.KEM;
import javax.crypto.SecretKey;

public class Main {
    public static void main(String[] args) throws Exception {
        // Java 24+ (JEP 496): ML-KEM-768 ships in JCA — no third-party provider needed
        KEM kem = KEM.getInstance("ML-KEM-768");
        KeyPairGenerator kpg = KeyPairGenerator.getInstance("ML-KEM-768");
        KeyPair kp = kpg.generateKeyPair();
        // sender side: encapsulate against the peer public key -> (ciphertext, secret)
        KEM.Encapsulated enc = kem.newEncapsulator(kp.getPublic()).encapsulate();
        SecretKey ss1 = enc.key();
        // receiver side: decapsulate the ciphertext with the private key
        KEM.Decapsulator dec = kem.newDecapsulator(kp.getPrivate());
        SecretKey ss2 = dec.decapsulate(enc.encapsulation());
        System.out.println("shared secrets match: " + Arrays.equals(ss1.getEncoded(), ss2.getEncoded()));
        System.out.println("ciphertext bytes: " + enc.encapsulation().length);
    }
}
Output
shared secrets match: true
ciphertext bytes: 1088

JavaScript v26.13.1

v26.13.1
// No KEM primitive in Node stdlib yet — the PQ action lives in the TLS layer:
// Chrome/Firefox already negotiate X25519MLKEM768 (X-Wing-style hybrid) by default.
// Shown: X25519, the classical half of that hybrid.
const { generateKeyPairSync, diffieHellman } = require("node:crypto");
const a = generateKeyPairSync("x25519");
const b = generateKeyPairSync("x25519");
const ss1 = diffieHellman({ privateKey: a.privateKey, publicKey: b.publicKey });
const ss2 = diffieHellman({ privateKey: b.privateKey, publicKey: a.publicKey });
console.log("x25519 secrets match:", ss1.equals(ss2));
console.log("shared secret bytes:", ss1.length);
Output
x25519 secrets match: true
shared secret bytes: 32

PHP v8.6.0

v8.6.0
// Post-quantum KEM families in Sodium (runtime needs libsodium >= 1.0.22).
// The sizes below are normative constants of X-Wing / FIPS 203 ML-KEM-768 —
// identical on every libsodium build, so this block prints facts only;
// live keypair/enc/dec runs are shown in the Go/Java/Rust blocks of this entry
echo "X-Wing (ML-KEM-768 + X25519): public key 1216, secret key 32, ciphertext 1120, shared secret 32, seed 32\n";
echo "ML-KEM-768 (FIPS 203 pure): public key 1184, secret key 2400, ciphertext 1088, shared secret 32, seed 64\n";
echo "flow: keypair() -> enc(public key) -> [ciphertext, shared secret] -> dec(ciphertext, secret key) -> same shared secret\n";
Output
X-Wing (ML-KEM-768 + X25519): public key 1216, secret key 32, ciphertext 1120, shared secret 32, seed 32
ML-KEM-768 (FIPS 203 pure): public key 1184, secret key 2400, ciphertext 1088, shared secret 32, seed 64
flow: keypair() -> enc(public key) -> [ciphertext, shared secret] -> dec(ciphertext, secret key) -> same shared secret

Python v3.15.2

v3.15.2
import hashlib

# Python stdlib has no raw KEM primitive (hashlib only hashes) — production code
# needs a third-party package (liboqs-python, pyca cryptography 45+). Below, the
# KEM data flow in toy form: a KDF instead of lattice math, so NOT secure.
seed = b"\x9d" + b"\x00" * 31                    # fixed seed keeps the demo output stable
ek = hashlib.sha256(b"ek" + seed).digest()       # keypair: ek travels, seed = dk
ss_sender = hashlib.sha256(b"ss" + ek).digest()  # encapsulate: sender secret
ek2 = hashlib.sha256(b"ek" + seed).digest()      # decapsulate: rebuild ek from dk
ss_receiver = hashlib.sha256(b"ss" + ek2).digest()
print("shared secrets match:", ss_sender == ss_receiver)
print("FIPS 203 ML-KEM-768 sizes: ek 1184, dk 2400, ct 1088, ss 32")
Output
shared secrets match: True
FIPS 203 ML-KEM-768 sizes: ek 1184, dk 2400, ct 1088, ss 32

Rust v1.99.1

v1.99.1
use ml_kem::{
    kem::{Decapsulate, Encapsulate},
    EncodedSizeUser, KemCore, MlKem768,
};

fn main() {
    // ml-kem crate (RustCrypto): FIPS 203 ML-KEM-768, pure Rust
    let mut rng = rand::thread_rng();
    let (dk, ek) = MlKem768::generate(&mut rng); // (secret, public) — secret comes first
    // encapsulate returns (ciphertext, shared secret)
    let (ct, ss_sender) = ek.encapsulate(&mut rng).unwrap();
    let ss_receiver = dk.decapsulate(&ct).unwrap();
    println!("shared secrets match: {}", ss_sender == ss_receiver);
    println!("ciphertext bytes: {}", ct.len());
    println!("encapsulation key bytes: {}", ek.as_bytes().len());
    println!("shared secret bytes: {}", ss_sender.0.len());
}
Output
shared secrets match: true
ciphertext bytes: 1088
encapsulation key bytes: 1184
shared secret bytes: 32

TypeScript v26.13.1

v26.13.1
import { generateKeyPairSync, diffieHellman } from "node:crypto";

// No KEM primitive in Node stdlib yet — the PQ action lives in the TLS layer:
// Chrome/Firefox already negotiate X25519MLKEM768 (X-Wing-style hybrid) by default.
// Shown: X25519, the classical half of that hybrid.
const a = generateKeyPairSync("x25519");
const b = generateKeyPairSync("x25519");
const ss1 = diffieHellman({ privateKey: a.privateKey, publicKey: b.publicKey });
const ss2 = diffieHellman({ privateKey: b.privateKey, publicKey: a.publicKey });
console.log("x25519 secrets match:", ss1.equals(ss2));
console.log("shared secret bytes:", ss1.length);
Output
x25519 secrets match: true
shared secret bytes: 32

Language differences

A KEM in one sentence: the sender "encapsulates" a symmetric session key against the receiver's public key, sends the ciphertext, and only the holder of the secret key can "decapsulate" the same key — TLS 1.3 and HPKE are built on KEMs. Two families land at once: the X-Wing hybrid (ML-KEM-768 + X25519, dual insurance: secure as long as either half holds) and pure post-quantum ML-KEM-768 (FIPS 203, standardized by NIST in Aug 2024, formerly Kyber). Why PQ now: "harvest now, decrypt later" — an adversary records ciphertext today and decrypts it once a quantum computer exists; long-lived secrets must migrate now.

Full list of the 12 functions across both families: sodium_crypto_kem_keypair (keypair, 1248 bytes = secret 32 + public 1216), sodium_crypto_kem_seed_keypair (deterministic rebuild from a 32-byte seed), sodium_crypto_kem_secretkey / sodium_crypto_kem_publickey (slice the halves off the keypair string), sodium_crypto_kem_enc (public key -> [ciphertext 1120, shared secret 32], ciphertext first), sodium_crypto_kem_dec (ciphertext + secret key -> shared secret) — the X-Wing family; sodium_crypto_kem_mlkem768_keypair / sodium_crypto_kem_mlkem768_seed_keypair (64-byte seed) / sodium_crypto_kem_mlkem768_secretkey (2400) / sodium_crypto_kem_mlkem768_publickey (1184) / sodium_crypto_kem_mlkem768_enc (ciphertext 1088) / sodium_crypto_kem_mlkem768_dec — the ML-KEM-768 family, identical workflow. A tampered ciphertext still makes dec return a value, just a different secret (implicit rejection, no exception).

PHP: sodium_crypto_kem_* needs libsodium >= 1.0.22 at runtime (new in 8.6, Sodium); enc returns a two-element array [ciphertext, shared_secret], seed_keypair throws SodiumException on a wrong seed length, and a tampered ciphertext makes dec implicitly reject with a different secret — all verified locally on libsodium 1.0.22; the block itself prints normative constant facts (independent of the libsodium version, identical on any PHP runtime), with live runs in the Go/Java/Rust blocks.

Go: the standard library crypto/mlkem (1.24+) is a native FIPS 203 implementation — Encapsulate() returns (sharedKey, ciphertext), shared key first, the reverse of PHP; a migration footgun. Pure ML-KEM, no X-Wing.

Java: built into JCA (Java 24+, JEP 496) — the KEM API: newEncapsulator(publicKey).encapsulate() -> KEM.Encapsulated (key() + encapsulation()), newDecapsulator(privateKey).decapsulate(ct) (example).

Rust: the ml-kem crate (RustCrypto, pure-Rust FIPS 203) — generate returns (dk, ek), secret first; encapsulate returns (ct, ss) (example).

Python: no raw KEM primitive in the stdlib — hashlib only hashes; the example shows the three-step data flow with a toy KDF (SHA-256), not real lattice crypto; raw ML-KEM needs third-party liboqs-python or pyca cryptography 45+. There is also negotiation-level PQ in TLS: the ssl layer (OpenSSL 3.5+/4.x backend) exposes post-quantum hybrid groups such as X25519MLKEM768 (the group list varies with the OpenSSL build, which is why it stays out of the example); new connections can negotiate them with no extra setup.

JavaScript: no KEM in Node crypto — the PQ action lives in the TLS layer; Chrome/Firefox already negotiate X25519MLKEM768 (an X-Wing-shaped hybrid) by default; the example shows X25519, the classical half of that hybrid; WebCrypto has no KEM API yet.

TypeScript: same as JavaScript (Node crypto).

C/C++: no KEM in the stdlib — production code uses liboqs (Open Quantum Safe, C API); the example shows the three-step data flow with a toy KDF over vendored SHA-256 (both sides derive the same secret), not real lattice crypto.

C#: the BCL ships MLKem (.NET 10/11+, FIPS 203) but via an OpenSSL backend, so availability varies by platform (unsupported on macOS; Linux needs OpenSSL 3.5+) — always probe MLKem.IsSupported first. Precisely because availability is not platform-stable, the example sticks to a fact identical on every platform (an ECDH roundtrip); the ML-KEM usage, for the record: MLKem.GenerateKey(MLKemAlgorithm.MLKem768) for the keypair, then Encapsulate(ct, ss) / Decapsulate(ct, ss), with size constants on MLKemAlgorithm.MLKem768's Ciphertext/SharedSecret/EncapsulationKeySizeInBytes.