# Security Statement > **Please read this file in full before using `purepycrypto`.** > > `purepycrypto` is a **pure-Python, zero-dependency** cryptography library, aimed at learning, teaching, experimentation, and embedded prototypes. > It is **not** a cryptography engineering implementation for highly adversarial, long-running, production-critical scenarios. > This document honestly explains its security properties, implementation boundaries, and known limitations. --- ## 1. Positioning Statement Design goals of `purepycrypto`: - **Readable, auditable** — a line-by-line pure-Python implementation, with the algorithm logic fully visible and no black-box binary dependencies; - **Portable** — depends only on the standard library; runs in any environment that can run CPython; - **Correctness first** — strictly follows RFC / FIPS / NIST standards and self-tests against official vectors. `purepycrypto` is **not**: - ❌ an equivalent replacement for `libsodium` / OpenSSL / BoringSSL / `cryptography` (pyca); - ❌ a library that has undergone third-party cryptographic audit, formal verification, or side-channel hardening; - ❌ designed for high-throughput, strongly adversarial scenarios (where holding keys is safer and the attacker has precise timing capability). > **If you need production-grade cryptography, prefer implementations that have been widely deployed and professionally audited** (such as `cryptography`, `libsodium`, or cryptography APIs provided by the operating system). --- ## 2. Randomness Source | Purpose | Source | Description | |---------|--------|-------------| | All random bytes | `os.urandom()` | OS CSPRNG (Windows `BCryptGenRandom` / Linux `getrandom` / macOS `arc4random` backend) | | `rand_bytes(n)` | `os.urandom(n)` | direct wrapper | | `rand_int(a, b)` | `os.urandom` + rejection sampling | avoids modulo bias | | X25519 private key | `os.urandom(32)` | generated by `x25519_generate_keypair` | | RSA prime-factor search | `os.urandom` | random starting point + prime stepping | | OAEP / PSS salt | `os.urandom` | random for each encryption/signature | | RSA blinding factor | `os.urandom` | mitigates timing side channels | **Guarantee**: the library **contains no** PRNG that an attacker can seed, nor any predictable or weak random generator. All randomness comes from the OS CSPRNG. **Responsibility**: callers **must** use cryptographically secure randomness for IV / nonce / salt (preferably `os.urandom` or this library's `rand_bytes`) and **must not** use the `random` module. --- ## 3. Constant-Time Implementation To reduce timing side-channel risk, the following sensitive paths use constant-time code: | Location | Measure | |----------|---------| | Constant-length comparison | `_consttime_eq`: XOR-OR accumulation over all bytes, no early return | | Integer comparison | `_consttime_int_eq`: accumulates differences in 64-bit chunks | | Conditional selection | `_consttime_select`: selects with bitmasks, no branches | | X25519 scalar multiplication | uses a Montgomery ladder + constant-time `cswap`, avoiding secret-dependent `if` | | Ed25519 scalar multiplication | fixed 4-bit window + **masked lookup table** (linear masked selection over 16 entries), 256-round fixed-length main loop, no secret-dependent branches / early exit (best-effort) | | GCM / AEAD tag verification | uses constant-time comparison; authentication failure does not expose the differing position | | RSA private-key operations | uses CRT + Montgomery modular exponentiation and introduces **blinding** | > **Note**: the measures above only mitigate **algorithm-level** timing differences. See [§5 Side Channels and Implementation Risks](#5-side-channels-and-implementation-risks). --- ## 4. Secure-Usage Points for Each Algorithm ### 4.1 Symmetric Encryption - **AES-GCM** (recommended): `nonce` must be 12 bytes and **never repeated under the same key**; `aad` binds context that is not encrypted but needs authentication. Authentication failure raises `DecryptionError`. - **AES-CTR**: `nonce` is 8 bytes; **the counter space must not overlap under the same key**, otherwise keystream reuse causes catastrophic leakage. - **AES-CBC**: `iv` must be random and unpredictable (to prevent IV-prediction attacks under chosen plaintext); a MAC is required to prevent tampering. - **AES-ECB**: does not hide plaintext patterns; **do not use it except for compatibility/deterministic needs**. - **CFB / OFB**: no authentication; if used for encryption, an additional MAC is required. ### 4.2 AEAD (Authenticated Encryption) - **ChaCha20-Poly1305**: 12-byte nonce; **the nonce must never be reused** (one-time keystream). - **XChaCha20-Poly1305**: 24-byte nonce, safe to generate randomly, suitable for scenarios that do not need counter management. - **Poly1305**: `key32` is a one-time key; **never reuse the same Poly1305 key across two messages**. > **Golden rule**: the `(key, nonce)` combination **may be used only once**. For GCM / CTR / ChaCha20-family algorithms, nonce reuse = disaster. > **The only exception**: **AES-GCM-SIV** (RFC 8452) is resistant to nonce misuse, but is still bounded by a repetition limit, see [§4.7](#47-aes-gcm-siv). ### 4.3 Key Derivation - **PBKDF2**: `iterations` recommended ≥ 200000 (SHA-256); new systems should prefer Argon2id. - **HKDF**: used for material expansion of **already high-entropy** keys; **not suitable for passwords**. - **scrypt**: `N`, `r`, `p` determine the memory and time cost; increase them according to hardware capability. - **Argon2id**: the first choice for modern password hashing (RFC 9106). Larger `m` (memory, KiB), `t` (iterations), and `p` (parallelism) are safer, requiring a performance trade-off. ### 4.4 Key Exchange - **X25519**: `x25519_shared` returns `is_zero`. **Must check it**: if `True`, the peer public key is a low-order point and the shared secret is unsafe, so **abort immediately** (RFC 7748 §6.1). - Do not use the negotiated shared secret **directly as a symmetric key**; derive it through HKDF. ### 4.5 RSA - **Key length**: `rsa_keygen` requires `bits >= 521`; **2048 / 3072 / 4096 are recommended**. - **Encryption**: use **OAEP** (`rsa_oaep_encrypt/decrypt`), not raw RSA or PKCS#1 v1.5. - **Signatures**: use **PSS** (`rsa_pss_sign/verify`), not PKCS#1 v1.5. - Encryption and signing are different primitives; **do not mix up padding and purpose**. - The message length for RSA encryption is limited; for large messages, use RSA to wrap a symmetric key (KEM approach) and then encrypt the data with an AEAD. --- ### 4.6 Ed25519 Digital Signatures - **Standard and variant**: `purepycrypto.ed25519` implements **Pure Ed25519** from RFC 8032 (not Ed25519ph / Ed25519ctx). Signatures are a fixed 64 bytes, and both the public key and the private-key seed are 32 bytes. - **Verification semantics**: `ed25519_verify` always **returns `False`** for invalid length, invalid point encoding, `S ≥ L`, etc. (no exception); callers must treat `False` explicitly as a verification failure and must not ignore the return value. - **Constant time**: scalar multiplication uses a fixed 4-bit window + **masked lookup table** (linear masked selection over 16 candidates) and a 256-round fixed-length main loop, striving to eliminate secret-dependent branches and early exits; but **pure Python cannot provide true constant time** (see §5). - **Private-key form**: the private key is a 32-byte random seed; the public key can be re-derived with `ed25519_publickey(seed)`; protect this seed like any other key. - RSA-PSS can still be used when interoperability with an existing RSA ecosystem is needed; new protocols should prefer **Ed25519** (shorter public keys / signatures, no randomness source needed, deterministic signatures). ### 4.7 AES-GCM-SIV - **Positioning**: a nonce-misuse resistant AEAD (RFC 8452). `key` is a key-generating key (16 or 32 bytes), `nonce` is a fixed **12 bytes**, and the tag is a fixed **16 bytes**. - **Nonce-misuse resistance principle**: `(key, nonce)` first derives a per-message authentication-key and encryption-key; the synthesized IV (tag) varies with the plaintext / AAD. Therefore, when `(key, nonce)` repeats, **the keystream is not reused as long as the plaintext or AAD differs**; the attacker can at most tell whether two messages are exactly identical. - **A repetition limit still exists**: GCM-SIV **is not "free to reuse nonces"**. RFC 8452 gives upper bounds on both the **total number of messages encrypted under a single key** and the **number of repetitions of a single nonce**; security degrades beyond them. Unless nonce management is genuinely difficult, still keep **nonces unique**. - **Performance cost**: encryption requires two passes (authenticate first, then encrypt), slower than AES-GCM; suitable for scenarios where nonce consistency is hard to guarantee strictly (e.g. multiple devices sharing a key but generating counters independently). - **Authentication failure**: when the ciphertext / tag / AAD is tampered with, `*_decrypt` raises `DecryptionError` and **never returns unauthenticated plaintext**. --- ## 5. Side Channels and Implementation Risks ⚠️ **A reality that must be recognized**: a pure-Python implementation **cannot guarantee** the following security properties. ### 5.1 Timing and Branch Side Channels Although the core paths use constant-time handling, the Python interpreter itself introduces variability that cannot be fully controlled: - The execution time of **big-integer arithmetic** (RSA, X25519, modular exponentiation) in the underlying implementation (`int`) **depends on the operand values**, so in theory an attacker has room for timing/power/cache side channels; - the timing of **object allocation and garbage collection (GC)** is uncontrollable; - **branch prediction, cache hits, and memory access patterns** are hard to keep constant at the Python level; - the **modular inverse in the form `pow(z2, P-2, P)`** is executed at the end of X25519, and its timing may leak limited information. > Therefore: **do not place this library in a strongly adversarial environment where the attacker can precisely measure timing**. ### 5.2 Memory Residue - Python **has no reliable key-erasure mechanism**. Key objects may remain in heap memory until GC, and may even be paged to disk (swap); - this library **does not provide** `mlock` (memory locking), `memset_s` (secure zeroing), etc.; - when a long-running process handles sensitive keys, memory protection must be considered separately (e.g. using restricted-process / memory-encryption OS mechanisms). ### 5.3 Faults and Exceptions - Authentication failures uniformly raise `DecryptionError` (without distinguishing the cause) to reduce oracle information; - but Python exception tracebacks, string formatting, etc. may still leak internal state (e.g. paths, line numbers). --- ## 6. Known Limitations 1. **Performance**: pure-Python throughput is far below C implementations. Large-file encryption, high-iteration PBKDF2, and large-memory-parameter Argon2id are noticeably slower in Python. 2. **Algorithm scope**: - ✅ includes SHA-3 / SHAKE, Ed25519, AES-GCM-SIV; - ❌ **excludes any post-quantum (PQC) algorithm** (Kyber / Dilithium / Falcon / SPHINCS+, etc.); - signatures may use **Ed25519** (recommended) or **RSA-PSS**; for key exchange, use **X25519**. 3. **PEM support scope**: `parse_private_pem` only parses **PKCS#8 RSA private keys** (label `PRIVATE KEY`); it does not support the legacy PKCS#1 label `RSA PRIVATE KEY`, nor EC / Ed25519, etc. 4. **GCM nonce length**: `gcm_encrypt` uses a 12-byte nonce; CTR uses an 8-byte nonce. Note the length conventions. 5. **Multiprocessing**: `parallel=True` automatically falls back to serial on environments that do not support `multiprocessing` / `SharedMemory`, with no functional impact; however, parallel workers still pass data via standard IPC, so **do not casually place long-term keys in shared memory**. 6. **Minimum RSA size**: `bits < 521` raises `ValueError` directly. 7. **No certificates / no TLS**: this library does not provide X.509 certificates, TLS, protocol handshakes, or other higher-layer facilities; these must be built separately with correct authentication and anti-replay handling. --- ## 7. Prohibitions (Do NOT) - ❌ Do not use this library for **production-critical, highly adversarial** cryptographic systems; - ❌ Do not reuse the nonce of GCM / CTR / ChaCha20 under the **same key**; - ❌ Do not reuse Poly1305's one-time key; - ❌ Do not use the `random` module to generate IV / nonce / salt / keys; - ❌ Do not ignore the `is_zero` returned by `x25519_shared`; - ❌ Do not encrypt structured data with ECB; - ❌ Do not use raw RSA or PKCS#1 v1.5 in place of OAEP / PSS; - ❌ Do not use HKDF for low-entropy passwords (use PBKDF2 / scrypt / Argon2id); - ❌ Do not treat this library as a drop-in replacement for OpenSSL / libsodium. --- ## 8. Recommended Practices (Do) - ✅ Prefer **AEAD**: AES-GCM or ChaCha20-Poly1305 / XChaCha20-Poly1305; - ✅ Generate IV / nonce / salt **randomly each time** (`os.urandom` or `rand_bytes`); - ✅ Derive the key-exchange result through **HKDF** before use; - ✅ Use **Argon2id** for password storage (or scrypt / PBKDF2, with parameters raised according to hardware); - ✅ Verify all AEAD Tags / MACs and treat `DecryptionError` as **authentication failure**, then abort; - ✅ Use **OAEP** for RSA encryption and **PSS** for signatures, with a bit size ≥ 2048; - ✅ New protocols should prefer **Ed25519** signatures (short public keys / short signatures, no randomness-source dependency); use RSA-PSS when RSA-ecosystem compatibility is needed; - ✅ When nonce uniqueness is hard to guarantee (multiple writers / weak randomness source), prefer **AES-GCM-SIV** or **XChaCha20-Poly1305**; - ✅ Validate the length and format of untrusted input to avoid leaking exception information. --- ## 9. Disclaimer ``` THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ``` The author **Dvs(DvsXT)** accepts no liability for any direct or indirect loss caused by the use of this library (including but not limited to data leakage, key leakage, or property loss). --- ## 10. Vulnerability Reporting If you find a security issue, please report it through the project Issues or the author's email `me@dvsyun.top`, and provide as much as possible: - reproduction steps and environment (Python version, operating system); - affected modules and functions; - expected behavior and actual behavior; - if standard vectors are involved, attach the vector source (RFC / NIST number). --- ## 11. Summary in One Sentence > `purepycrypto` is an **honest, readable, auditable pure-Python cryptography toolkit**; > it helps you **correctly understand and experiment with** modern cryptographic primitives, > but **should not** be misused as the security foundation of a highly adversarial production environment. > **For important systems, use mature, professionally audited implementations.**