Skip to content

crypto: Optimize built-in AES, CMAC, and ECC performance - #1017

Open
zxzxwu wants to merge 1 commit into
google:mainfrom
zxzxwu:optimize-builtin-crypto
Open

zxzxwu wants to merge 1 commit into
google:mainfrom
zxzxwu:optimize-builtin-crypto

Conversation

@zxzxwu

@zxzxwu zxzxwu commented Oct 23, 2026

Copy link
Copy Markdown
Collaborator

Summary

Optimize the pure-Python built-in cryptography backend (bumble/crypto/builtin.py):

  • AES / ECB / CBC / CMAC:
    • Replace byte-by-byte generator XOR (_xor) with int.from_bytes / int.to_bytes.
    • Lazily compute decryption round keys (_kd) via @functools.cached_property and cache key expansion (_expand_encryption_key, _expand_decryption_key) with @functools.lru_cache.
    • Unroll state word transforms in _AES.encrypt and _AES.decrypt and use a precompiled struct.Struct('>4I').
    • Fix _ECB.decrypt calling self._aes.encrypt instead of self._aes.decrypt.
    • Cache CMAC subkeys (_cmac_subkeys) and avoid double-encrypting the final 16-byte block in _CMAC.
  • ECC (SECP256R1):
    • Cache _public_key on EccKey so accessing both .x and .y does not perform scalar multiplication twice.
    • Reuse a singleton _SECP256R1 curve instance.
    • Reduce intermediate values modulo p in Jacobian point doubling/addition, use the a = p - 3 optimization for P-256, and support fast mixed addition when z2 == 1.
    • Use a 4-bit window for general Jacobian scalar multiplication (_jacobian_mul) and a lazy 16-point 4-tooth comb table for fixed-base generator multiplication (generate_public_key).

Benchmarks

Operation Before After Speedup
e(k, d) 60.1 µs 29.8 µs (13.1 µs cached key) 2.0x – 4.6x
aes_cmac(16B, k) 155.9 µs 45.1 µs (13.8 µs cached key) 3.5x – 11.3x
aes_cmac(64B, k) 238.6 µs 90.4 µs (57.9 µs cached key) 2.6x – 4.1x
EccKey.generate() + .x, .y 10.45 ms 0.61 ms ~17.1x
EccKey.dh(bx, by) 5.30 ms 1.43 ms ~3.7x

@zxzxwu
zxzxwu force-pushed the optimize-builtin-crypto branch from f682659 to 5a8a17e Compare October 23, 2026 09:26

This branch has not been deployed

No deployments
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