Release v3.2.0: pure-Python cryptography library (English docs/comments/errors)

- Zero-dependency pure-Python cryptography: SHA-2 / SHA-3 / SHAKE / BLAKE2b,
  HMAC, PBKDF2 / HKDF / scrypt / Argon2id, AES (ECB/CBC/CTR/CFB/OFB/GCM),
  AES-GCM-SIV, ChaCha20-Poly1305 / XChaCha20-Poly1305, X25519, Ed25519,
  RSA (keygen / OAEP / PSS / PEM), ASN.1 DER
- Unified error system: PPYC_ERR fatal exception vs (code, message, suggestion)
  non-fatal 3-tuple return
- Interactive TUI (Chinese / English i18n) + non-interactive CLI
- v3.2.0 adds the encoding, rand and kdf2 modules
- Documentation, code comments and error messages fully in English;
  the interactive TUI keeps its Chinese interface
- Tests: RFC / FIPS / NIST test vectors, 639 passing
This commit is contained in:
dvs
2026-09-27 09:40:12 +08:00
commit 0d69391aa9
78 changed files with 30545 additions and 0 deletions
+1588
View File
File diff suppressed because it is too large Load Diff
+454
View File
@@ -0,0 +1,454 @@
# Command-Line Mode (CLI)
`purepycrypto` provides **two interaction forms**, dispatched automatically based on whether arguments are present; the command-line mode is implemented by
`purepycrypto/cli_args.py`. It **does not enter an interactive session** — one call performs one action — making it suitable for scripts / pipes / CI.
> See [`quickstart.md`](quickstart.md) for the interactive interface, [`api.md`](api.md) for the complete library API,
> and [`errors.md`](errors.md) for the authoritative reference on error codes and exit codes.
---
## 1. Invocation
After installation there is only one command, `purepycrypto`:
```bash
purepycrypto # no arguments -> interactive TUI
purepycrypto <command> [options] # with arguments -> command-line mode
purepycrypto --help # command-line help
purepycrypto version # show version
```
When not installed (inside the source directory), the equivalent is:
```bash
python -m purepycrypto <command> [options]
```
> 💡 The only single-file artifact is the in-package `purepycrypto/single/purepycrypto.py`, with identical behavior:
> no arguments enters the TUI, arguments go to the command line. Example: `python purepycrypto/single/purepycrypto.py hash --text abc --hex`.
>
> The `argparse` `prog` name is `purepycrypto`, so `--help` displays that name.
View help / version:
```bash
purepycrypto --help
purepycrypto version
# purepycrypto 3.2.0
# Python 3.x.y
```
### Exit Codes
| Exit code | Meaning |
|-----------|---------|
| `0` | success |
| `1` | other (e.g. `rsa --op verify` verification FAIL) |
| `2` | `PPYC_ERR` (fatal error, see [`errors.md`](errors.md)) |
| `3` | input file not found (`PPYC_ERR_FILE_NOT_FOUND`) |
| `4` | argument error (`PPYC_ERR_INVALID_*`, etc.) |
### Error Output
The CLI formats both the **non-fatal error tuples** and **fatal `PPYC_ERR`** returned by the library into messages with error codes,
and maps the exit code to `2`. For example:
```bash
$ purepycrypto hash --algo nope --text abc --hex
[✗] PPYC_ERR_INVALID_ALGO: unknown algorithm: nope
Suggestion: available: sha256 / sha512 / blake2b
$ echo $?
2
```
The TUI also handles the end of pipe / redirect input gracefully:
```bash
$ echo "" | purepycrypto
[✗] PPYC_ERR_EOF: 输入流已结束(EOF)
建议: 交互式 TUI 需要终端输入;脚本化请用命令行模式 purepycrypto <子命令>
```
---
## 2. General Conventions
### 2.1 Binary Input
Read in the following **priority order** (the first match wins):
1. `--in FILE`: read from a file;
2. `--text STR`: use the UTF-8 text as input;
3. `--hex-in HEX`: use the hexadecimal string as input (not provided by some commands);
4. standard input (pipe): if none of the above is specified and stdin is not a terminal, read from stdin.
If none of the four is present, it errors:
```
[✗] no input: specify --in / --text / --hex, or provide data through a pipe
```
### 2.2 Binary Output
- `--out FILE`: write to a file (prints `[✓] Wrote xxx (N bytes)`);
- `--hex`: print as hex to stdout;
- `--b64`: print as Base64 to stdout;
- when neither is specified: `hash` / `hmac` / `kdf` default to hex output; the rest try UTF-8 text output and degenerate to hex on failure.
### 2.3 Passing Keys / IV / nonce
For key-type parameters `--xxx`, the convention is a **file path**; `--xxx-hex` is a **hexadecimal string**:
```bash
--key secret.bin # read from a file
--key-hex 00112233aabbcc # give hex directly (may include a 0x prefix or spaces)
```
---
## 3. Subcommands
Command list:
| Command | Purpose |
|---------|---------|
| [`hash`](#31-hash) | compute a hash (sha256 / sha512 / blake2b) |
| [`hmac`](#32-hmac) | compute an HMAC (sha256 / sha512) |
| [`kdf`](#33-kdf) | key derivation (pbkdf2 / hkdf / scrypt / argon2id) |
| [`aes`](#34-aes) | AES encryption/decryption (ecb / cbc / ctr / cfb / ofb / gcm) |
| [`chacha`](#35-chacha) | (X)ChaCha20-Poly1305 encryption/decryption |
| [`x25519`](#36-x25519) | X25519 key generation / shared secret |
| [`rsa`](#37-rsa) | RSA key generation / OAEP / PSS / PEM conversion |
| [`rand`](#38-rand) | generate random bytes |
| [`selftest`](#39-selftest) | run the built-in self-test |
| [`version`](#310-version) | show the version |
> ⚠️ The command-line interface **covers only the core algorithms** (hashing / HMAC / KDF / AES / ChaCha / X25519 / RSA / rand).
> **SHA-3 / SHAKE, Ed25519, AES-GCM-SIV** are currently called through the Python API, see [`api.md`](api.md).
---
### 3.1 `hash`
Compute a hash.
| Option | Default | Values | Description |
|--------|---------|--------|-------------|
| `--algo` | `sha256` | `sha256` / `sha512` / `blake2b` | hash algorithm |
| `--digest-size` | `64` | 1–64 | BLAKE2b digest length (bytes) |
| `--in` / `--text` / `--hex-in` | — | | input |
| `--out` / `--hex` / `--b64` | — | | output |
```bash
# pipe input
echo -n abc | purepycrypto hash --algo sha256 --hex
# ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad
# text input
purepycrypto hash --algo sha256 --text abc --hex
# file hash -> file
purepycrypto hash --algo sha512 --in data.bin --out digest.hex --hex
# BLAKE2b 32-byte digest
purepycrypto hash --algo blake2b --digest-size 32 --text abc --hex
```
---
### 3.2 `hmac`
Compute an HMAC.
| Option | Default | Values | Description |
|--------|---------|--------|-------------|
| `--algo` | `sha256` | `sha256` / `sha512` | underlying hash |
| `--key` / `--key-hex` | — | | HMAC key (required) |
| `--in` / `--text` / `--hex-in` | — | | input |
| `--out` / `--hex` / `--b64` | — | | output |
```bash
echo -n "Hi There" | purepycrypto hmac \
--algo sha256 --key-hex 0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b --hex
```
---
### 3.3 `kdf`
Key derivation.
| Option | Default | Description |
|--------|---------|-------------|
| `--algo` | `pbkdf2` | `pbkdf2` / `hkdf` / `scrypt` / `argon2id` |
| `--length` | `32` | output length (bytes) |
| `--hash-name` | `sha256` | `sha256` / `sha512` (PBKDF2 / HKDF) |
| `--iterations` | `100000` | PBKDF2 iteration count |
| `--n` | `16384` | scrypt `N` (a power of 2) |
| `--r` | `8` | scrypt `r` |
| `--p` | `1` | scrypt `p` / Argon2 parallelism |
| `--t` | `3` | Argon2 time cost |
| `--m` | `65536` | Argon2 memory cost (KiB) |
| `--info` / `--info-hex` | — | HKDF `info` (text / hex) |
| `--password` / `--password-hex` | — | password / input key material (required) |
| `--salt` / `--salt-hex` | — | salt |
| `--out` / `--hex` / `--b64` | — | output |
```bash
# PBKDF2
purepycrypto kdf --algo pbkdf2 --iterations 200000 --length 32 \
--password-hex 70617373776f7264 --salt-hex 73616c74 --hex
# HKDF
purepycrypto kdf --algo hkdf --length 32 \
--password-hex 6d6173746572 --info encryption --hex
# scrypt
purepycrypto kdf --algo scrypt --n 16384 --r 8 --p 1 --length 32 \
--password-hex 70617373 --salt-hex 4e61436c --hex
# Argon2id
purepycrypto kdf --algo argon2id --t 3 --m 65536 --p 4 --length 32 \
--password-hex 70617373 --salt-hex 00ff00ff00ff00ff00ff00ff00ff00ff --hex
```
> The password and salt can be given directly via `--password-hex` / `--salt-hex`, or read from a file via `--password FILE` / `--salt FILE`.
> Invalid parameters (e.g. `scrypt --n 15`) return `PPYC_ERR_INVALID_KDF_PARAM` with exit code `4`.
---
### 3.4 `aes`
AES encryption/decryption.
| Option | Default | Values | Description |
|--------|---------|--------|-------------|
| `--mode` | `gcm` | `ecb` / `cbc` / `ctr` / `cfb` / `ofb` / `gcm` | operation mode |
| `--op` | `enc` | `enc` / `dec` | encrypt / decrypt |
| `--key` / `--key-hex` | — | | key (16 / 24 / 32 bytes, required) |
| `--iv` / `--iv-hex` | — | | IV (CBC / CFB / OFB, 16 bytes) |
| `--nonce` / `--nonce-hex` | — | | nonce (GCM 12 bytes / CTR 8 bytes) |
| `--aad` / `--aad-hex` | — | | GCM additional authenticated data |
| `--tag-out` | — | | GCM encryption: write the 16-byte tag to a file separately |
| `--tag-file` | — | | GCM decryption: read the tag from a file |
| `--in` / `--text` / `--hex-in` | — | | input |
| `--out` / `--hex` / `--b64` | — | | output |
**GCM conventions**: when encrypting, if `--tag-out` is not used, the output is `ciphertext || tag` (the 16-byte tag appended at the end);
when decrypting, you can pass `ciphertext || tag` directly as input (the last 16 bytes are split off automatically), or give the tag separately via `--tag-file`.
On authentication failure (tag mismatch) it returns `PPYC_ERR_AUTH_FAILED`.
```bash
# AES-256-GCM encrypt a file (output ciphertext||tag)
purepycrypto aes --mode gcm --op enc --in plain.txt --out cipher.bin \
--key-hex 000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f \
--nonce-hex 000102030405060708090a0b
# decryption
purepycrypto aes --mode gcm --op dec --in cipher.bin --out plain.txt \
--key-hex 000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f \
--nonce-hex 000102030405060708090a0b
# AES-128-CBC
purepycrypto aes --mode cbc --op enc --text "secret" --hex \
--key-hex 000102030405060708090a0b0c0d0e0f \
--iv-hex 101112131415161718191a1b1c1d1e1f
```
---
### 3.5 `chacha`
(X)ChaCha20-Poly1305 encryption/decryption.
| Option | Default | Description |
|--------|---------|-------------|
| `--op` | `enc` | `enc` / `dec` |
| `--xchacha` | disabled | enable XChaCha20-Poly1305 (24-byte nonce) |
| `--key` / `--key-hex` | — | 32-byte key (required) |
| `--nonce` / `--nonce-hex` | — | 12 bytes (ChaCha) or 24 bytes (XChaCha) |
| `--aad` / `--aad-hex` | — | additional authenticated data |
| `--in` / `--text` / `--hex-in` | — | input |
| `--out` / `--hex` / `--b64` | — | output |
```bash
# ChaCha20-Poly1305 encryption (output ciphertext||tag)
purepycrypto chacha --op enc --text "secret" --out c.bin \
--key-hex <64 hex chars> --nonce-hex <24 hex chars>
# XChaCha20-Poly1305 decryption
purepycrypto chacha --op dec --xchacha --in c.bin --hex \
--key-hex <64 hex chars> --nonce-hex <48 hex chars>
```
---
### 3.6 `x25519`
X25519 key generation / shared secret.
| Option | Default | Description |
|--------|---------|-------------|
| `--op` | `keygen` | `keygen` / `base` / `shared` |
| `--priv` / `--priv-hex` | — | private key (32 bytes) |
| `--peer-pub` / `--peer-pub-hex` | — | peer public key (32 bytes) |
| `--out` | — | `keygen` outputs JSON; `shared` outputs the raw 32 bytes |
- `keygen`: generate a key pair; without `--out` it prints `private_key = ...` / `public_key = ...`; with `--out` it writes
`{"private": "...", "public": "..."}` (JSON).
- `base`: compute the public key from the private key (prints hex).
- `shared`: compute the shared secret from your own private key and the peer's public key (prints hex or writes to `--out`); **if the result is all zeros it warns on stderr**.
```bash
# generate a key pair (write JSON)
purepycrypto x25519 --op keygen --out alice.json
# derive the public key from the private key
purepycrypto x25519 --op base --priv-hex <64 hex chars>
# compute the shared secret
purepycrypto x25519 --op shared --priv-hex <64 hex chars> --peer-pub-hex <64 hex chars>
```
> An all-zero shared secret means the peer public key is a low-order point and you should **abort immediately** (RFC 7748 §6.1).
---
### 3.7 `rsa`
RSA key generation / OAEP / PSS / PEM conversion.
| Option | Default | Description |
|--------|---------|-------------|
| `--op` | `keygen` | `keygen` / `oaep-enc` / `oaep-dec` / `sign` / `verify` / `pem-to-der` |
| `--bits` | `2048` | key size in bits (≥ 521, recommended 2048 / 3072 / 4096) |
| `--no-parallel` | disabled | disable multiprocessing prime search |
| `--priv-pem FILE` | — | private key PEM (PKCS#8) |
| `--pub-pem FILE` | — | public key PEM (SPKI) |
| `--priv-out FILE` / `--pub-out FILE` | — | `keygen` output path |
| `--label` / `--label-hex` | — | OAEP label |
| `--sig` / `--sig-hex` | — | PSS signature (`--sig-file` is an equivalent alias) |
| `--in` / `--text` / `--hex-in` | — | input |
| `--out` / `--hex` / `--b64` | — | output |
- `keygen`: generate a key pair; `--priv-out` / `--pub-out` specify the write paths, otherwise the private-key PEM is printed to stdout.
- `oaep-enc`: requires `--pub-pem` (or `--priv-pem` to extract the public key from).
- `oaep-dec` / `sign` / `pem-to-der`: require `--priv-pem`.
- `verify`: requires `--pub-pem` (or `--priv-pem`) and `--sig` / `--sig-hex`; prints `VERIFY: OK` / `VERIFY: FAIL` with exit code `0` / `1`.
- `pem-to-der`: convert a PKCS#8 private key to DER output.
```bash
# generate a 2048-bit key pair
purepycrypto rsa --op keygen --bits 2048 --priv-out priv.pem --pub-out pub.pem
# OAEP encrypt / decrypt
purepycrypto rsa --op oaep-enc --pub-pem pub.pem --text "secret" --out enc.bin
purepycrypto rsa --op oaep-dec --priv-pem priv.pem --in enc.bin --out dec.txt
# PSS sign / verify
purepycrypto rsa --op sign --priv-pem priv.pem --in doc.bin --out doc.sig
purepycrypto rsa --op verify --pub-pem pub.pem --in doc.bin --sig-file doc.sig
# VERIFY: OK
# PEM -> DER
purepycrypto rsa --op pem-to-der --priv-pem priv.pem --out priv.der
```
---
### 3.8 `rand`
Generate random bytes.
| Parameter / Option | Default | Description |
|--------------------|---------|-------------|
| `length` (positional) | `32` | number of bytes |
| `--alnum` | disabled | generate a random alphanumeric string (instead of raw bytes) |
| `--out FILE` | — | output file |
| `--hex` | — | output as hex |
| `--b64` | — | output as Base64 |
```bash
purepycrypto rand 32 --hex
purepycrypto rand 24 --b64
purepycrypto rand 16 --alnum
purepycrypto rand 32 --out key.bin
```
> The randomness source is `os.urandom` (the OS CSPRNG).
---
### 3.9 `selftest`
Run the built-in self-test (covering standard vectors for SHA-2 / BLAKE2b / Argon2id / PBKDF2 / scrypt / HKDF / AES / GCM / ChaCha / X25519 / RSA / PEM, etc.), printing `all self-tests passed` when everything passes.
```bash
purepycrypto selftest
```
---
### 3.10 `version`
Show version information.
```bash
purepycrypto version
# purepycrypto 3.2.0
# Python 3.x.y
```
---
## 4. Piped Usage
The CLI naturally supports Unix pipes: when no input is specified it reads stdin, and its output can be consumed directly downstream.
```bash
# 1) compute the file's SHA-256 (hex)
cat data.bin | purepycrypto hash --algo sha256 --hex
# 2) encrypt piped data directly (ciphertext file)
printf 'secret' | purepycrypto aes --mode gcm --op enc \
--out cipher.bin --key-hex <key> --nonce-hex <nonce>
# 3) generate a random key -> save it
purepycrypto rand 32 --hex > key.hex
# 4) chained: derive a key -> HMAC
purepycrypto kdf --algo hkdf --length 32 \
--password-hex 6d6173746572 --hex | \
purepycrypto hmac --algo sha256 --key-hex "$(...)" ...
```
> Tip: pass keys / nonce via `--key-hex` / `--nonce-hex` or a file; **do not** write keys in plaintext into the shell history.
---
## ⚠️ Windows Multiprocessing Notes (Important)
Any API that triggers multiprocessing (`sha3_batch`, large-input `aes*gcm_siv*`, `rsa_keygen(parallel=True)`)
**must be wrapped by the caller script in `if __name__ == "__main__":` on Windows**,
otherwise it reports `RuntimeError: ... before the current process has finished its bootstrapping phase`.
```python
# my_script.py
from purepycrypto import sha3_batch, aes256_gcm_siv_encrypt
def main():
digests = sha3_batch([b"a", b"b"], "sha3_256", n_workers=4)
ct, tag = aes256_gcm_siv_encrypt(key, nonce, big_data)
if __name__ == "__main__": # <- mandatory on Windows
main()
```
- `sha3_batch` has a built-in fallback: if multiprocessing fails to start it degenerates to serial automatically, without crashing (but loses the speedup).
- `rsa_keygen` can be forced to serial with `--no-parallel` (CLI) / `parallel=False` (library).
- If you do not need the parallel speedup, explicitly passing `n_workers=1` completely avoids the issue.
---
*See [`errors.md`](errors.md) for the complete error-code reference.*
+266
View File
@@ -0,0 +1,266 @@
# Error System Manual (PPYC_ERR)
> As of purepycrypto v3.2.0, the library uses a **unified error system**.
> This document is the authoritative reference for error codes and handling.
---
## 1. Design Principles
The library strictly divides errors into two categories, semantically clear and never mixed:
| Type | Handling | Applicable scenarios |
|------|----------|----------------------|
| **Fatal error** | **Raise `PPYC_ERR`** | The program can no longer run safely: internal invariant broken (library bug), fatal environment problem, unable to construct an object during initialization |
| **Non-fatal error** | **Return a 3-tuple** `(error_code, error_message, suggestion)` | Expected failures: invalid input, failed validation, authentication failure, missing file, parse failure |
**Core idea**: expected failures **should not** be expressed with exceptions — the caller can handle them gracefully by checking the return value;
whereas a genuine crash should let the exception bubble up to expose the problem.
---
## 2. Fatal Error: `PPYC_ERR`
```python
from purepycrypto import PPYC_ERR, PPYC_ERR_INTERNAL
try:
...
except PPYC_ERR as e:
print(e.code) # 'PPYC_ERR_INTERNAL'
print(e.message) # human-readable reason
print(e.suggestion) # human-readable fix suggestion
print(str(e)) # '[PPYC_ERR_INTERNAL] reason Suggestion: ...'
```
### Construction
```python
raise PPYC_ERR(code, message, suggestion="")
# or the convenience function
from purepycrypto import raise_ppyc
raise_ppyc(PPYC_ERR_INTERNAL, "state machine inconsistent", "please file an issue")
```
### Attributes
| Attribute | Type | Description |
|-----------|------|-------------|
| `code` | `str` | error code, in the form `PPYC_ERR_xxx` |
| `message` | `str` | reason description |
| `suggestion` | `str` | fix suggestion (may be empty) |
| `as_tuple()` | method | returns `(code, message, suggestion)` |
### Legacy Exception Name Compatibility
The following historical exception names remain available; all are **subclasses** of `PPYC_ERR` and carry `code/message/suggestion`:
| Legacy name | Default code |
|-------------|--------------|
| `CryptoError` | `PPYC_ERR_INTERNAL` |
| `DecryptionError` | `PPYC_ERR_AUTH_FAILED` |
| `Ed25519Error` | `PPYC_ERR_INVALID_ARG` |
| `PPYCError` | (alias of `PPYC_ERR`) |
---
## 3. Non-Fatal Errors: 3-Tuple Return
```python
from purepycrypto import err, ok, is_ok, is_err, OK_TUPLE
# error
return err(PPYC_ERR_INVALID_KEY_LEN, "AES key must be 16/24/32 bytes", "pass a correct length")
# -> ('PPYC_ERR_INVALID_KEY_LEN', 'AES key must be 16/24/32 bytes', 'pass a correct length')
# success (validation-style API)
return OK_TUPLE # (None, None, None)
```
### Caller Checks
```python
result = some_api(...)
# method 1: generic check (works for any API)
if is_err(result):
code, msg, hint = result
print(code, msg, hint)
# method 2: using aes.gcm_decrypt as an example (returns plaintext bytes on success, a tuple on failure)
out = aes.gcm_decrypt(nonce, ct, tag, aad)
if isinstance(out, tuple) and out[0] is not None:
code, msg, hint = out
... # handle the error
else:
plaintext = out
```
### Helper Functions
| Function | Description |
|----------|-------------|
| `err(code, message, suggestion="")` | construct an error tuple (validates the `PPYC_ERR_` prefix) |
| `ok(value)` | semantically marks "success"; equivalent to returning `value` directly |
| `OK_TUPLE` | `(None, None, None)`, the success return of validation-style APIs |
| `is_ok(result)` | determines success (`None` or `(None,None,None)` or an ordinary value) |
| `is_err(result)` | determines whether it is an error tuple (`(PPYC_ERR_xxx, msg, hint)`) |
| `PPYCResult` | type alias `Tuple[Optional[str], Optional[str], Optional[str]]` |
---
## 4. Complete Error-Code Table
Import methods:
```python
from purepycrypto import PPYC_ERR_INVALID_KEY_LEN # import a single one directly
from purepycrypto import ALL_ERROR_CODES # all (tuple)
```
### 4.1 General
| Error code | Meaning |
|------------|---------|
| `PPYC_ERR_UNKNOWN` | uncategorized error |
| `PPYC_ERR_INTERNAL` | internal inconsistency (should raise `PPYC_ERR`) |
| `PPYC_ERR_UNSUPPORTED` | unsupported feature / value |
| `PPYC_ERR_NOT_IMPLEMENTED` | not yet implemented |
### 4.2 Argument Validation
| Error code | Meaning |
|------------|---------|
| `PPYC_ERR_INVALID_ARG` | invalid argument (general) |
| `PPYC_ERR_INVALID_TYPE` | invalid type (e.g. not bytes) |
| `PPYC_ERR_INVALID_LENGTH` | invalid length (general) |
| `PPYC_ERR_INVALID_HEX` | invalid hexadecimal format |
| `PPYC_ERR_OUT_OF_RANGE` | value out of range |
| `PPYC_ERR_MESSAGE_TOO_LONG` | message too long (exceeds the encoding limit) |
| `PPYC_ERR_INPUT_TOO_LARGE` | input exceeds the algorithm limit |
### 4.3 Key / nonce / IV
| Error code | Meaning |
|------------|---------|
| `PPYC_ERR_INVALID_KEY` | invalid key (general) |
| `PPYC_ERR_INVALID_KEY_LEN` | invalid key length |
| `PPYC_ERR_INVALID_NONCE` | invalid nonce |
| `PPYC_ERR_INVALID_NONCE_LEN` | invalid nonce length |
| `PPYC_ERR_INVALID_IV` | invalid IV |
| `PPYC_ERR_INVALID_IV_LEN` | invalid IV length |
| `PPYC_ERR_INVALID_SALT` | invalid salt |
### 4.4 Authentication / Decryption
| Error code | Meaning |
|------------|---------|
| `PPYC_ERR_AUTH_FAILED` | authentication failure (AEAD tag / signature verification fails) |
| `PPYC_ERR_DECRYPT_FAILED` | decryption failure |
| `PPYC_ERR_INVALID_PADDING` | invalid padding (PKCS#7 etc.) |
| `PPYC_ERR_INVALID_SIGNATURE` | invalid signature / verification fails |
| `PPYC_ERR_INVALID_TAG` | invalid authentication tag |
### 4.5 Encoding / Parsing
| Error code | Meaning |
|------------|---------|
| `PPYC_ERR_INVALID_ENCODING` | invalid encoding format (DER / PEM) |
| `PPYC_ERR_PARSE_FAILED` | parse failure |
| `PPYC_ERR_INVALID_POINT` | invalid curve point (decoding / low order) |
| `PPYC_ERR_INVALID_KEY_MATERIAL` | invalid key material |
### 4.6 File / IO
| Error code | Meaning |
|------------|---------|
| `PPYC_ERR_FILE_NOT_FOUND` | file not found |
| `PPYC_ERR_IO` | read/write failure |
| `PPYC_ERR_PERMISSION` | insufficient permission |
### 4.7 Environment / Dependencies
| Error code | Meaning |
|------------|---------|
| `PPYC_ERR_NO_MULTIPROCESS` | multiprocessing unavailable |
| `PPYC_ERR_ENV` | runtime environment problem |
### 4.8 Algorithm / Parameter Domain
| Error code | Meaning |
|------------|---------|
| `PPYC_ERR_INVALID_PARAM` | invalid algorithm parameter |
| `PPYC_ERR_INVALID_KDF_PARAM` | invalid KDF parameter (t/m/p/N/r/iterations/dklen) |
| `PPYC_ERR_INVALID_RSA_BITS` | invalid RSA bit size |
| `PPYC_ERR_INVALID_ALGO` | invalid algorithm name |
| `PPYC_ERR_INVALID_MODE` | invalid mode (ECB/CBC/GCM…) |
| `PPYC_ERR_INVALID_OPERATION` | invalid operation (enc/dec…) |
### 4.9 CLI / TUI
| Error code | Meaning |
|------------|---------|
| `PPYC_ERR_CLI_USAGE` | command-line usage error |
| `PPYC_ERR_CLI_INPUT` | invalid interactive input |
| `PPYC_ERR_EOF` | input stream ended (pipe / redirect) |
---
## 5. Real Examples
### 5.1 Library Call (checking the return value)
```python
from purepycrypto import AES, is_err, PPYC_ERR_AUTH_FAILED
aes = AES(key)
result = aes.gcm_encrypt(nonce, plaintext, aad)
if is_err(result):
print("encryption parameter error:", result)
else:
ct, tag = result
```
### 5.2 Command Line (automatic exit-code mapping)
```bash
$ purepycrypto hash --algo nope --text abc --hex
[✗] PPYC_ERR_INVALID_ALGO: unknown algorithm: nope
Suggestion: available: sha256 / sha512 / blake2b
$ echo $? # 2 (PPYC_ERR uniformly returns 2)
```
CLI exit code conventions:
| Exit code | Meaning |
|-----------|---------|
| `0` | success |
| `1` | other (e.g. argparse usage error, verification FAIL) |
| `2` | `PPYC_ERR` (fatal error) |
| `3` | file not found |
| `4` | argument error (ValueError / TypeError) |
### 5.3 TUI (graceful EOF handling)
```bash
$ echo "" | purepycrypto
...
Select >
[✗] PPYC_ERR_EOF: 输入流已结束(EOF)
建议: 交互式 TUI 需要终端输入;脚本化请用命令行模式 purepycrypto <子命令>
```
---
## 6. Authoring Conventions (for contributors)
1. **Single source of error definitions**: the library defines error codes and exception classes only in `purepycrypto/_ppyc_error.py`;
all other modules use `from ._ppyc_error import ...` and must not invent error-code string literals.
2. **Error-code prefix enforced**: `err()` validates the `PPYC_ERR_` prefix and raises `PPYC_ERR` if it does not match.
3. **docstrings must have a "Returns" section**: describe the normal return value, as well as the 3-tuple on error and the possible error codes.
4. **`raise ValueError` must not be used**: for parameter validation use `return err(...)`; for internal contradictions use `raise PPYC_ERR(...)`.
5. **Authentication failures go through tuples**: AEAD tag verification and signature verification failures → `return err(PPYC_ERR_AUTH_FAILED, ...)`.
---
*This manual is released together with `purepycrypto`. Error-code constants are in `purepycrypto/_ppyc_error.py`.*
+466
View File
@@ -0,0 +1,466 @@
# Quick Start
This tutorial takes you from scratch to the common features of `purepycrypto` in 5 minutes.
All examples are based on the `purepycrypto v3.2.0` public API and can be copied and run directly (Python >= 3.8).
> See [`api.md`](api.md) for the complete API, [`cli.md`](cli.md) for the command line, [`security.md`](security.md) for security, and [`errors.md`](errors.md) for error codes.
---
## 0. Installation
```bash
pip install purepycrypto
```
Verify the installation:
```bash
python -c "import purepycrypto; print(purepycrypto.__version__)"
# 3.2.0
```
`purepycrypto` has zero third-party dependencies and uses only the Python standard library; no compilation is required.
---
## 1. First Program: Hashing
```python
from purepycrypto import sha256
print(sha256(b"abc").hex())
# ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad
```
`sha256` / `sha512` take `bytes` and return a fixed-length `bytes` digest.
`blake2b` supports a custom digest length:
```python
from purepycrypto import sha512, blake2b
print(len(sha512(b"abc"))) # 64
print(len(blake2b(b"abc"))) # 64 (default)
print(len(blake2b(b"abc", 32))) # 32
```
**Key point**: hash function input must be `bytes`; for strings, call `.encode("utf-8")` first.
---
## 2. Password -> Key: KDF
### 2.1 PBKDF2
```python
from purepycrypto import pbkdf2_hmac
import os
salt = os.urandom(16) # a unique salt per password, must be stored with the ciphertext
key = pbkdf2_hmac(
password=b"correct horse battery staple",
salt=salt,
iterations=200_000, # recommended >= 200k
dklen=32,
hash_name="sha256", # or "sha512"
)
```
### 2.2 scrypt
```python
from purepycrypto import scrypt
key = scrypt(b"password", b"NaCl", N=2**14, r=8, p=1, dklen=32)
```
- `N` must be a **power of 2 and > 1**;
- `r`, `p` must be **>= 1**.
### 2.3 Argon2id (recommended for new systems)
```python
from purepycrypto import argon2id
import os
tag = argon2id(
password=b"password",
salt=os.urandom(16), # 16 bytes or more
t=3, # number of iterations
m=65536, # memory cost (KiB), = 64 MiB
p=4, # parallelism
tag_length=32,
)
```
### 2.4 HKDF (derive multiple subkeys from an existing high-entropy key)
```python
from purepycrypto import hkdf
master = bytes(32)
enc_key = hkdf(master, salt=b"", info=b"encryption", length=32)
mac_key = hkdf(master, salt=b"", info=b"authentication", length=32)
print(enc_key != mac_key) # True: different info derives different subkeys
```
---
## 3. Symmetric Encryption: AES
```python
from purepycrypto import AES
import os
key = os.urandom(32) # 32 bytes -> AES-256
aes = AES(key)
```
### 3.1 GCM (recommended, with built-in authentication)
```python
nonce = os.urandom(12) # 96-bit nonce
ct, tag = aes.gcm_encrypt(nonce, b"top secret", aad=b"v1")
pt = aes.gcm_decrypt(nonce, ct, tag, aad=b"v1")
assert pt == b"top secret"
```
> As of v3.2.0, GCM authentication failure **returns an error tuple** `(PPYC_ERR_AUTH_FAILED, msg, hint)` instead of raising;
> check with `is_err()` (see [§10 Error Handling Overview](#10-error-handling-overview)).
### 3.2 CBC / CTR
```python
iv = os.urandom(16)
ct = aes.encrypt_cbc(b"data", iv)
assert aes.decrypt_cbc(ct, iv) == b"data"
nonce8 = os.urandom(8)
ct = aes.encrypt_ctr(b"data", nonce8)
assert aes.decrypt_ctr(ct, nonce8) == b"data"
```
> ⚠️ **Nonce / IV must never be repeated under the same key**. CBC's IV should be random and unpredictable; the GCM / CTR nonce must be **unique**.
---
## 4. Authenticated Encryption: ChaCha20-Poly1305
When AES hardware acceleration is unavailable or an efficient software implementation is needed, ChaCha20-Poly1305 is a good choice:
```python
from purepycrypto import chacha20poly1305_encrypt, chacha20poly1305_decrypt
import os
key = os.urandom(32)
nonce = os.urandom(12) # 96-bit nonce
blob = chacha20poly1305_encrypt(key, nonce, b"message", aad=b"metadata")
pt = chacha20poly1305_decrypt(key, nonce, blob, aad=b"metadata")
assert pt == b"message"
# on authentication failure chacha20poly1305_decrypt returns an error tuple (PPYC_ERR_AUTH_FAILED); check with is_err
```
### XChaCha20-Poly1305 (192-bit nonce, safe to generate randomly)
```python
from purepycrypto import xchacha20poly1305_encrypt, xchacha20poly1305_decrypt
import os
key = os.urandom(32)
nonce = os.urandom(24) # 192-bit nonce
blob = xchacha20poly1305_encrypt(key, nonce, b"message", aad=b"metadata")
pt = xchacha20poly1305_decrypt(key, nonce, blob, aad=b"metadata")
assert pt == b"message"
```
---
## 5. Key Exchange: X25519
```python
from purepycrypto import x25519_generate_keypair, x25519_shared
# Alice
priv_a, pub_a = x25519_generate_keypair()
# Bob
priv_b, pub_b = x25519_generate_keypair()
# after exchanging public keys, each computes the shared secret
shared_a, zero_a = x25519_shared(priv_a, pub_b)
shared_b, zero_b = x25519_shared(priv_b, pub_a)
assert shared_a == shared_b
assert not zero_a and not zero_b # must check for the zero value
```
**Full flow**: X25519 negotiates a shared secret -> derive a symmetric key with HKDF -> encrypt data with AES-GCM or ChaCha20-Poly1305.
```python
from purepycrypto import hkdf
sym_key = hkdf(shared_a, info=b"handshake", length=32)
```
---
## 6. Public-Key Encryption and Signing: RSA
```python
from purepycrypto import (
rsa_keygen, rsa_oaep_encrypt, rsa_oaep_decrypt,
rsa_pss_sign, rsa_pss_verify,
)
pub, priv = rsa_keygen(bits=2048) # the first generation may take a few seconds
# encryption
ct = rsa_oaep_encrypt(b"secret", pub)
pt = rsa_oaep_decrypt(ct, priv)
assert pt == b"secret"
# signing
sig = rsa_pss_sign(b"document", priv)
assert rsa_pss_verify(b"document", sig, pub) is True
assert rsa_pss_verify(b"tampered", sig, pub) is False
```
---
## 7. Saving and Loading Keys: PEM / DER
```python
from purepycrypto import (
rsa_keygen, private_key_to_pem, public_key_to_pem, parse_private_pem,
)
pub, priv = rsa_keygen(2048)
pem = private_key_to_pem(priv) # returns str (PKCS#8 / PRIVATE KEY)
with open("key.pem", "w", encoding="ascii") as f:
f.write(pem)
# reload
with open("key.pem", encoding="ascii") as f:
priv2 = parse_private_pem(f.read())
assert priv2.n == priv.n
```
---
## 8. Full Example: Password-Based File Encryption
Below, KDF + AEAD are combined to implement "encrypt a piece of data with a password":
```python
from purepycrypto import pbkdf2_hmac, chacha20poly1305_encrypt, chacha20poly1305_decrypt
import os
def encrypt_with_password(password: bytes, data: bytes) -> bytes:
salt = os.urandom(16)
nonce = os.urandom(12)
key = pbkdf2_hmac(password, salt, iterations=200_000, dklen=32)
blob = chacha20poly1305_encrypt(key, nonce, data)
return salt + nonce + blob # concatenate the header info (in practice, store a version number, etc.)
def decrypt_with_password(password: bytes, packed: bytes) -> bytes:
salt, nonce, blob = packed[:16], packed[16:28], packed[28:]
key = pbkdf2_hmac(password, salt, iterations=200_000, dklen=32)
return chacha20poly1305_decrypt(key, nonce, blob)
packed = encrypt_with_password(b"hunter2", b"confidential payload")
assert decrypt_with_password(b"hunter2", packed) == b"confidential payload"
```
> **Best practice**: `salt`, `nonce`, and `tag` must be stored together with the ciphertext; when the password is wrong or the data is tampered with, `chacha20poly1305_decrypt` raises `DecryptionError`.
---
## 9. Advanced Algorithms Overview (SHA-3 / Ed25519 / AES-GCM-SIV)
All three modules can be used directly with zero dependencies (they can be imported from their own submodules and are also merged into the top-level exports).
### 9.1 SHA-3 / SHAKE (`purepycrypto.sha3`, FIPS 202)
```python
from purepycrypto.sha3 import sha3_256, sha3_512, shake128, hmac_sha3_256
sha3_256(b"abc").hex()
# 3a985da74fe225b2045c172d6bd390bd855f086e3e9d525b46bfe24511431532
sha3_512(b"abc").hex() # 64 bytes
shake128(b"abc", 32).hex() # XOF: outputs an arbitrary outlen bytes
# 5881092dd818bf5cf8a3ddb793fbcba74097d5c526a6d35f97b83351940f2cc8
hmac_sha3_256(b"key", b"message") # HMAC-SHA3, 32 bytes
```
- `sha3_224 / sha3_256 / sha3_384 / sha3_512(data)` → 28 / 32 / 48 / 64 byte digests;
- `shake128 / shake256(data, outlen)` → `outlen` bytes of XOF output;
- `hmac_sha3_256 / hmac_sha3_512(key, message)` → HMAC-SHA3.
### 9.2 Ed25519 Digital Signatures (`purepycrypto.ed25519`, RFC 8032)
```python
from purepycrypto.ed25519 import ed25519_keygen, ed25519_sign, ed25519_verify
seed, pub = ed25519_keygen() # seed (private key) 32 bytes, pub 32 bytes
sig = ed25519_sign(b"hello", seed) # 64-byte signature (R || S)
assert ed25519_verify(sig, b"hello", pub) is True
assert ed25519_verify(sig, b"hell0", pub) is False
```
- Signatures are a fixed 64 bytes; verification failure **returns `False`** (no exception);
- public keys/signatures are much shorter than RSA, suitable as the default signature scheme for new protocols (RSA-PSS is still retained).
### 9.3 AES-GCM-SIV (`purepycrypto.aes_gcm_siv`, RFC 8452)
```python
from purepycrypto.aes_gcm_siv import (
aes128_gcm_siv_encrypt, aes128_gcm_siv_decrypt, aes_gcm_siv_encrypt,
)
import os
key = os.urandom(16) # 16 -> AES-128; 32 -> AES-256
nonce = os.urandom(12) # fixed 12 bytes
ct, tag = aes128_gcm_siv_encrypt(key, nonce, b"secret", aad=b"hdr")
pt = aes128_gcm_siv_decrypt(key, nonce, ct, tag, aad=b"hdr")
assert pt == b"secret"
ct, tag = aes_gcm_siv_encrypt(key, nonce, b"secret") # unified entry, dispatched by key length
```
- **Nonce-misuse resistance**: an accidental `(key, nonce)` repetition does not fail catastrophically like GCM;
- but a **repetition limit** still exists (see [`security.md`](security.md)); when possible, still keep nonces unique;
- the AES-256 version has the same-shaped interface: `aes256_gcm_siv_encrypt / aes256_gcm_siv_decrypt`.
> See [`api.md`](api.md) for full signatures and parameters, and [`security.md`](security.md) for the security positioning.
---
## 10. Error Handling Overview
As of v3.2.0, the library uses a **unified error system** (see [`errors.md`](errors.md) for details):
- **Fatal error → raise `PPYC_ERR`** (carrying `code` / `message` / `suggestion`);
- **Non-fatal error → return a 3-tuple** `(error_code, error_message, suggestion)`; on success the position is `None`.
```python
from purepycrypto import AES, is_err, PPYC_ERR
# fatal error -> raise PPYC_ERR
try:
AES(b"short") # invalid key length
except PPYC_ERR as e:
print(e.code, e.message, e.suggestion) # PPYC_ERR_INVALID_KEY_LEN ...
# non-fatal error -> return a 3-tuple
aes = AES(b"0" * 16)
out = aes.gcm_decrypt(b"\x00" * 12, b"ct", b"\x00" * 16) # tag mismatch
if is_err(out):
code, msg, hint = out
print(code, msg, hint) # PPYC_ERR_AUTH_FAILED ...
else:
plaintext = out
```
**CLI exit codes**: `0` success / `1` other / `2` `PPYC_ERR` / `3` file not found / `4` argument error.
---
## 11. Command Line (TUI and CLI)
Prefer not to write code? After installation there is only one command, `purepycrypto`:
```bash
purepycrypto # no arguments -> interactive TUI (default English; PUREPYCRYPTO_LANG=cn switches to Chinese)
purepycrypto hash --text abc --hex # with arguments -> command-line mode
purepycrypto --help # command-line help
```
When not installed, equivalent: `python -m purepycrypto [subcommand]`.
Enter the interactive TUI and follow the prompts to choose hashing, KDF, AES, ChaCha20, X25519, RSA, and other operations.
Command-line mode (suitable for scripts / pipes / CI):
```bash
echo -n abc | purepycrypto hash --algo sha256 --hex
purepycrypto --help
```
See [`cli.md`](cli.md) for details.
---
## 12. Next Steps
- Complete function signatures and parameter descriptions -> [`api.md`](api.md)
- Full command-line mode description -> [`cli.md`](cli.md)
- Security boundaries and prohibitions -> [`security.md`](security.md)
- Error codes and exit codes -> [`errors.md`](errors.md)
- Running tests and standard-vector coverage -> the "Testing" section of [`../README.md`](../README.md)
> ⚠️ Reminder again: a pure-Python implementation is not suitable for highly adversarial, long-running production-critical systems. Read the security statement before using it in sensitive scenarios.
---
## ⚠️ Windows Multiprocessing Notes (Important)
Some APIs use a `multiprocessing` process pool for acceleration in **large-input** or **batch** scenarios:
| API | Condition that triggers multiprocessing |
|-----|-----------------------------------------|
| `sha3_batch(items, algo, n_workers)` | `n_workers > 1` and enough messages (count ≥ `n_workers × 4`) |
| `aes128/256_gcm_siv_encrypt(...)` | input ≥ 128 KB and `n_workers` is `None` (auto) or `> 1` |
**Windows starts child processes via `spawn` (which re-imports the main module), so caller scripts must be
wrapped in `if __name__ == "__main__":`.** Otherwise it raises:
```
RuntimeError: An attempt has been made to start a new process before the
current process has finished its bootstrapping phase.
This probably means that you are not using fork to start your child processes
and you have forgotten to use the proper idiom in the main module:
if __name__ == '__main__':
freeze_support()
...
```
### ✅ Correct pattern
```python
# my_script.py
from purepycrypto import sha3_batch, aes256_gcm_siv_encrypt
def main():
# batch hashing (multiprocessing)
digests = sha3_batch([b"a", b"b", ...], "sha3_256", n_workers=4)
# large-file encryption (automatic multiprocessing)
ct, tag = aes256_gcm_siv_encrypt(key, nonce, big_data)
if __name__ == "__main__": # <- mandatory on Windows
main()
```
### ⛔ Incorrect pattern (raises an error or silently slows down)
```python
from purepycrypto import sha3_batch, aes256_gcm_siv_encrypt
# called directly at module level -- on Windows the child process re-executes this module, causing a RuntimeError
digests = sha3_batch(messages, "sha3_256", n_workers=4)
ct, tag = aes256_gcm_siv_encrypt(key, nonce, big_data)
```
### 🛡️ Two ways to avoid it
1. **Add the `if __name__ == "__main__":` guard** (recommended; you keep the parallel speedup)
2. **Explicitly pass `n_workers=1` to force serial** (no startup overhead; actually faster for small data)
> **Fault tolerance note**: `sha3_batch` has a built-in fallback — if multiprocessing fails to start it automatically degenerates to
> serial computation and returns the correct result, without crashing (but loses the speedup).
> The AES-GCM-SIV multiprocessing branch, however, raises the `RuntimeError` above in the same situation,
> **so be sure to add the guard**.
> **Linux / macOS**: default to `fork` and usually have no such limitation; but for cross-platform consistency,
> it is still strongly recommended to add the `if __name__ == "__main__":` guard uniformly.
+227
View File
@@ -0,0 +1,227 @@
# 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.**