ML-KEM-768 lets a sender and a recipient obtain the same 32-byte secret. The recipient sends a public key. The sender returns a ciphertext. Each side keeps its own copy of the secret.
uses
System.SysUtils, StreamSec.DSI.PKTypes, StreamSec.DSI.MLC, stAESCT;
function NewRecipientKey(out aPrivateKey: iMLKEMPrivateKey): TBytes; var lPublicKey: iMLKEMPublicKey; begin MustGetDSIML.KEMKeyGen(mlkem768, lPublicKey, aPrivateKey); Result := lPublicKey.GetEncodedPublicKey; end;
Keep the private key on the recipient. Give the sender the 1,184 bytes returned by GetEncodedPublicKey through a channel that authenticates the recipient, or pin that key in the sender's configuration. Anyone who substitutes their own public key can recover the resulting secret.
StreamSec.DSI.MLC registers the ML-KEM provider. The sample also links stAESCT so the random generator has a constant-time software AES implementation on processors without AES instructions.
function EncapsulateForRecipient(const aEncodedPublicKey: TBytes; out aSenderSecret: TBytes): TBytes; var lPublicKey: iMLKEMPublicKey; begin lPublicKey := MustGetDSIML.NewKEMPublicKey(mlkem768, aEncodedPublicKey); MustGetDSIML.KEMEncaps(lPublicKey, aSenderSecret, Result); end;
KEMEncaps generates a fresh secret on each call. The function returns the 1,088-byte ciphertext to transmit to the recipient. Its separate aSenderSecret output stays with the sender. Preserve the ciphertext bytes exactly when transporting them.
function DecapsulateForRecipient(const aPrivateKey: iMLKEMPrivateKey; const aCiphertext: TBytes): TBytes; begin if (aPrivateKey = nil) or (aPrivateKey.GetKeySize <> mlkem768) then raise EArgumentException.Create('An ML-KEM-768 private key is required'); MustGetDSIML.KEMDecaps(aPrivateKey, aCiphertext, Result); end;
Pass the ciphertext to DecapsulateForRecipient with the private key from the first step. With the original ciphertext and matching key, the result is the same 32 bytes that the sender received.
A ciphertext of the wrong length raises eMLKEMWrongCipherTextSize. An invalid ciphertext of the expected length produces a replacement 32-byte secret. This is ML-KEM's implicit rejection. To confirm that the peers derived the same secret, verify the protocol's authentication tag using a key derived from that secret. Anyone with the recipient's public key can encapsulate, so a protocol that requires the sender's identity must authenticate it separately.
For a TLS connection, see Connect with X25519MLKEM768 in TLS 1.3.
StreamSec.DSI.PKTypes · StreamSec.DSI.MLC · stAESCT