Pure-Python, zero-dependency speed-up across every hot path. No public API,
error-semantics or security change.
Measured (interleaved A/B min-of-N, idle 16-core, 1 KiB payload):
Base64 decode 21.98x
Base58 encode 8.01x
ChaCha20-Poly1305 3.54x
XChaCha20-Poly1305 3.28x
Base64 encode 2.98x
AES-256-GCM (enc) 2.25x (dec) 2.26x
AES-GCM-SIV enc 2.06x
AES-256 CTR/ECB/CBC 2.01x / 1.96x / 1.88x
AES single block 1.87x
Poly1305 MAC 1.41x
Ed25519 sign 1.41x
X25519 base 1.19x
BLAKE2b / SHA3-512 / SHAKE128 1.34x / 1.33x / 1.30x
=> 24 improved, 3 unchanged, 0 regressed.
Techniques (all pure Python):
- code-generated, fully unrolled AES round function and Keccak-f[1600]
- big-integer bulk operations for GHASH, POLYVAL, buffer XOR, Base64 pack
- precomputed lookup tables (AES T-tables, GHASH/POLYVAL 4-bit windows)
- branch-free constant-time selection in Ed25519 scan and X25519 ladder
- lazy modular reduction in X25519 field arithmetic
- batched Base58/Base64 processing
- inlined inner loops in AEAD assembly and the SHA-2 message schedule
Verification:
- full test suite: 639 passed, 1 skipped, 0 failed
- all FIPS / RFC / NIST vectors reproduce byte-for-byte
- differential probe of 1266 deterministic inputs: identical
(one unreachable private-helper edge case, no caller can reach it)
- public API signature comparison: 0 removals, 0 changes
- independent security regression suite: 35 / 35
Also adds docs/benchmark.md, bench/benchmark.py and the v3.2.1 documentation.
28 KiB
Changelog
This file records all notable changes to purepycrypto.
The format follows Keep a Changelog, and the version numbers follow Semantic Versioning.
Unreleased
(none)
[3.2.1] - 2026-09-27
Changed — performance overhaul (pure Python, no API change)
Every hot path was reworked. The library is still 100% pure Python with zero dependencies; no primitive was replaced by a C-backed shortcut. The public API, the error semantics and the security properties are unchanged.
Measured speed-ups (v3.2.0 -> v3.2.1, interleaved A/B min-of-N on an idle 16-core machine, 1 KiB payload):
| Operation | Speed-up |
|---|---|
| Base64 decode | 21.98x |
| Base58 encode / decode | 8.01x / 3.98x |
| ChaCha20-Poly1305 / XChaCha20-Poly1305 encrypt | 3.54x / 3.28x |
| Base64 encode | 2.98x |
| AES-256-GCM encrypt / decrypt | 2.25x / 2.26x |
| AES-GCM-SIV encrypt | 2.06x |
| AES-256 CTR / ECB / CBC | 2.01x / 1.96x / 1.88x |
| AES single block (256-bit) | 1.87x |
| Poly1305 MAC | 1.41x |
| Ed25519 sign / verify / publickey | 1.41x / 1.39x / 1.39x |
| X25519 base | 1.19x |
| BLAKE2b / SHA3-256 / SHA3-512 / SHAKE128 | 1.34x / 1.26x / 1.33x / 1.30x |
| Geometric mean over 27 operations | 1.96x |
24 improved, 3 unchanged, 0 regressed. See docs/benchmark.md
for the full table and methodology.
Techniques used (all pure-Python):
- Code-generated, fully unrolled functions for the AES round function and the Keccak-f[1600] permutation, eliminating per-round loops, indexing and attribute lookups.
- Big-integer bulk operations for GHASH, POLYVAL, buffer XOR and the
Base64 pack/unpack paths (
int.from_bytes/to_bytes/^execute in C over a whole buffer in a single call). - Precomputed lookup tables: AES T-tables, GHASH / POLYVAL 4-bit windows, Keccak rho/pi offset tables, precomputed DER length headers.
- Constant-time-safe selection in the Ed25519 scalar scan and the X25519 Montgomery ladder (branch-free masking, timing proven comparable).
- Lazy modular reduction in X25519 field arithmetic, replacing a
% pper multiply with a cheaper fold. - Batch Base58 / Base64 processing, removing the per-character
divmod(the previous Base58 hot spot). - Inlined inner loops in AEAD assembly, the CTR/GCM block loops and the message schedule of SHA-2.
Verified — no behavior change
- Full test suite: 639 passed, 1 skipped, 0 failed.
- Standard vectors (FIPS 180-4 / FIPS 197 / FIPS 202 / RFC 5869 / RFC 6070 / RFC 7748 / RFC 7914 / RFC 8032 / RFC 8439 / RFC 8452 / RFC 9106 / NIST GCM) reproduce byte-for-byte.
- Differential probe of 1266 deterministic inputs against v3.2.0: identical,
except one unreachable private helper (
der._der_lenwith a negative argument, which no caller can produce since every call site passeslen()). - Public API signature comparison: 0 removals, 0 changes.
- Independent security regression suite: 35 / 35 (AEAD tamper detection, constant-time comparison helpers, X25519 low-order points, Ed25519 constant-time selection, RSA failure paths, error-message hygiene).
Changed — full English localization
- Documentation, code comments and error messages are now entirely in English.
This covers all modules under
purepycrypto/,docs/*.md,README.md,CHANGELOG.md,setup.py,pyproject.toml, the test suite and the examples. No public API, identifier, error code or behavior was changed. - The interactive TUI keeps its Chinese interface: the
cnlanguage pack and the TUI menu text are intentionally left as-is and switch with the TUI language.
Fixed — TUI error localization
- Errors surfaced inside the TUI are now localized at the display layer: the library
itself always reports English messages/suggestions, while the TUI maps a known
PPYC_ERR_*code back to Chinese when the TUI language iscn(see_TUI_ERR_TEXT/_tui_error_text()incli.py). Unknown codes fall back to the original English text. menu9/menu10(Encoding/Decoding, Secure Random) were missing from the language pack and rendered as raw key names; both are now proper i18n entries inenandcn.- The Encoding and Secure Random sub-menus were rewritten to use the i18n layer, so
they are now fully Chinese in
cnmode and fully English inenmode (previously they mixed both). Ctrl+Cprinted the literalbyebecause_t('bye')referenced a non-existent key; it now uses_t('goodbye').
[3.2.0] - 2026-09-27
Added — 3 new algorithm modules
1. purepycrypto.encoding — encoding module
Hand-written bitwise implementation (does not call the base64 library), byte-for-byte identical to the standard library:
- Base64 (RFC 4648 §4):
b64encode/b64decode,b64encode_urlsafe/b64decode_urlsafe(URL-safe),b64encode_nopad/b64decode_nopad(no padding) - Base32 (RFC 4648 §6/§7):
b32encode/b32decode(standard A-Z2-7),b32encode_hex/b32decode_hex(Extended Hex 0-9A-V) - Base16/Hex (RFC 4648 §8):
hex_encode/hex_decode,hex_encode_sep/hex_decode_sep(with separators, e.g.de:ad:be:ef) - Base58 (Bitcoin alphabet):
b58encode/b58decode - Big integer ↔ Base64URL:
b64_encode_bigint/b64_decode_bigint(JWKn/estyle) - Strict validation: invalid character/length/padding → returns a unified error tuple (
PPYC_ERR_INVALID_ENCODING/_LENGTH/_HEX)
Verification: byte-for-byte identical to the stdlib across multiple lengths × multiple random rounds; all RFC 4648 §10 vectors match exactly; zero differences over 400 fuzz rounds.
2. purepycrypto.rand — cryptographically secure random numbers (CSPRNG)
Uses only the OS CSPRNG (os.urandom / secrets); the random module is explicitly forbidden:
- Basic randomness:
random_bytes(n),random_int(a,b),random_below(n),random_bit(),random_bits(k)— all use rejection sampling, with no modulo bias - Tokens / strings:
token_bytes,token_hex,token_urlsafe,random_string(length, alphabet) - Password generation:
random_password(length, upper, lower, digits, special, exclude)— guarantees at least one character of each class - Uniqueness:
random_uuid4()(RFC 4122 v4),random_choice,random_sample - Entropy source unavailable → fatal
PPYC_ERR_ENV(never downgrades to an insecure entropy source)
Verification: chi-square uniformity test (random_int(0,9) χ²=6.58 < upper bound 34.5; random_below(256) χ²=295.9 < 390.5); 1000 uuid4/token values with no duplicates.
3. purepycrypto.kdf2 — hardened key derivation
- PBKDF2 (RFC 8018):
pbkdf2(password, salt, iterations, dklen, hash_name), supporting sha1/sha256/sha384/sha512- strict salt-length check (<8 bytes →
PPYC_ERR_INVALID_SALT;min_salt_lencan relax it for compatibility with legacy systems)
- strict salt-length check (<8 bytes →
- Argon2 (RFC 9106):
argon2id_hash/argon2i_hash/argon2d_hash(with sensible defaults t=3/m=65536/p=4)argon2id_hash_encoded()outputs a standard PHC string:$argon2id$v=19$m=...,t=...,p=...$<salt>$<hash>argon2id_verify()constant-time comparison
- scrypt convenience wrapper:
scrypt_simple(password, salt, n, r, p)(recommended parameters)
Verification: byte-for-byte identical to hashlib.pbkdf2_hmac; RFC 9106 §5 official vectors; the PHC format interoperates with argon2-cffi.
Changed
__init__.py: exports the public API of the three new modules (_HAS_KDF2/_HAS_ENCODING/_HAS_RANDcapability flags)- New CLI subcommands:
purepycrypto encode --format base64|base64url|base32|hex|base58 --op enc|decpurepycrypto random --kind bytes|token|urlsafe|password|uuid
- New TUI menu items:
[9] Encoding/[10] Random(bilingual CN/EN) build_single.py: includesencoding/rand/kdf2in the single-file merge; adds single-file alias guidance
Verification
- New tests:
test_encoding.py(44 cases),test_rand.py(43 cases),test_kdf2.py - All three modules pass standard vectors + cross-verification against the stdlib/authoritative implementations
[3.1.4] - 2026-09-27
Added
Unified error system (purepycrypto/_ppyc_error.py)
Library-wide error handling is fully unified into two categories:
- Fatal error → raise
PPYC_ERR: scenarios where an internal invariant is broken and safe execution cannot continue. Carries the three attributescode/message/suggestion. - Non-fatal error → return a 3-tuple
(error_code, error_message, suggestion): expected scenarios such as invalid input, failed validation, authentication failure, parse failure. On success it returns the actual value (orOK_TUPLE=(None,None,None)for validation-style APIs).
What's new:
- Exception class
PPYC_ERR(and aliasPPYCError), withas_tuple()support. - Helper functions:
err()/ok()/is_ok()/is_err()/raise_ppyc()/OK_TUPLE/PPYCResult. - 41 standard error codes, unified prefix
PPYC_ERR_, covering: general / arguments / key-nonce-IV / authentication-decryption / encoding-parsing / file IO / environment dependencies / algorithm parameters / CLI-TUI — nine major categories. - Enforced error-code prefix (
err()rejects any prefix other thanPPYC_ERR_). - The legacy exception names
CryptoError/DecryptionError/Ed25519Errorare all kept as subclasses ofPPYC_ERR, carrying default error codes, ensuring backward compatibility. - New documentation
docs/errors.md(error-system manual: design principles / API / complete error-code table / real examples). - New test
purepycrypto/tests/test_errors.py(23 cases).
Changed (⚠️ Breaking)
raise ValueError/raise SystemExitin all modules have been converted to the unified system:- Public-API parameter validation / authentication failure / decryption failure → return a tuple
(e.g.
AES.gcm_decrypt,rsa_oaep_decrypt,chacha20poly1305_decrypt,blake2b(invalid digest_size),shake128/256(invalid outlen),sha3_batch(invalid algorithm name), etc.) - Constructors / internal helpers → raise
PPYC_ERR(e.g.AES(key)key length,RSAPrivateKey(...)key material,choose_hash,oaep_encode, etc.)
- Public-API parameter validation / authentication failure / decryption failure → return a tuple
(e.g.
- CLI:
SystemExitis fully replaced byPPYC_ERR;_cli_maincatches them uniformly and maps exit codes:0=success /2=PPYC_ERR/3=file not found /4=argument error. - TUI: pipe/redirect input end (EOF) → raises
PPYC_ERR_EOF, caught by_tui_main, which prints a unified error message (including a suggestion) and returns exit code 2, no longer raising a bareEOFError. - Single-file packaging:
_ppyc_erroris included in the merge (prioritized over other modules); the version number is now read dynamically from_version.py.
Fixed
6 real defects newly found by the v3.1.4 deep audit (all captured by the new boundary tests and audit scripts):
sha3.pyhex wrapper crash:shake128_hex/256_hex/sha3_*_hexcalled.hex()on an error tuple returned for invalid parameters →AttributeError. A unified_to_hex()handler was added.- CLI
_write_binary()crash: commands such as KDF/AES/RSA called.hex()directly when the underlying layer returned an error tuple →AttributeError. Now intercepted uniformly at the I/O layer and converted toPPYC_ERR. - CLI
x25519wrong exit code: it printed an error for a wrong private-key length but returned code 0. Now it raisesPPYC_ERR→ exit code 2. - TUI
_hash_menu/_kdf_menucrash: with invalid parameters such asblake2b(digest_size=0)orscrypt(N=15), the TUI raised a bareAttributeError. A unified_raise_if_err()handler was added. - TUI
x25519/rsaunpacking crash: unpacks such asshared, zero = x25519_shared(...)received an error tuple for invalid parameters →ValueError: too many values to unpack. Protection was added. - TUI self-test failure: the XChaCha tamper detection in
_self_test()still expectedDecryptionErrorto be raised, but the new system returns a tuple → the self-test falsely reported "tamper detection not effective". Changed to a tuple assertion.
- Fixed an issue in
rsa.pywhere internal helpers had been mistakenly changed to return tuples, causing caller unpacking failures (choose_hash/mgf1/oaep_encode/oaep_decode/pss_encode/mod_inverse/_jacobireverted to raisingPPYC_ERR, with the public API responsible for converting to tuples). - Fixed
__init__.pynot actually exporting the error-code constants, which madefrom purepycrypto import PPYC_ERR_xxxfail. - Fixed
ALL_ERROR_CODESmistakenly counting the prefix constantPPYC_ERR_PREFIXin the error-code table. - Fixed the single-file merge missing the
Unionimport and the_ppyc_errormodule.
Verification
- Full pytest suite: 126+ passed (including the new
test_errors_edge.py69 cases +test_vectors_strict.py57 cases) - Deep audit: 0 remaining raises other than
PPYC_ERR; 41 error codes with no redundancy and none missing - CLI/TUI full-branch error scenarios: no
Traceback, correct exit codes - All three usage modes (library / CLI / TUI) verified in practice
- The single-file bundle
purepycrypto/single/purepycrypto.pyverified in practice (version 3.1.4)
[2.7.10] - 2026-09-27
Version numbering rule:
v{major}.{feature upgrades}.{bug fixes}In this release the major version rises to 2 (major architecture refactor), with 7 feature upgrades + 10 bug fixes.
⚠️ Breaking Changes
- Command unification: removed the
purepycrypto-argscommand and switched to a single commandpurepycrypto.purepycrypto(no arguments) → launch the interactive TUIpurepycrypto <subcommand> ...(with arguments) → command-line mode
- Entry-behavior change:
purepycrypto:mainnow dispatches automatically based on whether arguments are present (the old formpython -m purepycrypto cli ...is still compatible, but using arguments directly is recommended). - Single-file artifact location change: moved from the project root into the package at
purepycrypto/single/purepycrypto.py; the development-directory root no longer generatespurepycrypto_tui.py/purepycrypto_cli.py/purepycrypto_lib.py.
Added (7 feature upgrades)
- TUI CN/EN language switch (CN / EN, default EN)
- A "Switch Language" item was added to the top-level menu; it takes effect immediately after switching
- Supports the environment variable
PUREPYCRYPTO_LANG=en|cnto override the default language - New
set_language()/get_language()API
sha3_batch(items, algo, n_workers)— batch parallel hashing- Multiprocessing parallelism across multiple independent messages (the SHA-3 sponge cannot split a single long message across blocks)
n_workers=Noneauto-detects the CPU count; small batches automatically degenerate to serial
- AES-GCM-SIV cache switch:
set_cache_enabled(bool)/cache_enabled()/clear_caches()- enabled by default (performance first); can be disabled if the threat model disallows derived keys residing in memory
- AES-GCM-SIV multiprocessing parameter:
n_workers=None(auto-optimal) /1(force serial) - Single-command architecture: one
purepycryptocommand provides both the TUI and the CLI - Single-file bundle:
build_single.py --mode onegeneratespurepycrypto/single/purepycrypto.py(likewise: no arguments = TUI, arguments = command line) - Performance optimization (alternating measurement in the same process, minimum over multiple rounds)
- SHA-3:
keccak_f16001410 → 191 µs/perm (7.4x, SWAR packed integers)sha3_256425 → 838 KB/s (1.97x);hmac_sha3_256277 → 628 KB/s (2.27x) - AES-GCM-SIV: large message auto-multiprocessing 146 → 1101 KB/s (7.5x) 32B small message 1693 → 198 µs (8.5x, POLYVAL table cache + derived-key cache)
- Ed25519:
sign3.52 → 1.79 ms,verify3.89 → 1.95 ms (2.0x each)
- SHA-3:
Fixed (10 bug fixes)
- BLAKE2b: wrong digest when the input length is an integer multiple of 128 bytes (incorrect handling of the final block's
fflag) - Single-file constant conflict:
aes_gcm_siv'sNONCE_LENoverrode the same-named constant inchacha, breaking XChaCha - Single-file entry conflict: the
if __name__ == "__main__"blocks bundled in each module fired first, causing the CLI build to enter the TUI by mistake - AES-GCM-SIV unified entry:
aes_gcm_siv_encrypt/decryptwere missing then_workersparameter (NameError) sha3_batchmultiprocessing result ordering: round-robin sharding caused the output to not correspond to the input (changed to contiguous sharding)sha3_batchWindows spawn crash: child-process re-entry errored when the__main__guard was missing (added a fallback that degenerates to serial)- CLI / TUI crash on GBK consoles:
UnicodeEncodeErrorwhen printing characters such as✓(added console-encoding compatibility) build_singlemistakenly deleted the__main__example inside a docstring: changed to match only top-level indentationbuild_singledeleted thetry/exceptfallback import block incompletely: changed to delete the whole block- Single-file entry
_sysundefined: the--mode oneartifact crashed withNameErroron startup
Changed
- Docs: README / docs (api, cli, quickstart, security, verification) all updated,
clearly stating that Windows multiprocessing must use the
if __name__ == "__main__":guard (with correct/incorrect patterns and workarounds) - New example:
purepycrypto/examples/parallel_usage.pydemonstrates correct multiprocessing usage - pyproject.toml / setup.py: clarified the CLI/TUI installation logic (single console script) and added the
purepycrypto.singlepackage
Verification Conclusion
- Full pytest suite: 103 passed
- Correctness: SHA-3 vs
hashlib(110+ lengths × 3 algorithms), RFC 8452 (48/48), RFC 8032 (TEST 1-3) all pass - All three usage modes verified in practice:
import purepycrypto/purepycrypto <subcommand>/purepycrypto(TUI)
1.1.0 - 2026-09-26
v1.1.0 adds, on top of v1.0.0, the SHA-3/Keccak hash family, Ed25519 signatures, and AES-GCM-SIV (nonce-misuse resistant AEAD), and upgrades the command line into three single-file artifacts: TUI / CLI / pure library.
Added
SHA-3 / Keccak (purepycrypto.sha3, FIPS 202)
sha3_224(data)/sha3_256(data)/sha3_384(data)/sha3_512(data)— SHA-3 fixed-length digests, outputting 28 / 32 / 48 / 64 bytes respectively.shake128(data, outlen)/shake256(data, outlen)— SHAKE XOF extendable output, returning an arbitraryoutlenbytes.hmac_sha3_256(key, message)/hmac_sha3_512(key, message)— HMAC-SHA3, outputting 32 / 64 bytes (the block size is the variant's rater, consistent with OpenSSL/hashlib).- Convenient hex interfaces:
sha3_224_hex/sha3_256_hex/sha3_384_hex/sha3_512_hex/shake128_hex/shake256_hex. - Low-level:
keccak_f1600(state)(24-round Keccak-f[1600]), sponge absorb/squeeze, pad10*1 padding.
Ed25519 (purepycrypto.ed25519, RFC 8032)
ed25519_keygen() -> (seed32, pub32)— generates an Ed25519 key pair (32-byte seed + 32-byte public key).ed25519_publickey(seed32) -> bytes— derives the 32-byte public key from a 32-byte seed.ed25519_sign(message, seed32) -> bytes— generates a 64-byte signature (R || S).ed25519_verify(signature64, message, pub32) -> bool— verifies; invalid input or failed verification always returnsFalse(no exception).- Helper interfaces:
ed25519_scalarmult_base(scalar),ed25519_is_valid_publickey(pub32), exceptionEd25519Error. - Implementation highlights: extended homogeneous coordinates, constant-time masked-lookup 4-bit window scalar multiplication, strict point-encoding rejection rules (y ≥ p, non-square, x=0 sign-bit anomaly).
AES-GCM-SIV (purepycrypto.aes_gcm_siv, RFC 8452)
aes128_gcm_siv_encrypt(key, nonce, plaintext, aad=b"") -> (ct, tag)andaes128_gcm_siv_decrypt(key, nonce, ct, tag, aad=b"") -> bytes.aes256_gcm_siv_encrypt(...)/aes256_gcm_siv_decrypt(...)— AES-256 same-shaped interface.aes_gcm_siv_encrypt(key, nonce, plaintext, aad=b"")/aes_gcm_siv_decrypt(key, nonce, ct, tag, aad=b"")— unified entry dispatched automatically by key length (16 / 32 bytes).- Also provides the public
polyval(h, data)and the constantsTAG_LEN(16),NONCE_LEN(12).
Single-File Packaging (purepycrypto/scripts/build_single.py)
- Added three single-file artifacts:
purepycrypto_tui.py(interactive TUI),purepycrypto_cli.py(command-line mode),purepycrypto_lib.py(pure library). - Added the command-line arguments module
purepycrypto.cli_args, providing the subcommandshash/hmac/kdf/aes/chacha/x25519/rsa/rand/selftest/version.
Package Layout Adjustment
- Moved the three directories
tests/,examples/,scripts/into thepurepycrypto/package, leaving only one top-level package directory in the source tree.
Fixed
- Fixed the defect where BLAKE2b produced a wrong result when the input length is an integer multiple of 128 bytes (final-block length / counter boundary handling).
Changed
build_single.pysupports--mode tui|cli|lib|all, generating the three single-file artifacts individually or all at once (--allgenerates tui + cli + lib together).- The command-line mode is now provided by
purepycrypto.cli_args;python -m purepycryptostill launches the interactive TUI. - Version bumped from
1.0.0to1.1.0.
Notes
- The new modules are all self-tested against standard official vectors: SHA-3 / SHAKE (FIPS 202, cross-verified against
hashlib), Ed25519 (RFC 8032 §7.1), AES-GCM-SIV (RFC 8452 appendix test vectors). - The statement in v1.0.0 that "Ed25519/EdDSA is not included" is void as of v1.1.0: this release provides Ed25519. It still does not include any post-quantum (PQC) algorithm.
1.0.0 - 2026-09-26
The first official release. purepycrypto is a zero-third-party-dependency pure-Python cryptography library
covering hashing, key derivation, symmetric encryption, authenticated encryption, key exchange, and RSA public-key cryptography.
Added
Project Skeleton
- Added the top-level package
purepycrypto, with the public API exported uniformly bypurepycrypto/__init__.py. - Added modules:
common,hash,kdf,aes,chacha,x25519,rsa,der,parallel,cli. - Added package metadata:
__version__,__author__ = "Dvs(DvsXT)",__license__ = "MIT",__version_tuple__.
Hashing (purepycrypto.hash)
sha256(message)— SHA-256 (FIPS 180-4).sha512(message)— SHA-512 (FIPS 180-4).blake2b(data, digest_size=64)— BLAKE2b (RFC 7693), supporting 1–64 byte digests.
Key Derivation and Message Authentication (purepycrypto.kdf)
hmac_sha256(key, message)— HMAC-SHA256 (RFC 2104).hmac_sha512(key, message)— HMAC-SHA512 (RFC 2104).pbkdf2_hmac(password, salt, iterations, dklen, hash_name="sha256")— PBKDF2 (RFC 8018), supporting SHA-256 / SHA-512.hkdf_extract(salt, ikm, hash_name="sha256")— HKDF-Extract (RFC 5869).hkdf_expand(prk, info, length, hash_name="sha256")— HKDF-Expand (RFC 5869).hkdf(ikm, salt=b"", info=b"", length=32, hash_name="sha256")— HKDF one-shot wrapper.scrypt(password, salt, N=4096, r=8, p=1, dklen=32)— scrypt (RFC 7914), including Salsa20/8, BlockMix, and ROMix implementations.argon2id(password, salt, t=1, m=256, p=1, tag_length=32, secret=b"", ad=b"", version=0x13)— Argon2id (RFC 9106), supporting a secret (pepper) and associated data.
Symmetric Encryption (purepycrypto.aes)
AES(key)— AES-128/192/256 (FIPS 197), based on a LibTomCrypt-style T-table implementation.- Block operations:
encrypt_block/decrypt_block. - Operation modes (NIST SP 800-38A):
encrypt_ecb(data)/decrypt_ecb(data)encrypt_cbc(data, iv)/decrypt_cbc(data, iv)encrypt_ctr(data, nonce8)/decrypt_ctr(data, nonce8)encrypt_cfb(data, iv)/decrypt_cfb(data, iv)encrypt_ofb(data, iv)/decrypt_ofb(data, iv)
- GCM (NIST SP 800-38D, AEAD):
gcm_encrypt(nonce12, plaintext, aad=b"") -> (ct, tag)gcm_decrypt(nonce, ct, tag, aad=b"") -> bytes
- ECB / CBC / CTR / GCM support multiprocessing acceleration via the
n_workersparameter.
Authenticated Encryption (purepycrypto.chacha)
poly1305_mac(key32, msg)— Poly1305 one-time authenticator (RFC 8439).chacha20poly1305_encrypt(key, nonce, plaintext, aad=b"")/chacha20poly1305_decrypt(key, nonce, ct_with_tag, aad=b"")— ChaCha20-Poly1305 (RFC 8439).xchacha20poly1305_encrypt(key, nonce, plaintext, aad=b"")/xchacha20poly1305_decrypt(key, nonce, ct_with_tag, aad=b"")— XChaCha20-Poly1305 (192-bit nonce, draft-irtf-cfrg-xchacha).
Key Exchange (purepycrypto.x25519)
x25519(k, u)— X25519 scalar multiplication (RFC 7748).x25519_base(scalar)— scalar multiplication with u=9 as the base point.x25519_shared(priv, peer_pub) -> (shared, is_zero)— shared-secret computation with low-order point (all-zero) detection.x25519_generate_keypair() -> (priv, pub)— generates an X25519 key pair.
RSA Public-Key Cryptography (purepycrypto.rsa)
RSAPublicKey/RSAPrivateKey— RSA key objects, including CRT decryption, Montgomery modular-exponentiation acceleration, blinding, and self-verification.rsa_keygen(bits=2048, parallel=True) -> (RSAPublicKey, RSAPrivateKey)— key generation, using 4 rounds of Miller-Rabin + strong Lucas primality testing (BPSW).rsa_oaep_encrypt(message, pub, label=b"")/rsa_oaep_decrypt(ciphertext, priv, label=b"")— RSA-OAEP (RFC 8017).rsa_pss_sign(message, priv, salt_len=None)/rsa_pss_verify(message, signature, pub, salt_len=None)— RSA-PSS (RFC 8017).- Internal helpers:
extended_gcd,mod_inverse,mgf1,oaep_encode/oaep_decode,pss_encode/pss_verify.
Serialization (purepycrypto.der)
private_key_to_pkcs1_der(priv)/public_key_to_pkcs1_der(pub)— PKCS#1 DER.private_key_to_pkcs8_der(priv)— PKCS#8 private-key DER (RFC 5958).public_key_to_spki_der(pub)— SubjectPublicKeyInfo public-key DER (RFC 5280).private_key_to_pem(priv)/public_key_to_pem(pub)— PEM encoding.parse_private_pem(pem)— parses a PKCS#8 PEM private key intoRSAPrivateKey.
Engineering Utilities (purepycrypto.common / purepycrypto.parallel)
- Constant-time comparison:
_consttime_eq,_consttime_int_eq,_consttime_select. - Secure random:
rand_bytes(n)(based onos.urandom),rand_int(a, b). - Padding utilities:
_pad16,_pad_pkcs7/_unpad_pkcs7. - Constants:
MASK32,MASK64,MASK128,POLY1305_P,GHASH_R,R_CONST. - Exceptions:
CryptoError(base class),DecryptionError(authentication failure). - Multiprocessing acceleration: pool reuse (
_get_pool),SharedMemoryallocation and release, automatic cleanup viaatexit. - Parallel-capability probe flag
_HAS_MP; falls back to serial automatically when unsupported.
Command Line
- Supports
python -m purepycryptoto launch the interactive TUI.
Notes
- This release does not include Ed25519/EdDSA, nor any post-quantum (PQC) algorithm.
rsa_keygenrequiresbits >= 521, with 2048 / 3072 / 4096 recommended.- All core algorithms are self-tested against standard official vectors (FIPS 180-4 / RFC 2104 / RFC 5869 / RFC 6070 / RFC 7914 / RFC 9106 / FIPS 197 / NIST GCM / RFC 8439 / RFC 7748 / RFC 8017).