This project is a pure Python implementation of Kyber, the lattice-based Key Encapsulation Mechanism (KEM) algorithm selected by NIST for post-quantum standardization (now published as FIPS 203: ML-KEM).
This implementation is developed FOR EDUCATIONAL AND RESEARCH PURPOSES ONLY.
This project provides a complete, from-scratch implementation of the ML-KEM standard, including:
-
Full KEM Scheme (IND-CCA2): Implements
ML-KEM.KeyGen,ML-KEM.Encaps, andML-KEM.Decaps. -
Underlying PKE Scheme (IND-CPA): Implements
K-PKE.KeyGen,K-PKE.Encrypt, andK-PKE.Decrypt. -
Polynomial Arithmetic: Provides a Polynomial class for all operations in the ring
$R_Q = \mathbb{Z}_Q[X] / (X^N + 1)$ . -
Number Theoretic Transform (NTT): Includes correct implementations of
NTTandinverse_NTT(Algorithms 9 & 10) for fast polynomial multiplication, with a correspondingPolynomialNTTclass. -
Cryptographic Primitives: Implements all required hash functions (
XOF,PRF,H,J,G) as specified by FIPS 203, usingpycryptodomeandhashlib. -
Conversion & Sampling: Correctly implements
SampleNTT,SamplePolyCBD,Compress/Decompress, andByteEncode/ByteDecode. -
Parameter Support: A full
unittestsuite validates all three official parameter sets: ML-KEM-512, 768, and 1024.
The code is structured modularly to mirror the FIPS 203 specification:
constants.py: Defines core constants likeN,Q, and the pre-computedZETAStwiddle factors.hash.py: Wrappers for all cryptographic hash functions (SHAKE-128, SHAKE-256, SHA3-256, SHA3-512).conversion.py: Handles all serialization (ByteEncode/ByteDecode), bit-packing (BitsToBytes/BytesToBits), andCompress/Decompressfunctions.polynomial.py: The core of the project. Implements thePolynomialandPolynomialNTTclasses, all polynomial arithmetic,NTT/inverse_NTT, and sampling functions (SampleNTT,SamplePolyCBD).utils.py: Contains helper functions for the NTT, such asBaseCaseMultiply(Algorithm 12).pke_scheme.py: Implements theK_PKEclass, representing the IND-CPA secure public-key encryption scheme (Algorithms 13-15).kem_scheme.py: Implements the finalML_KEMclass, building the IND-CCA2 secure Key Encapsulation Mechanism on top ofK_PKE(Algorithms 16-21).test_ml_kem.py: Aunittestfile that runs a full KeyGen, Encapsulation, and Decapsulation cycle for all three parameter sets to verify correctness.
The project is set up for testing using Python's built-in unittest module.
- Ensure you have the required dependencies (primarily
pycryptodomefor the hash functions):
pip install pycryptodome- Run the main test file from your terminal:
python test_ml_kem.py- This will execute the full KEM cycle for ML-KEM-512, 768, and 1024, printing the status and verifying that the encapsulated and decapsulated keys match.