Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/ecies/js-post-quantum/llms.txt

Use this file to discover all available pages before exploring further.

The encrypt function is the primary entry point for post-quantum encryption in @ecies/post-quantum. It accepts a receiver’s ML-KEM public key and plaintext bytes, performs key encapsulation to derive a shared secret, and symmetrically encrypts the data using an AEAD cipher — returning a single self-contained encrypted payload.

Function Signature

function encrypt(
  receiverPK: Uint8Array,
  data: Uint8Array,
  config?: Config
): Uint8Array

Parameters

receiverPK
Uint8Array
required
The receiver’s raw ML-KEM public key. Obtain this from config.asymmetricModule.keygen().publicKey. The expected byte length depends on the configured variant: 800 bytes for ML-KEM-512, 1184 bytes for ML-KEM-768, and 1568 bytes for ML-KEM-1024.
data
Uint8Array
required
The plaintext data to encrypt. Must be a Uint8Array. To encrypt a string, convert it first using new TextEncoder().encode(str).
config
Config
Configuration specifying algorithm choices. Defaults to DEFAULT_CONFIG, which uses ML-KEM-768 for key encapsulation, AES-256-GCM for symmetric encryption, and a 16-byte nonce. Pass a custom Config instance to override any of these settings.

Return Value

encrypted
Uint8Array
The encrypted payload as a contiguous byte array with the following layout:
pke_ciphertext (768 / 1088 / 1568 bytes)
  || nonce (12 / 16 / 24 bytes)
  || AEAD tag (16 bytes)
  || ciphertext (same length as plaintext)
The pke_ciphertext size is determined by config.asymmetricAlgorithm. The nonce size is config.symmetricNonceLength for AES-256-GCM, or always 24 bytes for XChaCha20-Poly1305.

How It Works

  1. Calls config.asymmetricModule.encapsulate(receiverPK), which returns { cipherText: pke, sharedSecret }. The pke is the encapsulated key that the receiver needs to recover the shared secret.
  2. Uses sharedSecret as the symmetric key to encrypt data with the configured AEAD cipher (AES-256-GCM or XChaCha20-Poly1305), producing a payload of nonce || AEAD tag || ciphertext.
  3. Returns concat(pke, nonce, tag, ciphertext) as a single Uint8Array.

Examples

import { DEFAULT_CONFIG, encrypt } from "@ecies/post-quantum";

const { publicKey, secretKey } = DEFAULT_CONFIG.asymmetricModule.keygen();
const encoder = new TextEncoder();
const data = encoder.encode("secret message");

const encrypted = encrypt(publicKey, data);
console.log(encrypted.length); // 1088 + 16 + 16 + 14 = 1134 bytes

Error Cases

  • Throws Error: Unsupported asymmetric algorithm: <value> if config.asymmetricAlgorithm is set to a value outside "ml-kem-512" | "ml-kem-768" | "ml-kem-1024".
  • Any errors raised internally by the AEAD cipher (e.g., from the underlying @noble/post-quantum or @noble/ciphers primitives) propagate up unchanged.

Build docs developers (and LLMs) love