← Back to section · Tutorials & Labs

Project: A File Encryption Tool Built on a Hybrid KEM

Wire ML-KEM-768 and X25519 together as a hybrid key encapsulation, derive a session key with HKDF, and encrypt files with AES-256-GCM: a complete, runnable, verifiable teaching-grade file encryption tool.

Published 22 November 2026 · 6 min read · PQ Frontier

Project: A File Encryption Tool Built on a Hybrid KEM
AI-generated site artwork
Video explainer · Code examples and hands-on projects

Assembling the parts from the earlier tutorials into one complete artifact is the best test of understanding. This project builds a command-line file encryption tool: the sender encrypts any file with the recipient’s hybrid public key, and the recipient decrypts it with the private key. It is small but complete — key generation, encapsulation, key derivation, symmetric encryption, file format, and decryption checks, one full chain. The boundary first: this is a teaching implementation whose purpose is to make the engineering structure of a hybrid KEM clear. The private key is stored as a plaintext local file with no passphrase protection and no integrity auditing, so never encrypt real sensitive data with it; in production use audited tools such as age or libsodium’s sealed box.

Goal and Architecture

The tool has three commands: keygen generates a key pair and writes out public and private key files; encrypt reads a public key and plaintext and produces a self-contained ciphertext file; decrypt reads the private key and ciphertext and recovers the plaintext. The encryption path is the standard hybrid encryption structure: ML-KEM-768 and X25519 each produce one shared secret, the two are concatenated into HKDF-SHA256 to derive a 256-bit session key, and the file content is encrypted with AES-256-GCM, whose authentication tag provides integrity. The ciphertext file stores the KEM ciphertext, the ephemeral X25519 public key, and the nonce in a simple binary header with fixed length prefixes, because the ML-KEM-768 ciphertext length is fixed by the standard at 1088 bytes — the benefit of using a standard parameter set: the format can be hard-coded and parsing never has to guess.

Why insist on hybrid? ML-KEM alone would work, but the hybrid structure answers a trust question: post-quantum algorithms have a much shorter cryptanalytic history than X25519, while classical algorithms fail wholesale against a quantum computer. Concatenating both into a single derived key buys insurance on both sides — the same idea that hybrid key exchange in TLS 1.3 uses in the real world; this project is its miniature file-based counterpart.

Walking Through the Core Code

Install the dependencies with pip install oqs cryptography: oqs is the Python binding for liboqs (oqs-python), and cryptography provides X25519, HKDF, and AES-GCM. Key generation and the encryption core look like this:

import oqs, os, struct
from cryptography.hazmat.primitives.asymmetric.x25519 import (
    X25519PrivateKey, X25519PublicKey)
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.ciphers.aead import AESGCM

KEM_ALG = "ML-KEM-768"

def derive_key(ss_kem: bytes, ss_x: bytes) -> bytes:
    return HKDF(algorithm=hashes.SHA256(), length=32,
                salt=None, info=b"pq-file-tool v1").derive(ss_kem + ss_x)

def encrypt(pub_kem: bytes, pub_x_bytes: bytes, data: bytes) -> bytes:
    with oqs.KeyEncapsulation(KEM_ALG) as kem:
        ct_kem, ss_kem = kem.encap_secret(pub_kem)
    eph = X25519PrivateKey.generate()
    ss_x = eph.exchange(X25519PublicKey.from_public_bytes(pub_x_bytes))
    key = derive_key(ss_kem, ss_x)
    nonce = os.urandom(12)
    ct = AESGCM(key).encrypt(nonce, data, None)
    eph_pub = eph.public_key().public_bytes_raw()
    return b"PQF1" + ct_kem + eph_pub + nonce + ct

Several details deserve attention. First, encap_secret returns the ciphertext and the shared secret in one call, and the encapsulation public key is just a byte string — oqs does not maintain a “public key object”. This surprises many people; when debugging, keep straight what is bytes and what is an object. Second, the HKDF info field carries the tool name and version. That is context binding: the same pair of shared secrets derives naturally separated keys in different protocols, and bumping the version later keeps old and new ciphertexts from interfering. Third, decryption must mirror the order exactly: decap_secret with the private key recovers the KEM shared secret, the X25519 private key and the ephemeral public key from the header do an exchange, and the same HKDF derives the key; if any byte disagrees, GCM decryption raises InvalidTag — a good sign that the integrity check is doing its job.

A word on the shape of key generation: keygen is the mirror image of encryption — it generates a KEM key pair with oqs.KeyEncapsulation(KEM_ALG) and exports the private key bytes with export_secret_key(), then generates an X25519 key pair; the public halves are assembled into one public key file and the private halves into one private key file. Both files follow the same “magic number plus fixed-length fields” convention, so the decryptor checks the magic first and confirms the file type — a beginner mistake like feeding the private key file where the public key belongs is caught at step one, instead of surfacing later as an incomprehensible GCM error after a wrong key is derived. The private key file’s permissions should also be set to owner-only on the way out (os.chmod(path, 0o600)) — a teaching project does no real key management, but habits like this are worth forming from day one.

Running and Verifying

After the three commands work, run at least four checks. First, round-trip equality: hash a known file with SHA-256, encrypt and decrypt it, and hash again — the two values must match. Second, tampering must fail: flip any byte in the middle of the ciphertext file with a hex editor, and decryption must error rather than emit corrupted data — that is exactly what the AEAD tag is for. Third, the wrong key must fail: decrypting with a different private key must also raise an error. Fourth, check the length: the ciphertext file should be exactly 4 (magic) + 1088 (KEM ciphertext) + 32 (ephemeral public key) + 12 (nonce) + 16 (GCM tag) = 1152 bytes larger than the plaintext; one byte more or less means the format is written wrong. Together these four checks form the minimal acceptance suite for this small tool; in a real project they belong in automated tests, not in a one-off manual run.

Exercises

Four exercises, easy to hard. One: replace the fixed-length header with a TLV format carrying a version and an algorithm identifier, leaving room to negotiate ML-KEM-1024 later — and think about how the decryptor should refuse if the algorithm identifier is tampered with to force a downgrade. Two: add passphrase protection to the private key file — derive a key from the passphrase with hashlib.scrypt, encrypt the private key bytes with AES-GCM, and compare how scrypt parameters affect unlock time. Three: replace the X25519 channel with a single ML-KEM-1024 channel, then with a three-channel variant, and measure how ciphertext size and runtime change, testing your intuition about the size ledger. Four, the advanced one: move the same encapsulation logic onto sockets for two-process communication — exactly what the KEM key exchange demo service in this same subcategory does; comparing the two shows how file formats and wire formats differ and where they coincide.

Summary

This project turns the hybrid KEM from a concept into runnable code: two-channel encapsulation, concatenated derivation, AEAD encryption, a fixed format, and four acceptance checks. Its value is not raw power but a complete structure where every design choice has a stated reason. The boundary, one last time: plaintext private keys on disk, no auditing, no side-channel hardening — this tool is for learning and experiments only. Once you understand the structure, leave production work to mature tools and spend your energy on key management and protocol design, the genuinely harder problems.

Tags: ML-KEMHybrid EncryptionliboqsFile Encryption