Post-Quantum Hybrid Envelope Encryption in Python: Anatomy of Our Code

​The transition to post-quantum cryptography (PQC) rarely starts by replacing every cryptographic routine all at once. In practice, real systems need to coexist with mature classical libraries, evolve key exchange algorithms, and maintain data integrity throughout the process.

​The hybrid_pqc.py module and the test_hybrid_pqc.py suite we built implement exactly this pragmatic middle ground: application-level hybrid envelope encryption, combining X25519 (classical) and ML-KEM-768 (the NIST FIPS 203 standard for Key Encapsulation Mechanism) to protect an AES-256-GCM symmetric key.

​1. The Core Idea: Separation of Responsibilities and Defense in Depth

​Instead of encrypting payloads directly with asymmetric or post-quantum schemes, the code divides the problem into three clear layers:

​Hybrid secret agreement (hybrid_encapsulate_with_oqs and hybrid_decapsulate_with_oqs): Combines a shared secret obtained via ephemeral X25519 exchange with the secret encapsulated using ML-KEM-768. In the bundle (kem_bundle), the first 32 bytes correspond to the ephemeral X25519 public key, and the remainder contains the ML-KEM-768 ciphertext.

​KEK derivation (derive_hybrid_kek): Concatenates classical_shared_secret + pq_shared_secret as input keying material (IKM) for HKDF-SHA256, producing a 32-byte (256-bit) Key Encryption Key (KEK) bound to the policy context.

​Double-layer AEAD envelope (seal_payload and open_payload): A random 32-byte data key (DEK) is generated for each payload and encrypted with AES-256-GCM under the KEK (wrapped_dek), while the payload itself (plaintext) is encrypted with AES-256-GCM under the DEK (ciphertext).

​The advantage of the hybrid model is straightforward: even if one cryptographic family faces a mathematical or computational breakthrough in the future, reconstructing the combined secret in HKDF still depends on the other family.

​2. Context Authentication and Downgrade Prevention

​A common mistake in encrypted formats is treating headers or algorithm metadata as merely informational. If an attacker changes kem_scheme or aead_scheme in the envelope, the system may be induced to accept a weaker or incompatible policy (downgrade).

​In our code, this is handled in two steps:

​Explicit validation before decryption (open_payload): Required fields are checked and compared with expected_policy (policy_id, kem_scheme, and aead_scheme), raising CryptoPolicyError if they do not match.

​Binding to the AAD (_compute_aad): The Additional Authenticated Data passed to AES-256-GCM for the payload includes not only policy_id, but also kem_scheme, aead_scheme, and kem_bundle itself. Any 1-bit change to these fields causes the authentication check to fail and raises DecryptionError.

​3. The Role of oqs and the Scope Limitations

​The cryptography standard library provides X25519, HKDF, and AESGCM, but does not natively implement ML-KEM-768. For this reason, the code isolates the post-quantum operation in generate_hybrid_keypair_with_oqs, hybrid_encapsulate_with_oqs, and hybrid_decapsulate_with_oqs using oqs.KeyEncapsulation("ML-KEM-768").

​It is worth keeping this module’s limitations within a larger architecture clear:

​It covers payload encryption and hybrid encapsulation, but does not replace TLS/mTLS for network communications, certificate/code signing (which uses schemes such as ML-DSA / SLH-DSA), or secure key management in an HSM/KMS.

​In production, private keys must be protected (for example, in vaults or HSMs), and sensitive buffer clearing in memory, key rotation, and policy versioning should be part of the operational lifecycle.

​4. How the Test Suite Validates Critical Behavior

​In test_hybrid_pqc.py, the tests are structured to ensure that security failures are deterministic and observable:

​Full cycle (seal_payload -> open_payload): Verifies that the original plaintext is recovered intact both with injected secrets and through the encapsulate + decapsulate flow.

​Rejection of policies and missing fields: Tests changes to policy_id, kem_scheme, and aead_scheme, as well as the removal of keys from the envelope dictionary.

​Tamper detection (bit-flip): Changes 1 bit in kem_bundle, kek_nonce, wrapped_dek, data_nonce, or ciphertext and confirms that DecryptionError is raised.

​Simulation and real-world testing: Uses _FakeOqsKEM to test the logic without requiring liboqs to be compiled in every CI environment, while keeping test_hybrid_full_roundtrip_with_real_oqs to validate the real oqs package when available.

​Conclusion

​The code demonstrates how to structure a crypto-agile, hybrid foundation in Python without mixing business rules with scattered cryptographic primitives. By combining X25519 and ML-KEM-768 via HKDF, protecting the DEK with AES-256-GCM, authenticating metadata in the AAD, and covering tampering and downgrade scenarios with automated tests, it provides a solid, verifiable starting point for evolving applications toward the post-quantum era.

$BTC