Skip to content

Add WOLFSSL_MLKEM_DYNAMIC_KEYS for ML-KEM key memory optimization#4

Closed
Frauschi wants to merge 2 commits intomasterfrom
claude/practical-brattain
Closed

Add WOLFSSL_MLKEM_DYNAMIC_KEYS for ML-KEM key memory optimization#4
Frauschi wants to merge 2 commits intomasterfrom
claude/practical-brattain

Conversation

@Frauschi
Copy link
Copy Markdown
Owner

@Frauschi Frauschi commented Apr 8, 2026

Summary

  • Adds opt-in WOLFSSL_MLKEM_DYNAMIC_KEYS macro that makes priv, pub, and a (when WOLFSSL_MLKEM_CACHE_A) buffers in MlKemKey dynamically allocated pointers instead of static arrays
  • Buffers are right-sized to the actual ML-KEM level (512/768/1024) instead of the compile-time maximum
  • DecodePublicKey only allocates the public key buffer, saving private key memory for encapsulate-only use cases (e.g., TLS key exchange)
  • Incompatible with WOLFSSL_NO_MALLOC (compile-time error)
  • Off by default; no changes when macro is not defined

Memory savings (when ML-KEM-1024 is compiled in)

Scenario Static Dynamic Savings
ML-KEM-512 full key 4096 B 2048 B 2048 B
ML-KEM-512 pub-only 4096 B 1024 B 3072 B
ML-KEM-512 + CACHE_A 12288 B 4096 B 8192 B

Test plan

  • Default build (no macro): all tests pass
  • WOLFSSL_MLKEM_DYNAMIC_KEYS alone: ML-KEM tests pass
  • WOLFSSL_MLKEM_DYNAMIC_KEYS + WOLFSSL_MLKEM_CACHE_A: ML-KEM tests pass
  • WOLFSSL_MLKEM_DYNAMIC_KEYS + WOLFSSL_NO_MALLOC: compile-time error as expected

🤖 Generated with Claude Code

When enabled, the MlKemKey struct uses dynamically allocated pointers
instead of static arrays for priv, pub, and a (CACHE_A) buffers. This
right-sizes buffers to the actual ML-KEM level and only allocates the
needed key parts (e.g., no private key buffer for encapsulate-only use).

Saves ~2-4KB per key object (up to ~12KB with CACHE_A) when using
smaller key levels or public-key-only operations.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Comment thread wolfcrypt/src/wc_mlkem.c Outdated
Comment thread wolfcrypt/src/wc_mlkem.c Outdated
Comment thread wolfcrypt/src/wc_mlkem.c
- Indent preprocessor directives in Init to match surrounding code style
- Remove unnecessary block nesting in Free; move k declaration inside
  the if (key->priv != NULL) clause where it is actually needed
- Make mlkemkey_get_k() unconditionally available and reuse it in
  MakeKeyWithRandom to replace the duplicate type-to-k switch

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@Frauschi Frauschi closed this Apr 9, 2026
@Frauschi Frauschi deleted the claude/practical-brattain branch April 20, 2026 12:03
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant