Reviewing post-quantum cryptography code is harder than reviewing classical cryptography. The algorithms are newer, the implementation patterns less familiar, and many of the side-channel pitfalls are subtly different from what experienced reviewers learned with RSA and ECC. A thorough review checklist is essential.
This article presents a checklist that combines NIST guidance, OWASP recommendations, and lessons learned from open-source PQC implementations. It is not exhaustive but it covers the bread-and-butter findings we have seen repeatedly in audit work.
1. Constant-Time Operations
The first and most important question for any cryptographic implementation is whether secret-dependent operations run in constant time. A non-constant-time implementation leaks secrets through timing side channels.
For PQC specifically, the operations that must be constant-time include:
- ML-KEM polynomial sampling. The
SamplePolyCBDand related routines must not branch on secret bits. - ML-KEM compression and decompression. The bit-fiddling operations need to use bitwise ops, not modular reductions that may have variable-time hardware support.
- ML-DSA rejection sampling. The
RejNTTPolyandRejBoundedPolyfunctions sample polynomial coefficients with rejection. Make sure rejection does not leak which trial succeeded. - ML-DSA Decompose and HighBits/LowBits. These routines branch on coefficient values.
- SLH-DSA WOTS chaining. The chain function iterates a hash a secret-dependent number of times. The iteration count must not affect timing.
- All comparisons of secret-derived values. Constant-time memcmp, not memcmp.
Tools to check:
- dudect. Statistical timing analysis tool.
- ctgrind. Valgrind-based constant-time checker.
- Trail of Bits constant-time analysis skill. Their structured review approach.
- Manual review for
if (secret_bit)patterns and array indexing by secret values.
2. Side-Channel Hygiene Beyond Timing
Timing is not the only side channel. Cache, power, and electromagnetic side channels also matter, especially in high-assurance contexts.
Checklist items:
- Memory access patterns. ML-KEM and ML-DSA both have phases that index into arrays based on secret values. Look for array lookups indexed by
secret[i]and consider whether the access pattern leaks. - Power analysis countermeasures. For deployments in physically exposed environments (smart cards, IoT), power side channels are a documented attack vector. Reference NIST IR 8413A on side-channel considerations.
- Recompilation safety. Some constant-time tricks are removed by aggressive optimizers. Verify with the actual production toolchain, not just debug builds.
- Volatile and barrier annotations. Sensitive memory writes should not be optimized away. Look for
volatilewrites and explicit memory barriers.
3. RNG Sourcing
Post-quantum algorithms are highly sensitive to the quality of their randomness. ML-KEM key generation, ML-DSA signing in hedged mode, and SLH-DSA key generation all consume randomness.
Checklist:
- Source of randomness is
getrandom(2)(Linux),SystemRandomBytes(Windows BCrypt), orarc4random_buf(BSD/macOS). Notrand(), notsrand(time(NULL)). - No fallback to weak RNG on initialization failure. If the OS RNG is unavailable, the operation must fail, not silently fall back to a deterministic seed.
- Reseeding policy is documented. Long-running processes need a reseeding strategy.
- Test fixtures use deterministic RNG explicitly. KAT tests use a deterministic seed (the
zanddvalues from ACVP), but production code paths must never accept caller-supplied randomness. - Hedged mode correctness for ML-DSA. ML-DSA hedged signing mixes deterministic-from-secret with fresh randomness. Both inputs must be present and correctly combined.
NIST SP 800-90A, B, and C cover RNG construction, source testing, and DRBG construction respectively. SP 800-90B compliance for the entropy source is the gold standard.
4. KAT Validation
We have a separate article on PQC test vectors usage. For a code review, the relevant checks are:
- NIST ACVP vectors are run. The CI pipeline includes ACVP vectors for every implemented algorithm.
- All parameter sets are covered. ML-KEM-512, 768, 1024 if all are claimed. ML-DSA-44, 65, 87.
- Failure cases are tested. Invalid ciphertexts, wrong public keys, malformed signatures all produce expected errors.
- Vectors are pinned and vendored. Not fetched at CI time.
5. Key Material Handling
Secret keys, wrapped keys, and intermediate computations all need to be protected from accidental disclosure.
Checklist:
- Zeroization on drop. Secret keys, intermediate polynomials, and shared secrets are zeroed when no longer needed. Look for
Zeroizing, explicitmemset_s, or platform-specific equivalents. - No
Cloneon secret types. Cloning a secret introduces extra copies that must also be zeroized. Most cryptographic libraries either disable Clone on secret types or wrap them in single-instance handles. - No
DisplayorDebugon secret types. Logging or printing a secret type is a recipe for disaster. The type system should make this hard. - No serde Serialize on secret types unless absolutely necessary. Deserialization is fine; serialization can leak.
- Stack guarding for sensitive functions. Some compilers offer stack zeroing on function exit. Use it for hot paths.
6. Error Handling
PQC implementations have several error paths that need careful handling.
Checklist:
- ML-KEM decapsulation does not leak failure to attacker. The implicit-rejection path returns a deterministic but unrecoverable shared secret, not an error code that an attacker can observe.
- ML-DSA signature verification returns boolean, not exception. A verification failure is a normal outcome, not an error. The caller distinguishes "valid signature" from "invalid signature."
- Malformed input rejection is constant-time. An attacker should not learn how the input was malformed.
- Buffer length checks are explicit. PQC keys, ciphertexts, and signatures are large. A length mismatch should fail loudly and early.
- Panic safety in Rust. If you use unsafe and a panic happens between
mem::forgetand zeroization, you have a leak. Use scope guards.
Validating inputs before calling into a C library, and wrapping binding code that can panic in catch_unwind, keeps a panic in the binding layer from taking down the whole process. This is a defense in depth that is worth checking for in any Rust PQC code.
7. Hybrid Construction Correctness
If the code uses hybrid PQ + classical construction, several specific issues arise.
Checklist:
- Both shared secrets are combined correctly. The standard pattern is
HKDF(ML-KEM-secret || X25519-secret || transcript). The order, separator, and transcript content matter. - No concatenation without context separation. Concatenating raw shared secrets without a hash is unsafe under generic composition theorems.
- Both halves are used in signing. Hybrid signatures must combine both signature outputs into a single verifiable artifact, with both signatures required for validity.
- Backward compatibility with classical-only. If your code supports both classical-only and hybrid modes, the negotiation must be authenticated to prevent downgrade attacks.
The IETF PQUIP working group has draft documents (draft-ietf-pquip-hybrid-signature-spectrums) that specify several hybrid constructions. Reference them in code comments.
8. Random Number Quality in Tests
This sounds minor but it has bitten projects:
- Tests do not call
srand(0)and consume the production RNG. A test that resets the RNG to a deterministic seed and then runs production code paths will fail intermittently or produce confusing results. - Property tests use a deterministic but well-distributed seed.
quickcheckwith a fixed seed is fine.rand::thread_rng()in a test that compares against KAT vectors is a bug. - No "lucky" tests. A test that passes most of the time but occasionally fails because of randomness is a bug, not a flaky test.
9. FFI and Unsafe Code Boundaries
Most PQC implementations in higher-level languages wrap C reference implementations. The FFI boundary is a common bug surface.
Checklist:
- Buffer sizes are explicit on both sides. The C function expects exact lengths; Rust/Python/etc. must pass exactly that.
- Endianness is handled at the boundary. PQC algorithms are little-endian on the wire but some platforms are big-endian internally.
- Memory ownership is clear. Who allocates, who frees. A common bug is "C-allocated buffer freed by Rust drop handler."
- No use-after-free. Pointers from C may be invalidated by C-side state changes.
- Panic and exception safety. A panic in Rust must not unwind through C code without cleanup, and vice versa.
10. Documentation and Threat Model
The non-code parts of the review:
- Threat model is documented. What does the implementation protect against? What does it not?
- Side-channel posture is stated. "Constant-time on x86_64 with cmov, not validated on ARM" is honest and useful. "Constant-time" with no qualification is not.
- Validated vectors and test results are recorded. "Passes ACVP-Server commit abc123 for ML-KEM-768" is actionable.
- Algorithm choice is justified. Why ML-KEM-768 and not 512 or 1024? Why hybrid and not pure?
- Cryptoperiod is stated. How often should keys rotate? This connects to key rotation policies for PQC.
11. Specific PQC Implementation Gotchas
Some pitfalls that have appeared in real PQC code:
- NTT (Number-Theoretic Transform) ordering. ML-KEM and ML-DSA use NTT for polynomial multiplication. Bit-reversal versus natural order is a common bug source. Verify against reference implementation.
- Centered representation versus non-centered. Some operations use coefficients in
[-q/2, q/2), others in[0, q). Mixing the two is a bug. ||versusXORversus+. Hybrid combiners use specific operations. Substituting one for another silently produces incorrect output.- Hash function variant. SHAKE-128 versus SHAKE-256, SHA-256 versus SHA-512, all matter and all look similar in code.
- Domain separation tags. A hash used for two purposes needs distinct domain separation strings. Forgetting one is a subtle bug.
- Salt length and seed length. ML-KEM uses 32-byte seeds. ML-DSA uses 32-byte seeds. SLH-DSA seed length depends on parameter set. Check that buffer sizes match the standard.
12. Library Version and Provenance
The supply chain question:
- Are you using a maintained, reviewed library? Open Quantum Safe (liboqs) is one option. PQClean is another. Both have active maintainers.
- Is the library version pinned? Cryptographic library updates can introduce subtle behavior changes.
- Are upstream advisories monitored? Subscribe to security advisories for the libraries you depend on.
- Have you reviewed the dependency tree? Cryptographic libraries often have transitive dependencies that also handle sensitive data.
Sample Review Workflow
A practical PQC code review goes through phases:
- Pre-review: Confirm the algorithm and parameter set against the design doc. Confirm threat model and target.
- Static analysis: Run language-appropriate static analyzers (Clippy for Rust, Bandit for Python, etc.) plus crypto-specific tools (Semgrep with crypto rules).
- Constant-time check: Run
dudector equivalent. Manually review hot paths. - KAT validation: Confirm CI runs ACVP vectors for all parameter sets.
- Manual review: Walk through the implementation against the FIPS specification step by step. Check all 12 categories above.
- Threat model check: Compare what the code protects against to what the threat model claims.
- Documentation review: Make sure the documentation matches the code.
Frequently Asked Questions
How long should a PQC code review take? For a well-structured implementation with good test coverage, a thorough review of one algorithm (e.g., ML-KEM-768) is 1-2 weeks of senior reviewer time. For an end-to-end review of a hybrid implementation, plan for 4-8 weeks.
Can automated tools replace manual review? No. Static analysis and constant-time tools find a useful fraction of bugs but miss algorithmic issues, threat-model gaps, and subtle protocol misuse. Manual review by someone familiar with the FIPS standards is essential.
What is the most common PQC implementation bug? Constant-time violations in rejection sampling and polynomial coefficient handling. Both ML-KEM and ML-DSA have phases where naive implementations leak through timing.
Should I review the algorithm or the integration? Both. The integration (how your application uses the library) is at least as bug-prone as the algorithm. Misuse of a correct library is a leading cause of cryptographic vulnerabilities in production systems.
Does QNSQY use third-party PQC implementations? Yes. QNSQY uses open-source implementations: RustCrypto's ml-kem, ml-dsa and slh-dsa crates, which pass NIST's ACVP test vectors in QNSQY's test run, the pqcrypto crates (bindings to PQClean's C code) for its pre-standard FN-DSA and HQC, and established Rust libraries for X25519, Ed25519 and AES-GCM. None of them is CMVP-validated. The integration code is QNSQY's own.
Sources
- NIST FIPS 203 (ML-KEM Standard) — https://csrc.nist.gov/pubs/fips/203/final
- NIST FIPS 204 (ML-DSA Standard) — https://csrc.nist.gov/pubs/fips/204/final
- NIST FIPS 205 (SLH-DSA Standard) — https://csrc.nist.gov/pubs/fips/205/final
- NIST IR 8413A (Status Report on Side-Channel Considerations for PQC) — https://csrc.nist.gov/pubs/ir/8413/upd1/final
- NIST SP 800-90B (Recommendation for the Entropy Sources Used for Random Bit Generation) — https://csrc.nist.gov/publications/detail/sp/800-90b/final
- OWASP Cryptographic Storage Cheat Sheet — https://cheatsheetseries.owasp.org/cheatsheets/Cryptographic_Storage_Cheat_Sheet.html
Related Articles
- How to Use Official PQC Test Vectors
- Key Rotation Policies for PQC
- ML-KEM Explained
- Hybrid Encryption: Belt and Braces for the Quantum Transition
- Threat Modeling for PQC Systems
- ACME and PQC: Let's Encrypt Roadmap
- PQC in CI/CD Pipelines
- AWS CloudHSM: PQC Algorithm Coverage
- PKCS#11 PQC Mechanism Identifiers
Protect Your Data Before Q-Day Arrives
QNSQY's NIST-standardized post-quantum encryption protects files against both current and quantum-era threats.