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:
@@ -0,0 +1,30 @@
|
||||
# Normalize line endings for a cross-platform repository.
|
||||
# Python source and text files are stored with LF in the repository;
|
||||
# working-tree checkout uses the platform default (CRLF on Windows).
|
||||
|
||||
* text=auto eol=lf
|
||||
|
||||
# ---- Explicit: source & docs ----
|
||||
*.py text eol=lf
|
||||
*.pyi text eol=lf
|
||||
*.typed text eol=lf
|
||||
*.md text eol=lf
|
||||
*.toml text eol=lf
|
||||
*.cfg text eol=lf
|
||||
*.ini text eol=lf
|
||||
*.txt text eol=lf
|
||||
*.json text eol=lf
|
||||
*.in text eol=lf
|
||||
|
||||
# ---- Binary ----
|
||||
*.whl binary
|
||||
*.gz binary
|
||||
*.zip binary
|
||||
*.png binary
|
||||
*.jpg binary
|
||||
*.jpeg binary
|
||||
*.ico binary
|
||||
*.pdf binary
|
||||
|
||||
# ---- Keep generated / vendored single-file bundles byte-exact ----
|
||||
purepycrypto/single/purepycrypto.py text eol=lf
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
# ---- Python ----
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
*.so
|
||||
.Python
|
||||
build/
|
||||
dist/
|
||||
*.egg-info/
|
||||
.eggs/
|
||||
pip-wheel-metadata/
|
||||
|
||||
# ---- Tests / coverage ----
|
||||
.pytest_cache/
|
||||
.coverage
|
||||
.coverage.*
|
||||
htmlcov/
|
||||
.tox/
|
||||
.nox/
|
||||
|
||||
# ---- Virtual environments ----
|
||||
.venv/
|
||||
venv/
|
||||
env/
|
||||
ENV/
|
||||
|
||||
# ---- Editors / system ----
|
||||
.vscode/
|
||||
.idea/
|
||||
*.swp
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
# ---- Build artifacts ----
|
||||
*.bak
|
||||
*.tmp
|
||||
_merged/
|
||||
+390
@@ -0,0 +1,390 @@
|
||||
# Changelog
|
||||
|
||||
This file records all notable changes to `purepycrypto`.
|
||||
|
||||
The format follows [Keep a Changelog](https://keepachangelog.com/zh-CN/1.1.0/),
|
||||
and the version numbers follow [Semantic Versioning](https://semver.org/lang/zh-CN/).
|
||||
|
||||
---
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### 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 `cn` language 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 is `cn`
|
||||
(see `_TUI_ERR_TEXT` / `_tui_error_text()` in `cli.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 in
|
||||
`en` and `cn`.
|
||||
- The Encoding and Secure Random sub-menus were rewritten to use the i18n layer, so
|
||||
they are now fully Chinese in `cn` mode and fully English in `en` mode
|
||||
(previously they mixed both).
|
||||
- `Ctrl+C` printed the literal `bye` because `_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` (JWK `n`/`e` style)
|
||||
- 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_len` can relax it for compatibility with legacy systems)
|
||||
- **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_RAND` capability flags)
|
||||
- **New CLI subcommands**:
|
||||
- `purepycrypto encode --format base64|base64url|base32|hex|base58 --op enc|dec`
|
||||
- `purepycrypto random --kind bytes|token|urlsafe|password|uuid`
|
||||
- **New TUI menu items**: `[9] Encoding` / `[10] Random` (bilingual CN/EN)
|
||||
- **`build_single.py`**: includes `encoding` / `rand` / `kdf2` in 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 attributes `code` / `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 (or `OK_TUPLE` = `(None,None,None)` for validation-style APIs).
|
||||
|
||||
What's new:
|
||||
|
||||
- Exception class `PPYC_ERR` (and alias `PPYCError`), with `as_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 than `PPYC_ERR_`).
|
||||
- The legacy exception names `CryptoError` / `DecryptionError` / `Ed25519Error` are all kept as subclasses of `PPYC_ERR`,
|
||||
carrying default error codes, ensuring backward compatibility.
|
||||
- New documentation [`docs/errors.md`](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 SystemExit` in 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.)
|
||||
- **CLI**: `SystemExit` is fully replaced by `PPYC_ERR`; `_cli_main` catches 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 bare `EOFError`.
|
||||
- **Single-file packaging**: `_ppyc_error` is 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):
|
||||
|
||||
1. **`sha3.py` hex wrapper crash**: `shake128_hex/256_hex/sha3_*_hex` called `.hex()` on an error tuple
|
||||
returned for invalid parameters → `AttributeError`. A unified `_to_hex()` handler was added.
|
||||
2. **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 to `PPYC_ERR`.
|
||||
3. **CLI `x25519` wrong exit code**: it printed an error for a wrong private-key length but returned code 0. Now it raises
|
||||
`PPYC_ERR` → exit code 2.
|
||||
4. **TUI `_hash_menu`/`_kdf_menu` crash**: with invalid parameters such as `blake2b(digest_size=0)` or `scrypt(N=15)`,
|
||||
the TUI raised a bare `AttributeError`. A unified `_raise_if_err()` handler was added.
|
||||
5. **TUI `x25519`/`rsa` unpacking crash**: unpacks such as `shared, zero = x25519_shared(...)` received an error tuple
|
||||
for invalid parameters → `ValueError: too many values to unpack`. Protection was added.
|
||||
6. **TUI self-test failure**: the XChaCha tamper detection in `_self_test()` still expected `DecryptionError` to 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.py` where internal helpers had been mistakenly changed to return tuples, causing caller unpacking failures
|
||||
(`choose_hash` / `mgf1` / `oaep_encode` / `oaep_decode` / `pss_encode` / `mod_inverse` / `_jacobi`
|
||||
reverted to raising `PPYC_ERR`, with the public API responsible for converting to tuples).
|
||||
- Fixed `__init__.py` not actually exporting the error-code constants, which made `from purepycrypto import PPYC_ERR_xxx` fail.
|
||||
- Fixed `ALL_ERROR_CODES` mistakenly counting the prefix constant `PPYC_ERR_PREFIX` in the error-code table.
|
||||
- Fixed the single-file merge missing the `Union` import and the `_ppyc_error` module.
|
||||
|
||||
### Verification
|
||||
|
||||
- Full pytest suite: **126+ passed** (including the new `test_errors_edge.py` 69 cases + `test_vectors_strict.py` 57 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.py` verified 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-args` command and switched to a **single command** `purepycrypto`.
|
||||
- `purepycrypto` (no arguments) → launch the interactive TUI
|
||||
- `purepycrypto <subcommand> ...` (with arguments) → command-line mode
|
||||
- **Entry-behavior change**: `purepycrypto:main` now dispatches automatically based on whether arguments are present (the old form
|
||||
`python -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 generates `purepycrypto_tui.py` / `purepycrypto_cli.py` / `purepycrypto_lib.py`.
|
||||
|
||||
### Added (7 feature upgrades)
|
||||
|
||||
1. **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|cn` to override the default language
|
||||
- New `set_language()` / `get_language()` API
|
||||
2. **`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=None` auto-detects the CPU count; small batches automatically degenerate to serial
|
||||
3. **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
|
||||
4. **AES-GCM-SIV multiprocessing parameter**: `n_workers=None` (auto-optimal) / `1` (force serial)
|
||||
5. **Single-command architecture**: one `purepycrypto` command provides both the TUI and the CLI
|
||||
6. **Single-file bundle**: `build_single.py --mode one` generates `purepycrypto/single/purepycrypto.py`
|
||||
(likewise: no arguments = TUI, arguments = command line)
|
||||
7. **Performance optimization** (alternating measurement in the same process, minimum over multiple rounds)
|
||||
- SHA-3: `keccak_f1600` 1410 → **191 µs/perm** (**7.4x**, SWAR packed integers)
|
||||
`sha3_256` 425 → **838 KB/s** (1.97x); `hmac_sha3_256` 277 → 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: `sign` 3.52 → **1.79 ms**, `verify` 3.89 → **1.95 ms** (**2.0x** each)
|
||||
|
||||
### Fixed (10 bug fixes)
|
||||
|
||||
1. **BLAKE2b**: wrong digest when the input length is an integer multiple of 128 bytes (incorrect handling of the final block's `f` flag)
|
||||
2. **Single-file constant conflict**: `aes_gcm_siv`'s `NONCE_LEN` overrode the same-named constant in `chacha`, breaking XChaCha
|
||||
3. **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
|
||||
4. **AES-GCM-SIV unified entry**: `aes_gcm_siv_encrypt/decrypt` were missing the `n_workers` parameter (NameError)
|
||||
5. **`sha3_batch` multiprocessing result ordering**: round-robin sharding caused the output to not correspond to the input (changed to contiguous sharding)
|
||||
6. **`sha3_batch` Windows spawn crash**: child-process re-entry errored when the `__main__` guard was missing (added a fallback that degenerates to serial)
|
||||
7. **CLI / TUI crash on GBK consoles**: `UnicodeEncodeError` when printing characters such as `✓` (added console-encoding compatibility)
|
||||
8. **`build_single` mistakenly deleted the `__main__` example inside a docstring**: changed to match only top-level indentation
|
||||
9. **`build_single` deleted the `try/except` fallback import block incompletely**: changed to delete the whole block
|
||||
10. **Single-file entry `_sys` undefined**: the `--mode one` artifact crashed with `NameError` on 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.py` demonstrates correct multiprocessing usage
|
||||
- **pyproject.toml / setup.py**: clarified the CLI/TUI installation logic (single console script) and added the `purepycrypto.single` package
|
||||
|
||||
### 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 arbitrary `outlen` bytes.
|
||||
- `hmac_sha3_256(key, message)` / `hmac_sha3_512(key, message)` — HMAC-SHA3, outputting 32 / 64 bytes (the block size is the variant's rate `r`, 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 returns `False` (no exception).
|
||||
- Helper interfaces: `ed25519_scalarmult_base(scalar)`, `ed25519_is_valid_publickey(pub32)`, exception `Ed25519Error`.
|
||||
- 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)` and `aes128_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 constants `TAG_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 subcommands `hash` / `hmac` / `kdf` / `aes` / `chacha` / `x25519` / `rsa` / `rand` / `selftest` / `version`.
|
||||
|
||||
#### Package Layout Adjustment
|
||||
|
||||
- Moved the three directories `tests/`, `examples/`, `scripts/` into the `purepycrypto/` 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.py` supports `--mode tui|cli|lib|all`, generating the three single-file artifacts individually or all at once (`--all` generates tui + cli + lib together).
|
||||
- The command-line mode is now provided by `purepycrypto.cli_args`; `python -m purepycrypto` still launches the interactive TUI.
|
||||
- Version bumped from `1.0.0` to `1.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 by `purepycrypto/__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_workers` parameter.
|
||||
|
||||
#### 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 into `RSAPrivateKey`.
|
||||
|
||||
#### Engineering Utilities (`purepycrypto.common` / `purepycrypto.parallel`)
|
||||
|
||||
- Constant-time comparison: `_consttime_eq`, `_consttime_int_eq`, `_consttime_select`.
|
||||
- Secure random: `rand_bytes(n)` (based on `os.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`), `SharedMemory` allocation and release, automatic cleanup via `atexit`.
|
||||
- Parallel-capability probe flag `_HAS_MP`; falls back to serial automatically when unsupported.
|
||||
|
||||
#### Command Line
|
||||
|
||||
- Supports `python -m purepycrypto` to launch the interactive TUI.
|
||||
|
||||
### Notes
|
||||
|
||||
- This release **does not include** Ed25519/EdDSA, nor any post-quantum (PQC) algorithm.
|
||||
- `rsa_keygen` requires `bits >= 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).
|
||||
|
||||
---
|
||||
|
||||
[Unreleased]: https://github.com/dvs/purepycrypto/compare/v1.1.0...HEAD
|
||||
[1.1.0]: https://github.com/dvs/purepycrypto/releases/tag/v1.1.0
|
||||
[1.0.0]: https://github.com/dvs/purepycrypto/releases/tag/v1.0.0
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Dvs(DvsXT) <dvs6666@163.com>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
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.
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
include LICENSE
|
||||
include README.md
|
||||
include CHANGELOG.md
|
||||
include pyproject.toml
|
||||
include setup.py
|
||||
recursive-include purepycrypto *.py py.typed
|
||||
recursive-include purepycrypto/tests *.py *.json
|
||||
recursive-include purepycrypto/examples *.py
|
||||
recursive-include purepycrypto/scripts *.py
|
||||
recursive-include docs *.md
|
||||
global-exclude *.py[cod] __pycache__ *.so *.bak *.bak_* pytest_full.txt
|
||||
@@ -0,0 +1,804 @@
|
||||
# purepycrypto
|
||||
|
||||
[](https://pypi.org/project/purepycrypto/)
|
||||
[](https://www.python.org/)
|
||||
[](./LICENSE)
|
||||
[](.)
|
||||
[-orange)](.)
|
||||
|
||||
> **Pure Python Cryptography Toolkit — a zero-dependency pure-Python cryptography library.**
|
||||
> SHA-2 / SHA-3 / SHAKE / BLAKE2b · PBKDF2 / HKDF / scrypt / Argon2id · AES (ECB/CBC/CTR/CFB/OFB/GCM) · AES-GCM-SIV · ChaCha20-Poly1305 / XChaCha20-Poly1305 · X25519 · Ed25519 · RSA-OAEP / PSS · PKCS#1 / PKCS#8 / SPKI / PEM
|
||||
|
||||
Current version: **v3.2.0** (this release adds the `kdf2` / `encoding` / `rand` modules, see [§ New in v3.2.0](#-new-in-v320)).
|
||||
|
||||
---
|
||||
|
||||
## 🆕 What's New in This Release (v3.2.0)
|
||||
|
||||
> Version numbering rule: `v{major}.{feature upgrades}.{bug fixes}` → this release contains both **feature upgrades** and **bug fixes**.
|
||||
|
||||
### 1. Unified Error System (⚠️ Breaking Change)
|
||||
|
||||
Library-wide error handling is unified into two categories, semantically clear and never mixed:
|
||||
|
||||
- **Fatal error → raise `PPYC_ERR(code, message, suggestion)`**
|
||||
Raised only when the program can no longer continue safely (internal invariant broken, 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) **no longer raise exceptions**; the caller can handle them gracefully by checking the return value.
|
||||
- **41 standard error codes**, unified prefix `PPYC_ERR_`, covering 9 major categories.
|
||||
- Helper functions: `ok()` / `err()` / `is_ok()` / `is_err()` / `raise_ppyc()` / `OK_TUPLE` / `PPYCResult`.
|
||||
- Legacy exception names `CryptoError` / `DecryptionError` / `Ed25519Error` are kept as **subclasses** of `PPYC_ERR` (backward compatible).
|
||||
- CLI exit codes: `0` success / `2` `PPYC_ERR` / `3` file not found / `4` argument error.
|
||||
- See [`docs/errors.md`](docs/errors.md) for details.
|
||||
|
||||
### 2. TUI CN/EN Language Switch (default EN)
|
||||
|
||||
The TUI supports **Chinese / English interface switching**, defaulting to English, and can be overridden with the environment variable `PUREPYCRYPTO_LANG=cn`.
|
||||
|
||||
### 3. Performance Optimization
|
||||
|
||||
| Algorithm | Before | After | Speedup |
|
||||
|-----------|--------|-------|---------|
|
||||
| SHA-3 `keccak_f1600` | 1410 µs/perm | **191 µs/perm** | **7.4x** |
|
||||
| SHA-3 `sha3_256` throughput | 425 KB/s | **838 KB/s** | 1.97x |
|
||||
| SHA-3 `hmac_sha3_256` | 277 KB/s | **628 KB/s** | 2.27x |
|
||||
| AES-GCM-SIV large message | 146 KB/s | **1101 KB/s** | **7.5x** |
|
||||
| AES-GCM-SIV 32B small message | 1693 µs | **198 µs** | **8.5x** |
|
||||
| Ed25519 `sign` | 3.52 ms | **1.79 ms** | 2.0x |
|
||||
| Ed25519 `verify` | 3.89 ms | **1.95 ms** | 2.0x |
|
||||
|
||||
> Techniques: SHA-3 uses **SWAR packed integers**; AES-GCM-SIV adds a **POLYVAL table cache** + derived-key cache + CTR multiprocessing; Ed25519 window and precomputation optimizations.
|
||||
|
||||
### 4. Fixes for 6 Real Defects
|
||||
|
||||
Including the `sha3.py` hex wrapper crash, the CLI `_write_binary()` crash, the CLI `x25519` wrong exit code,
|
||||
TUI hash / KDF menu crashes, TUI `x25519`/`rsa` unpacking crashes, TUI self-test false positives, etc. See [`CHANGELOG.md`](./CHANGELOG.md) for details.
|
||||
|
||||
---
|
||||
|
||||
## 📖 Table of Contents
|
||||
|
||||
- [Project Overview](#-project-overview)
|
||||
- [Feature Overview](#-feature-overview)
|
||||
- [Requirements](#-requirements)
|
||||
- [Installation](#-installation)
|
||||
- [Three Usage Modes](#-three-usage-modes-one-command-three-forms)
|
||||
- [Quick Start](#-quick-start)
|
||||
- [Unified Error System](#-unified-error-system)
|
||||
- [New in v3.2.0](#-new-in-v320)
|
||||
- [Windows Multiprocessing Notes](#-windows-multiprocessing-notes-important)
|
||||
- [TUI Language Switch](#-tui-language-switch-cn--en)
|
||||
- [API Cheat Sheet](#-api-cheat-sheet)
|
||||
- [Security Notes](#-security-notes)
|
||||
- [Known Limitations](#-known-limitations)
|
||||
- [Testing](#-testing)
|
||||
- [FAQ](#-faq)
|
||||
- [Contributing](#-contributing)
|
||||
- [License](#-license)
|
||||
- [Author](#-author)
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Project Overview
|
||||
|
||||
`purepycrypto` is a cryptography toolkit **implemented entirely in pure Python with zero third-party dependencies**. Its goal is not to replace heavily audited libraries such as
|
||||
`cryptography` / OpenSSL that call high-performance C implementations, but to provide:
|
||||
|
||||
- **Readable, auditable, portable** — every algorithm is written line by line in pure Python, with no reliance on any C extension or system library;
|
||||
- **Teaching- and embedded-friendly** — runs in any environment that can run CPython, with no compilation;
|
||||
- **Correctness first** — strictly follows RFC / FIPS / NIST standards and self-tests against official vectors;
|
||||
- **Modern algorithm portfolio** — covers hashing, message authentication, key derivation, symmetric encryption, authenticated encryption, key exchange, and public-key signatures.
|
||||
|
||||
> ⚠️ The performance and side-channel characteristics of pure Python make it **unsuitable** for high-throughput, strongly adversarial, long-running production-critical scenarios.
|
||||
> Be sure to read the [Security Notes](#-security-notes) and [`docs/security.md`](docs/security.md).
|
||||
|
||||
Author: **Dvs(DvsXT)** · License: **MIT** · Current version: **v3.2.0**
|
||||
|
||||
---
|
||||
|
||||
## ✨ Feature Overview
|
||||
|
||||
| Category | Algorithm / Feature | Standard | Status |
|
||||
|----------|---------------------|----------|--------|
|
||||
| **Hashing** | SHA-256 / SHA-512 | FIPS 180-4 | ✅ |
|
||||
| | BLAKE2b (variable digest length 1–64 bytes) | RFC 7693 | ✅ |
|
||||
| | SHA3-224 / 256 / 384 / 512 | FIPS 202 | ✅ |
|
||||
| | SHAKE128 / SHAKE256 (extendable-output XOF) | FIPS 202 | ✅ |
|
||||
| **Message Authentication** | HMAC-SHA256 / HMAC-SHA512 | RFC 2104 | ✅ |
|
||||
| | HMAC-SHA3-256 / HMAC-SHA3-512 | RFC 2104 / FIPS 198-1 | ✅ |
|
||||
| | Poly1305 (one-time authenticator) | RFC 8439 | ✅ |
|
||||
| **Key Derivation** | PBKDF2-HMAC-SHA256 / SHA512 | RFC 8018 / RFC 6070 | ✅ |
|
||||
| | HKDF (extract / expand / one-shot) | RFC 5869 | ✅ |
|
||||
| | scrypt | RFC 7914 | ✅ |
|
||||
| | Argon2id (with secret / associated data) | RFC 9106 | ✅ |
|
||||
| **Symmetric Encryption** | AES-128 / 192 / 256 | FIPS 197 | ✅ |
|
||||
| | Modes: ECB / CBC / CTR / CFB / OFB | NIST SP 800-38A | ✅ |
|
||||
| | GCM (AEAD, with AAD) | NIST SP 800-38D | ✅ |
|
||||
| **Authenticated Encryption** | ChaCha20-Poly1305 | RFC 8439 | ✅ |
|
||||
| | XChaCha20-Poly1305 (192-bit nonce) | draft-irtf-cfrg-xchacha | ✅ |
|
||||
| | AES-GCM-SIV (nonce-misuse resistant) | RFC 8452 | ✅ |
|
||||
| **Key Exchange** | X25519 | RFC 7748 | ✅ |
|
||||
| **Public-Key Encryption** | RSA-OAEP | RFC 8017 | ✅ |
|
||||
| **Digital Signatures** | RSA-PSS | RFC 8017 | ✅ |
|
||||
| | Ed25519 (Pure EdDSA) | RFC 8032 | ✅ |
|
||||
| **Serialization** | PKCS#1 / PKCS#8 / SPKI / PEM | RFC 8017 / 5958 / 5280 | ✅ |
|
||||
| **Engineering Utilities** | Constant-time comparison, secure random | — | ✅ |
|
||||
| | Multiprocessing acceleration (pool reuse + SharedMemory) | — | ✅ |
|
||||
| | Interactive TUI (CN/EN bilingual) / command-line CLI | — | ✅ |
|
||||
| | Single-file bundle `purepycrypto/single/purepycrypto.py` | — | ✅ |
|
||||
| **New in v3.2.0** | `kdf2` (hardened KDF) / `encoding` (encoding) / `rand` (CSPRNG) | — | ✅ |
|
||||
| **Not Included** | Post-quantum algorithms (Kyber / Dilithium / Falcon / SPHINCS+, etc.) | — | ❌ Not provided |
|
||||
|
||||
> **Explicitly excludes** any post-quantum (PQC) algorithm. For signatures, choose **Ed25519** (recommended for new protocols) or **RSA-PSS**;
|
||||
> for key exchange, use the **X25519** + **HKDF** + **AES-GCM** / **AES-GCM-SIV** / **ChaCha20-Poly1305** combination.
|
||||
|
||||
---
|
||||
|
||||
## 🧩 Requirements
|
||||
|
||||
- **Python ≥ 3.7** (`pyproject.toml` declares `requires-python = ">=3.7"`; CI covers 3.7–3.13)
|
||||
- **No third-party runtime dependencies** (uses only the standard library: `struct`, `os`, `math`, `base64`, `multiprocessing`, etc.)
|
||||
- Optional: multiprocessing acceleration is enabled automatically on platforms that support `multiprocessing.shared_memory` (Python ≥ 3.8), otherwise it falls back to serial execution automatically
|
||||
|
||||
---
|
||||
|
||||
## 📦 Installation
|
||||
|
||||
Install from PyPI:
|
||||
|
||||
```bash
|
||||
pip install purepycrypto
|
||||
```
|
||||
|
||||
Upgrade to the latest version:
|
||||
|
||||
```bash
|
||||
pip install --upgrade purepycrypto
|
||||
```
|
||||
|
||||
Install from source (development mode):
|
||||
|
||||
```bash
|
||||
git clone <repo-url>
|
||||
cd purepycrypto
|
||||
pip install -e .
|
||||
```
|
||||
|
||||
After installation, a single command `purepycrypto` is available (no arguments enters the TUI, arguments go to the command line).
|
||||
|
||||
---
|
||||
|
||||
## 🎛️ Three Usage Modes (One Command, Three Forms)
|
||||
|
||||
After installation only **one** command, `purepycrypto`, is registered; its behavior is dispatched automatically based on whether arguments are present:
|
||||
|
||||
```bash
|
||||
# (1) no arguments -> interactive TUI (default English; PUREPYCRYPTO_LANG=cn switches to Chinese)
|
||||
purepycrypto
|
||||
purepycrypto tui # explicitly launch the TUI (equivalent)
|
||||
|
||||
# (2) with arguments -> command-line mode (subcommands: hash / hmac / kdf / aes / chacha / x25519 / rsa / rand / selftest / version)
|
||||
purepycrypto hash --text abc --hex
|
||||
purepycrypto --help # show command-line help
|
||||
|
||||
# (3) import as a library
|
||||
python -c "import purepycrypto; print(purepycrypto.__version__)"
|
||||
```
|
||||
|
||||
When not installed (inside the source directory), the equivalent form is:
|
||||
|
||||
```bash
|
||||
python -m purepycrypto # TUI
|
||||
python -m purepycrypto hash --text abc --hex # command line
|
||||
python -c "import purepycrypto" # library
|
||||
```
|
||||
|
||||
> ⚠️ **Important**: The command-line entry point has been unified into a **single command** `purepycrypto` (no arguments = TUI, arguments = CLI).
|
||||
> The only single-file artifact is the in-package `purepycrypto/single/purepycrypto.py` (generated by
|
||||
> `scripts/build_single.py --mode one`), whose behavior is likewise "no arguments = TUI, arguments = CLI".
|
||||
|
||||
### Single-File Bundle
|
||||
|
||||
```bash
|
||||
# generate the single file in the source directory (no arguments = TUI, arguments = CLI)
|
||||
python purepycrypto/scripts/build_single.py --mode one -o purepycrypto/single/purepycrypto.py
|
||||
|
||||
# run it directly
|
||||
python purepycrypto/single/purepycrypto.py # TUI
|
||||
python purepycrypto/single/purepycrypto.py hash --text abc --hex # command line
|
||||
```
|
||||
|
||||
Used as a library (when there is no entry point):
|
||||
|
||||
```python
|
||||
import purepycrypto as ppc
|
||||
print(ppc.sha3_256(b"abc").hex())
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🚀 Quick Start
|
||||
|
||||
All examples are based on the `purepycrypto v3.2.0` public API and can be run directly (Python ≥ 3.8).
|
||||
|
||||
### 1. Hashing
|
||||
|
||||
```python
|
||||
from purepycrypto import sha256, sha512, blake2b
|
||||
|
||||
print(sha256(b"abc").hex())
|
||||
# ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad
|
||||
|
||||
print(len(sha512(b"abc"))) # 64
|
||||
print(len(blake2b(b"abc"))) # 64 (default)
|
||||
print(len(blake2b(b"abc", digest_size=32))) # 32
|
||||
```
|
||||
|
||||
> Input must be `bytes`; for strings, call `.encode("utf-8")` first. When `blake2b`'s `digest_size` is invalid (outside 1–64),
|
||||
> it **returns an error tuple** instead of raising (see [Unified Error System](#-unified-error-system)).
|
||||
|
||||
### 2. Key Derivation (KDF)
|
||||
|
||||
```python
|
||||
from purepycrypto import (
|
||||
hmac_sha256, pbkdf2_hmac, hkdf, hkdf_extract, hkdf_expand, scrypt, argon2id,
|
||||
)
|
||||
import os
|
||||
|
||||
# --- HMAC ---
|
||||
mac = hmac_sha256(b"key", b"message")
|
||||
|
||||
# --- PBKDF2 ---
|
||||
salt = os.urandom(16)
|
||||
dk = pbkdf2_hmac(b"password", salt, iterations=200_000, dklen=32, hash_name="sha256")
|
||||
|
||||
# --- HKDF (RFC 5869) ---
|
||||
prk = hkdf_extract(salt=salt, ikm=b"input key material") # extract
|
||||
okm = hkdf_expand(prk=prk, info=b"app-context", length=32) # expand
|
||||
okm2 = hkdf(ikm=b"input key material", salt=salt, info=b"app-context", length=32)
|
||||
|
||||
# --- scrypt (RFC 7914) ---
|
||||
sk = scrypt(b"password", b"NaCl", N=2**14, r=8, p=1, dklen=32)
|
||||
|
||||
# --- Argon2id (RFC 9106, recommended for new systems) ---
|
||||
tag = argon2id(
|
||||
password=b"password",
|
||||
salt=os.urandom(16), # recommended ≥ 16 bytes
|
||||
t=3, # number of iterations
|
||||
m=65536, # memory (KiB)
|
||||
p=4, # parallelism
|
||||
tag_length=32,
|
||||
)
|
||||
```
|
||||
|
||||
### 3. AES Symmetric Encryption
|
||||
|
||||
```python
|
||||
from purepycrypto import AES
|
||||
import os
|
||||
|
||||
key = os.urandom(32) # 16 / 24 / 32 bytes -> AES-128 / 192 / 256
|
||||
aes = AES(key)
|
||||
|
||||
# --- GCM (AEAD, recommended) ---
|
||||
nonce = os.urandom(12) # 96-bit nonce
|
||||
ct, tag = aes.gcm_encrypt(nonce, b"secret data", aad=b"header")
|
||||
pt = aes.gcm_decrypt(nonce, ct, tag, aad=b"header") # returns bytes on success
|
||||
# on auth failure returns an (error_code, message, suggestion) tuple, see "Unified Error System"
|
||||
|
||||
# --- CBC (automatic PKCS#7 padding) ---
|
||||
iv = os.urandom(16)
|
||||
ct = aes.encrypt_cbc(b"secret data", iv)
|
||||
pt = aes.decrypt_cbc(ct, iv)
|
||||
|
||||
# --- CTR (nonce is 8 bytes) ---
|
||||
ct = aes.encrypt_ctr(b"secret data", os.urandom(8))
|
||||
```
|
||||
|
||||
Other modes: `encrypt_ecb / decrypt_ecb`, `encrypt_cfb / decrypt_cfb`, `encrypt_ofb / decrypt_ofb`.
|
||||
|
||||
### 4. ChaCha20-Poly1305 / XChaCha20-Poly1305
|
||||
|
||||
```python
|
||||
from purepycrypto import (
|
||||
chacha20poly1305_encrypt, chacha20poly1305_decrypt,
|
||||
xchacha20poly1305_encrypt, xchacha20poly1305_decrypt,
|
||||
poly1305_mac,
|
||||
)
|
||||
import os
|
||||
|
||||
key = os.urandom(32)
|
||||
|
||||
# ChaCha20-Poly1305 (12-byte nonce, RFC 8439) -- returns ciphertext || tag
|
||||
blob = chacha20poly1305_encrypt(key, os.urandom(12), b"secret", aad=b"aad")
|
||||
pt = chacha20poly1305_decrypt(key, nonce, blob, aad=b"aad") # returns a tuple on failure
|
||||
|
||||
# XChaCha20-Poly1305 (24-byte nonce, safe to generate randomly)
|
||||
blob = xchacha20poly1305_encrypt(key, os.urandom(24), b"secret", aad=b"aad")
|
||||
pt = xchacha20poly1305_decrypt(key, nonce24, blob, aad=b"aad")
|
||||
|
||||
# raw Poly1305 authenticator
|
||||
mac = poly1305_mac(os.urandom(32), b"message")
|
||||
```
|
||||
|
||||
### 5. X25519 Key Exchange
|
||||
|
||||
```python
|
||||
from purepycrypto import x25519, x25519_base, x25519_shared, x25519_generate_keypair
|
||||
|
||||
priv_a, pub_a = x25519_generate_keypair() # both 32 bytes
|
||||
priv_b, pub_b = x25519_generate_keypair()
|
||||
|
||||
shared_a, is_zero_a = x25519_shared(priv_a, pub_b)
|
||||
shared_b, is_zero_b = x25519_shared(priv_b, pub_a)
|
||||
assert shared_a == shared_b
|
||||
if is_zero_a or is_zero_b: # must check for a low-order point (all zero)
|
||||
raise RuntimeError("low-order or forged public key detected")
|
||||
|
||||
pub = x25519_base(priv_a) # base point u=9
|
||||
raw = x25519(priv_a, pub_b) # same as shared_a
|
||||
```
|
||||
|
||||
### 6. Ed25519 Digital Signatures
|
||||
|
||||
```python
|
||||
from purepycrypto import ed25519_keygen, ed25519_publickey, 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 # verification failure returns False, does not raise
|
||||
|
||||
# derive the public key from a known seed (RFC 8032 §7.1 TEST 1)
|
||||
seed = bytes.fromhex("9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60")
|
||||
print(ed25519_publickey(seed).hex())
|
||||
# d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a
|
||||
```
|
||||
|
||||
### 7. RSA Public-Key Encryption and Signing
|
||||
|
||||
```python
|
||||
from purepycrypto import (
|
||||
rsa_keygen, rsa_oaep_encrypt, rsa_oaep_decrypt,
|
||||
rsa_pss_sign, rsa_pss_verify,
|
||||
)
|
||||
|
||||
pub, priv = rsa_keygen(bits=2048, parallel=True) # parallel=True uses multiprocessing to speed up prime search
|
||||
|
||||
# OAEP encryption (RFC 8017)
|
||||
ct = rsa_oaep_encrypt(b"secret message", pub, label=b"ctx")
|
||||
pt = rsa_oaep_decrypt(ct, priv, label=b"ctx")
|
||||
|
||||
# PSS sign / verify
|
||||
sig = rsa_pss_sign(b"message to sign", priv)
|
||||
assert rsa_pss_verify(b"message to sign", sig, pub) is True
|
||||
assert rsa_pss_verify(b"tampered", sig, pub) is False
|
||||
```
|
||||
|
||||
> RSA keys must be **at least 521 bits** (below this a `PPYC_ERR` is raised; OAEP/PSS need a sufficient modulus length). 2048 / 3072 / 4096 are recommended.
|
||||
|
||||
### 8. PEM / DER Serialization
|
||||
|
||||
```python
|
||||
from purepycrypto import (
|
||||
rsa_keygen, private_key_to_pem, public_key_to_pem, parse_private_pem,
|
||||
private_key_to_pkcs8_der, public_key_to_spki_der,
|
||||
)
|
||||
|
||||
pub, priv = rsa_keygen(2048)
|
||||
|
||||
pem_priv = private_key_to_pem(priv) # -----BEGIN PRIVATE KEY----- (PKCS#8)
|
||||
pem_pub = public_key_to_pem(pub) # -----BEGIN PUBLIC KEY----- (SPKI)
|
||||
|
||||
der_priv = private_key_to_pkcs8_der(priv)
|
||||
der_pub = public_key_to_spki_der(pub)
|
||||
|
||||
priv2 = parse_private_pem(pem_priv) # parse a PKCS#8 PEM private key
|
||||
assert priv2.n == priv.n
|
||||
|
||||
with open("private_key.pem", "w", encoding="ascii") as f:
|
||||
f.write(pem_priv)
|
||||
```
|
||||
|
||||
### 9. SHA-3 / SHAKE
|
||||
|
||||
```python
|
||||
from purepycrypto import sha3_256, sha3_512, shake128, hmac_sha3_256, sha3_batch
|
||||
|
||||
print(sha3_256(b"abc").hex())
|
||||
# 3a985da74fe225b2045c172d6bd390bd855f086e3e9d525b46bfe24511431532
|
||||
|
||||
print(shake128(b"abc", 32).hex()) # XOF: outputs an arbitrary outlen bytes
|
||||
# 5881092dd818bf5cf8a3ddb793fbcba74097d5c526a6d35f97b83351940f2cc8
|
||||
|
||||
mac = hmac_sha3_256(b"key", b"message") # 32 bytes
|
||||
|
||||
# batch parallel hashing (multiple independent messages; n_workers=None auto-detects CPU count)
|
||||
digests = sha3_batch([b"a", b"b", b"c"], algo="sha3_256", n_workers=4)
|
||||
```
|
||||
|
||||
### 10. AES-GCM-SIV
|
||||
|
||||
```python
|
||||
from purepycrypto import (
|
||||
aes128_gcm_siv_encrypt, aes128_gcm_siv_decrypt, # 16-byte key
|
||||
aes256_gcm_siv_encrypt, aes256_gcm_siv_decrypt, # 32-byte key
|
||||
aes_gcm_siv_encrypt, aes_gcm_siv_decrypt, # unified entry (dispatches by key length)
|
||||
set_cache_enabled, cache_enabled, clear_caches,
|
||||
)
|
||||
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"header")
|
||||
pt = aes128_gcm_siv_decrypt(key, nonce, ct, tag, aad=b"header")
|
||||
assert pt == b"secret"
|
||||
|
||||
# cache control (enabled by default; disable if the threat model disallows derived keys residing in memory)
|
||||
set_cache_enabled(False) # disable cache
|
||||
assert cache_enabled() is False
|
||||
clear_caches() # clear cached content
|
||||
```
|
||||
|
||||
> ⚠️ GCM-SIV only **reduces** the harm of nonce reuse; it does not permit unlimited reuse. When possible, still keep nonces unique.
|
||||
|
||||
### 11. Unified Error Handling (Overview)
|
||||
|
||||
```python
|
||||
from purepycrypto import AES, is_err, PPYC_ERR, PPYC_ERR_INVALID_KEY_LEN
|
||||
|
||||
# fatal error -> raise PPYC_ERR
|
||||
try:
|
||||
AES(b"short") # invalid key length
|
||||
except PPYC_ERR as e:
|
||||
print(e.code) # 'PPYC_ERR_INVALID_KEY_LEN'
|
||||
print(e.message) # human-readable reason
|
||||
print(e.suggestion) # human-readable fix suggestion
|
||||
|
||||
# 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
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔐 Unified Error System
|
||||
|
||||
As of v3.2.0, library-wide errors are unified into two categories (see [`docs/errors.md`](docs/errors.md) for details):
|
||||
|
||||
| Type | Handling | Applicable scenarios |
|
||||
|------|----------|----------------------|
|
||||
| **Fatal error** | **Raise `PPYC_ERR`** | 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)` | Invalid input, failed validation, authentication failure, missing file, parse failure |
|
||||
|
||||
```python
|
||||
from purepycrypto import PPYC_ERR, err, ok, is_ok, is_err, OK_TUPLE, PPYC_ERR_INVALID_KEY_LEN
|
||||
|
||||
# fatal error
|
||||
raise PPYC_ERR(PPYC_ERR_INTERNAL, "state machine inconsistent", "please file an issue")
|
||||
|
||||
# non-fatal error (returns a tuple)
|
||||
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 check**:
|
||||
|
||||
```python
|
||||
result = some_api(...)
|
||||
if is_err(result): # generic check: works for any API
|
||||
code, msg, hint = result
|
||||
...
|
||||
else:
|
||||
value = result
|
||||
```
|
||||
|
||||
**Legacy exception names are still compatible** (all are subclasses of `PPYC_ERR`): `CryptoError` (default `PPYC_ERR_INTERNAL`),
|
||||
`DecryptionError` (default `PPYC_ERR_AUTH_FAILED`), `Ed25519Error` (default `PPYC_ERR_INVALID_ARG`).
|
||||
|
||||
**CLI exit codes**:
|
||||
|
||||
| Exit code | Meaning |
|
||||
|-----------|---------|
|
||||
| `0` | success |
|
||||
| `1` | other (e.g. `rsa --op verify` verification FAIL) |
|
||||
| `2` | `PPYC_ERR` (fatal error) |
|
||||
| `3` | file not found |
|
||||
| `4` | argument error |
|
||||
|
||||
---
|
||||
|
||||
## ✅ New in v3.2.0
|
||||
|
||||
> The following modules are officially available as of v3.2.0 and are all merged into the top-level exports.
|
||||
|
||||
| Module | Responsibility | Representative interfaces |
|
||||
|--------|----------------|---------------------------|
|
||||
| `purepycrypto.kdf2` | **Hardened key derivation** (stricter validation on top of `kdf`: minimum salt length, Argon2 encoded strings, etc.) | `pbkdf2`, `argon2id_hash` / `argon2id_verify`, `argon2id_hash_encoded` / `argon2_verify_encoded`, `scrypt_simple`, `hkdf_expand_multi` |
|
||||
| `purepycrypto.encoding` | **Pure-Python encoding** (byte-for-byte identical to the standard library) | `b64encode` / `b64decode` (including URL-safe / nopad), `b32encode` / `b32decode`, `hex_encode` / `hex_decode`, `b58encode` / `b58decode` |
|
||||
| `purepycrypto.rand` | **Cryptographically secure random (CSPRNG)** toolkit | `random_bytes` / `random_int`, `token_bytes` / `token_hex` / `token_urlsafe`, `random_password`, `random_uuid4`, `random_choice` / `random_sample` |
|
||||
|
||||
```python
|
||||
# example
|
||||
from purepycrypto import b64encode, b58encode, token_hex, random_password
|
||||
|
||||
print(b64encode(b"abc")) # b'YWJj'
|
||||
print(b58encode(b"\x00\x01\x02hello")) # b'13DgQxdPmp'
|
||||
print(token_hex(4)) # 8-char hex string
|
||||
print(random_password(16)) # random password
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## ⚠️ 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 |
|
||||
| `aes128/256_gcm_siv_encrypt(...)` | large input and `n_workers` is `None` (auto) or `> 1` |
|
||||
| `rsa_keygen(..., parallel=True)` | multiprocessing prime search enabled by default |
|
||||
|
||||
**Windows starts child processes via `spawn` (which re-imports the main module)**, so caller scripts **must** be wrapped in
|
||||
`if __name__ == "__main__":`, otherwise a `RuntimeError: ... bootstrapping phase` is raised.
|
||||
|
||||
### ✅ Correct pattern
|
||||
|
||||
```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()
|
||||
```
|
||||
|
||||
### ⛔ 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 and returns the correct result,
|
||||
> without crashing (but loses the speedup); the AES-GCM-SIV multiprocessing branch raises a `RuntimeError` 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 recommended to add the guard uniformly.
|
||||
|
||||
---
|
||||
|
||||
## 🌐 TUI Language Switch (CN / EN)
|
||||
|
||||
The TUI supports **Chinese/English interface switching**, **defaulting to English**.
|
||||
|
||||
```bash
|
||||
# Windows (cmd)
|
||||
set PUREPYCRYPTO_LANG=cn && purepycrypto
|
||||
# Windows (PowerShell)
|
||||
$env:PUREPYCRYPTO_LANG="cn"; purepycrypto
|
||||
# Linux / macOS
|
||||
PUREPYCRYPTO_LANG=cn purepycrypto
|
||||
# default (English)
|
||||
purepycrypto
|
||||
```
|
||||
|
||||
You can also switch it in the TUI menu, or call it in code:
|
||||
|
||||
```python
|
||||
from purepycrypto.cli import set_language, get_language
|
||||
set_language("cn") # or "en"
|
||||
print(get_language()) # 'cn' / 'en'
|
||||
```
|
||||
|
||||
> Values: `en` (default) / `cn`. An invalid value falls back to `en`.
|
||||
|
||||
---
|
||||
|
||||
## 📚 API Cheat Sheet
|
||||
|
||||
The complete API is in [`docs/api.md`](docs/api.md). Basic interfaces can be imported from the top-level `purepycrypto`,
|
||||
while SHA-3 / Ed25519 / AES-GCM-SIV etc. can be imported from their own submodules (or from the top level).
|
||||
|
||||
### Hashing
|
||||
|
||||
| Function | Signature |
|
||||
|----------|-----------|
|
||||
| `sha256` / `sha512` | `(message: bytes) -> bytes` |
|
||||
| `blake2b` | `(data: bytes, digest_size: int = 64) -> bytes` |
|
||||
| `sha3_224 / sha3_256 / sha3_384 / sha3_512` | `(data: bytes) -> bytes` |
|
||||
| `shake128 / shake256` | `(data: bytes, outlen: int) -> bytes` |
|
||||
| `sha3_batch` | `(items, algo="sha3_256", n_workers=None) -> list[bytes]` (v3.2.0) |
|
||||
|
||||
### KDF / MAC
|
||||
|
||||
| Function | Signature |
|
||||
|----------|-----------|
|
||||
| `hmac_sha256` / `hmac_sha512` | `(key: bytes, message: bytes) -> bytes` |
|
||||
| `hmac_sha3_256` / `hmac_sha3_512` | `(key: bytes, message: bytes) -> bytes` |
|
||||
| `pbkdf2_hmac` | `(password, salt, iterations, dklen, hash_name="sha256") -> bytes` |
|
||||
| `hkdf_extract` | `(salt, ikm, hash_name="sha256") -> bytes` |
|
||||
| `hkdf_expand` | `(prk, info, length, hash_name="sha256") -> bytes` |
|
||||
| `hkdf` | `(ikm, salt=b"", info=b"", length=32, hash_name="sha256") -> bytes` |
|
||||
| `scrypt` | `(password, salt, N=4096, r=8, p=1, dklen=32) -> bytes` |
|
||||
| `argon2id` | `(password, salt, t=1, m=256, p=1, tag_length=32, secret=b"", ad=b"", version=0x13) -> bytes` |
|
||||
| `poly1305_mac` | `(key32: bytes, msg: bytes) -> bytes` |
|
||||
|
||||
### Symmetric Encryption
|
||||
|
||||
| Interface | Description |
|
||||
|-----------|-------------|
|
||||
| `AES(key)` | construct an AES object (key is 16/24/32 bytes) |
|
||||
| `AES.gcm_encrypt(nonce, plaintext, aad=b"", n_workers=None)` | returns `(ciphertext, tag)` |
|
||||
| `AES.gcm_decrypt(nonce, ct, tag, aad=b"")` | returns the plaintext bytes on success, an error tuple on authentication failure |
|
||||
| `AES.encrypt_cbc / decrypt_cbc` | CBC (16-byte IV, automatic PKCS#7 padding) |
|
||||
| `AES.encrypt_ecb / decrypt_ecb` | ECB |
|
||||
| `AES.encrypt_ctr / decrypt_ctr` | CTR (8-byte nonce) |
|
||||
| `AES.encrypt_cfb / decrypt_cfb` | CFB |
|
||||
| `AES.encrypt_ofb / decrypt_ofb` | OFB |
|
||||
| `chacha20poly1305_encrypt / decrypt` | ChaCha20-Poly1305 (12-byte nonce) |
|
||||
| `xchacha20poly1305_encrypt / decrypt` | XChaCha20-Poly1305 (24-byte nonce) |
|
||||
| `aes_gcm_siv_encrypt / decrypt` | unified entry dispatched by key length (16/32) |
|
||||
| `aes128_gcm_siv_encrypt / decrypt` | AES-128-GCM-SIV (submodule `purepycrypto.aes_gcm_siv`) |
|
||||
| `aes256_gcm_siv_encrypt / decrypt` | AES-256-GCM-SIV (submodule) |
|
||||
| `set_cache_enabled / cache_enabled / clear_caches` | GCM-SIV cache control (v3.2.0) |
|
||||
|
||||
### Public Key
|
||||
|
||||
| Interface | Signature |
|
||||
|-----------|-----------|
|
||||
| `x25519` | `(k: bytes, u: bytes) -> bytes` (invalid input returns an error tuple) |
|
||||
| `x25519_base` | `(scalar: bytes) -> bytes` |
|
||||
| `x25519_shared` | `(priv, peer_pub) -> (shared, is_zero)` |
|
||||
| `x25519_generate_keypair` | `() -> (priv, pub)` |
|
||||
| `rsa_keygen` | `(bits=2048, parallel=True) -> (RSAPublicKey, RSAPrivateKey)` |
|
||||
| `rsa_oaep_encrypt` | `(message, pub, label=b"") -> bytes` |
|
||||
| `rsa_oaep_decrypt` | `(ciphertext, priv, label=b"") -> bytes` |
|
||||
| `rsa_pss_sign` | `(message, priv, salt_len=None) -> bytes` |
|
||||
| `rsa_pss_verify` | `(message, signature, pub, salt_len=None) -> bool` |
|
||||
| `ed25519_keygen` | `() -> (seed32, pub32)` |
|
||||
| `ed25519_publickey` | `(seed32: bytes) -> bytes` |
|
||||
| `ed25519_sign` | `(message: bytes, seed32: bytes) -> bytes` (64 bytes) |
|
||||
| `ed25519_verify` | `(signature64, message, pub32) -> bool` |
|
||||
| `private_key_to_pem` / `public_key_to_pem` | `(key) -> str` |
|
||||
| `parse_private_pem` | `(pem: str) -> RSAPrivateKey` |
|
||||
| `private_key_to_pkcs8_der` / `public_key_to_spki_der` | `(key) -> bytes` |
|
||||
| `private_key_to_pkcs1_der` / `public_key_to_pkcs1_der` | `(key) -> bytes` |
|
||||
|
||||
### Utilities and Errors
|
||||
|
||||
| Interface | Description |
|
||||
|-----------|-------------|
|
||||
| `rand_bytes(n)` | returns `n` bytes of cryptographically secure random data (`os.urandom`) |
|
||||
| `rand_int(a, b)` | returns a uniformly random integer in `[a, b]` (rejection sampling) |
|
||||
| `PPYC_ERR` / `PPYCError` | fatal-error exception (carries code/message/suggestion) |
|
||||
| `CryptoError` / `DecryptionError` / `Ed25519Error` | legacy exception names (subclasses of `PPYC_ERR`) |
|
||||
| `err` / `ok` / `is_ok` / `is_err` / `raise_ppyc` / `OK_TUPLE` / `PPYCResult` | non-fatal error helpers |
|
||||
| `ALL_ERROR_CODES` | all 41 error code constants (tuple) |
|
||||
|
||||
---
|
||||
|
||||
## 🔐 Security Notes
|
||||
|
||||
This section is a summary; the full statement is in [`docs/security.md`](docs/security.md).
|
||||
|
||||
- **Randomness source**: all random bytes come from `os.urandom()` (the OS CSPRNG); the library does **not** contain any PRNG that can be seeded.
|
||||
- **Constant-time comparison**: sensitive comparisons (Tag / MAC / shared key) use `_consttime_eq` / `_consttime_int_eq` to avoid early-return timing differences.
|
||||
- **X25519 low-order point detection**: `x25519_shared` returns `is_zero`; callers **must** check it and reject an all-zero result.
|
||||
- **AEAD authentication**: GCM / ChaCha20-Poly1305 / XChaCha20-Poly1305 / AES-GCM-SIV **return an error tuple**
|
||||
on authentication failure (`PPYC_ERR_AUTH_FAILED`) and **never return unauthenticated plaintext**.
|
||||
- **Error codes do not leak sensitive information**: error codes and messages describe only the **category and fix suggestion**, never key / nonce / plaintext content (see `docs/security.md`).
|
||||
- **RSA blinding**: the private-key decryption path includes blinding to mitigate timing side-channel risk.
|
||||
- **Ed25519 signatures**: Pure EdDSA (RFC 8032); scalar multiplication uses a masked lookup-table constant-time approach (best-effort).
|
||||
- ⚠️ **Do not use it for highly adversarial, long-running production-critical systems**. Pure Python cannot guarantee memory zeroization and cannot fully eliminate timing / branch / cache side channels.
|
||||
|
||||
---
|
||||
|
||||
## ⚠️ Known Limitations
|
||||
|
||||
1. **Performance**: pure-Python throughput is far below C implementations that call OpenSSL; large-file encryption/decryption and high-parameter PBKDF2/Argon2id will be noticeably slow.
|
||||
2. **Side channels**: core comparisons and X25519/Ed25519 scalar multiplication have constant-time handling, but the Python interpreter's own branching, object allocation, and big-integer arithmetic timing cannot be fully controlled, making it **unsuitable for strongly adversarial scenarios that directly face untrusted input**.
|
||||
3. **Memory zeroization**: Python has no reliable memory-erasure mechanism; keys may remain in heap memory until GC.
|
||||
4. **Algorithm scope**: includes SHA-3/SHAKE, Ed25519, and AES-GCM-SIV; **excludes any post-quantum (PQC) algorithm**.
|
||||
5. **nonce length**: `gcm_encrypt` uses a 96-bit (12-byte) nonce; CTR uses an 8-byte nonce; do not reuse a nonce under the same key.
|
||||
6. **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.
|
||||
7. **Minimum RSA size**: `rsa_keygen` requires `bits >= 521`; below this a `PPYC_ERR` is raised.
|
||||
|
||||
---
|
||||
|
||||
## 🧪 Testing
|
||||
|
||||
```bash
|
||||
# run all tests (tests live in the in-package purepycrypto/tests)
|
||||
pytest purepycrypto/tests -q
|
||||
```
|
||||
|
||||
Standard vectors covered by the tests (NIST / RFC):
|
||||
|
||||
- SHA-256 / SHA-512 (FIPS 180-4), BLAKE2b (RFC 7693)
|
||||
- HMAC-SHA256 / 512 (RFC 4231), PBKDF2 (RFC 6070), HKDF (RFC 5869), scrypt (RFC 7914), Argon2id (RFC 9106)
|
||||
- SHA-3 / SHAKE (FIPS 202, cross-verified against `hashlib`)
|
||||
- AES (FIPS 197) and GCM (NIST SP 800-38D)
|
||||
- ChaCha20 / Poly1305 / ChaCha20-Poly1305 (RFC 8439)
|
||||
- X25519 (RFC 7748), Ed25519 (RFC 8032 §7.1), AES-GCM-SIV (RFC 8452)
|
||||
- RSA-OAEP / PSS (RFC 8017)
|
||||
- Unified error system `test_errors.py` / `test_errors_edge.py`
|
||||
|
||||
---
|
||||
|
||||
## ❓ FAQ
|
||||
|
||||
**Q: Why not use the `hashlib` / `hmac` standard libraries?**
|
||||
A: This library is positioned as a "pure-Python auditable implementation"; hashing and HMAC are also implemented from scratch to keep the algorithm logic fully visible and portable. If you only care about performance, the standard library or `cryptography` is more suitable.
|
||||
|
||||
**Q: How does the `AES(key)` key length determine the variant?**
|
||||
A: 16 → AES-128; 24 → AES-192; 32 → AES-256. Any other length raises `PPYC_ERR(PPYC_ERR_INVALID_KEY_LEN)`.
|
||||
|
||||
**Q: Does authentication failure raise an exception or return an error?**
|
||||
A: As of v3.2.0, `gcm_decrypt` / `chacha*decrypt` etc. **return a 3-tuple** `(code, msg, hint)` (`code` is `PPYC_ERR_AUTH_FAILED`); check with `is_err()`. The historical name `DecryptionError` can still be caught.
|
||||
|
||||
**Q: Why does X25519 return `is_zero`?**
|
||||
A: When the shared secret is all zeros it means the peer public key is a low-order point and the shared secret is unsafe, so it **must be rejected** (RFC 7748 §6.1).
|
||||
|
||||
**Q: Can it be used for both signing and encryption?**
|
||||
A: Yes. Use RSA-PSS or Ed25519 for signing, and RSA-OAEP for encryption; the two use different padding schemes, so do not mix them.
|
||||
|
||||
**Q: Are there multiple command-line entry points?**
|
||||
A: There is only one command, `purepycrypto`: no arguments launches the TUI, arguments enter the command line (subcommands `hash` / `hmac` / `kdf` / `aes` / `chacha` / `x25519` / `rsa` / `rand` / `selftest` / `version`).
|
||||
|
||||
**Q: Is Ed25519 available?**
|
||||
A: **Yes.** `ed25519_keygen` / `ed25519_sign` / `ed25519_verify`. It still does **not provide** any post-quantum algorithm.
|
||||
|
||||
---
|
||||
|
||||
## 🤝 Contributing
|
||||
|
||||
1. New algorithms must come with **standard test vectors** (RFC / FIPS / NIST) and test cases added under `purepycrypto/tests/`.
|
||||
2. Keep **zero third-party dependencies** (standard library only).
|
||||
3. Use constant-time functions for sensitive comparisons; use `os.urandom` for randomness.
|
||||
4. **Follow the unified error system**: parameter validation / authentication failure → `return err(...)`; internal contradiction → `raise PPYC_ERR(...)`; do not invent error codes.
|
||||
5. Code must pass `pytest -q`. Commit messages and documentation may be in Chinese or English; code identifiers stay in English.
|
||||
|
||||
---
|
||||
|
||||
## 📄 License
|
||||
|
||||
This project is released under the **MIT License**. See [`LICENSE`](LICENSE) for details.
|
||||
|
||||
---
|
||||
|
||||
## 👤 Author
|
||||
|
||||
**Dvs(DvsXT)** — self-developed cryptography library · purepycrypto
|
||||
|
||||
- Email: dvs6666@163.com
|
||||
- Project homepage: https://apds.top
|
||||
|
||||
> 💡 **Disclaimer**: This library is designed for learning, experimentation, teaching, and embedded prototypes, and the author accepts no liability for any direct or indirect loss caused by its use.
|
||||
> For production-critical scenarios, please prefer implementations that have been widely audited and maintained by professional cryptography engineering teams.
|
||||
|
||||
---
|
||||
|
||||
<div align="center">
|
||||
|
||||
**purepycrypto v3.2.0** · Made with ❤️ by **Dvs(DvsXT)**
|
||||
|
||||
</div>
|
||||
+1588
File diff suppressed because it is too large
Load Diff
+454
@@ -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
@@ -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`.*
|
||||
@@ -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.
|
||||
@@ -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.**
|
||||
@@ -0,0 +1,389 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
purepycrypto
|
||||
============
|
||||
Pure-Python cryptography library (zero third-party dependencies) - developed by Dvs(DvsXT).
|
||||
|
||||
Hash
|
||||
----
|
||||
- SHA-256 / SHA-512 / BLAKE2b (``hash``)
|
||||
- SHA-3 / Keccak / SHAKE, HMAC-SHA3 (``sha3``)
|
||||
|
||||
Key derivation
|
||||
--------
|
||||
- HMAC-SHA256/512, PBKDF2, HKDF, scrypt, Argon2id (``kdf``)
|
||||
|
||||
Symmetric encryption
|
||||
--------
|
||||
- AES-128/192/256: ECB / CBC / CTR / CFB / OFB / GCM (``aes``)
|
||||
- AES-GCM-SIV (RFC 8452, nonce-misuse resistant) (``aes_gcm_siv``)
|
||||
- ChaCha20-Poly1305 / XChaCha20-Poly1305 (``chacha``)
|
||||
|
||||
Public key
|
||||
----
|
||||
- X25519 (RFC 7748) (``x25519``)
|
||||
- Ed25519 (RFC 8032) (``ed25519``)
|
||||
- RSA: keygen / OAEP / PSS / PEM (``rsa``)
|
||||
- ASN.1 DER / PEM (``der``)
|
||||
|
||||
Utilities
|
||||
----
|
||||
- Constant-time comparison, secure random, multiprocessing (``common`` / ``parallel``)
|
||||
|
||||
Usage
|
||||
----
|
||||
from purepycrypto import sha256, sha3_256, AES, ed25519_sign
|
||||
|
||||
digest = sha256(b"hello")
|
||||
aes = AES(b"0" * 16)
|
||||
ct, tag = aes.gcm_encrypt(b"\\x00" * 12, b"secret")
|
||||
|
||||
Command line
|
||||
------
|
||||
One command, two modes (call it directly after install, no python -m needed):
|
||||
|
||||
purepycrypto # no args -> interactive TUI
|
||||
purepycrypto hash --algo sha256 --text abc --hex # with args -> CLI
|
||||
purepycrypto --help # CLI help
|
||||
purepycrypto version # show version
|
||||
purepycrypto selftest # run built-in self-test
|
||||
|
||||
Equivalent invocation (when not installed):
|
||||
|
||||
python -m purepycrypto # TUI
|
||||
python -m purepycrypto hash --text abc --hex # CLI
|
||||
"""
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Public API exports
|
||||
# ------------------------------------------------------------------
|
||||
# ---- Unified error system (the single place where errors are defined) ----
|
||||
from ._ppyc_error import (
|
||||
PPYC_ERR,
|
||||
PPYCError,
|
||||
CryptoError,
|
||||
DecryptionError,
|
||||
Ed25519Error,
|
||||
ok, err, is_ok, is_err, raise_ppyc, OK_TUPLE,
|
||||
PPYCResult,
|
||||
ALL_ERROR_CODES,
|
||||
PPYC_ERR_PREFIX,
|
||||
)
|
||||
|
||||
from .common import (
|
||||
_consttime_eq,
|
||||
_consttime_int_eq,
|
||||
_consttime_select,
|
||||
rand_int,
|
||||
rand_bytes,
|
||||
MASK32, MASK64, MASK128,
|
||||
POLY1305_P,
|
||||
GHASH_R,
|
||||
R_CONST,
|
||||
)
|
||||
|
||||
from .hash import sha256, sha512, blake2b
|
||||
|
||||
from .kdf import (
|
||||
hmac_sha256,
|
||||
hmac_sha512,
|
||||
pbkdf2_hmac,
|
||||
hkdf,
|
||||
hkdf_extract,
|
||||
hkdf_expand,
|
||||
scrypt,
|
||||
argon2id,
|
||||
)
|
||||
|
||||
from .aes import AES
|
||||
|
||||
from .chacha import (
|
||||
poly1305_mac,
|
||||
chacha20poly1305_encrypt,
|
||||
chacha20poly1305_decrypt,
|
||||
xchacha20poly1305_encrypt,
|
||||
xchacha20poly1305_decrypt,
|
||||
)
|
||||
|
||||
from .x25519 import (
|
||||
x25519,
|
||||
x25519_base,
|
||||
x25519_shared,
|
||||
x25519_generate_keypair,
|
||||
)
|
||||
|
||||
from .rsa import (
|
||||
RSAPublicKey,
|
||||
RSAPrivateKey,
|
||||
rsa_keygen,
|
||||
rsa_oaep_encrypt,
|
||||
rsa_oaep_decrypt,
|
||||
rsa_pss_sign,
|
||||
rsa_pss_verify,
|
||||
)
|
||||
|
||||
from .der import (
|
||||
private_key_to_pkcs1_der,
|
||||
public_key_to_pkcs1_der,
|
||||
private_key_to_pkcs8_der,
|
||||
public_key_to_spki_der,
|
||||
private_key_to_pem,
|
||||
public_key_to_pem,
|
||||
parse_private_pem,
|
||||
)
|
||||
|
||||
from .parallel import _HAS_MP
|
||||
|
||||
# ---- Algorithms added in v1.1 (optional: skipped if the module is missing, for gradual upgrades) ----
|
||||
try:
|
||||
from .sha3 import (
|
||||
sha3_224, sha3_256, sha3_384, sha3_512,
|
||||
shake128, shake256,
|
||||
hmac_sha3_256, hmac_sha3_512,
|
||||
sha3_batch,
|
||||
)
|
||||
_HAS_SHA3 = True
|
||||
except ImportError:
|
||||
_HAS_SHA3 = False
|
||||
|
||||
try:
|
||||
from .ed25519 import (
|
||||
ed25519_keygen,
|
||||
ed25519_publickey,
|
||||
ed25519_sign,
|
||||
ed25519_verify,
|
||||
)
|
||||
_HAS_ED25519 = True
|
||||
except ImportError:
|
||||
_HAS_ED25519 = False
|
||||
|
||||
try:
|
||||
from .aes_gcm_siv import (
|
||||
aes128_gcm_siv_encrypt,
|
||||
aes128_gcm_siv_decrypt,
|
||||
aes256_gcm_siv_encrypt,
|
||||
aes256_gcm_siv_decrypt,
|
||||
aes_gcm_siv_encrypt,
|
||||
aes_gcm_siv_decrypt,
|
||||
set_cache_enabled,
|
||||
cache_enabled,
|
||||
clear_caches,
|
||||
)
|
||||
_HAS_GCM_SIV = True
|
||||
except ImportError:
|
||||
_HAS_GCM_SIV = False
|
||||
|
||||
# ---- Modules added in v3.2.0 (optional: skipped when the module is missing, for gradual upgrades) ----
|
||||
try:
|
||||
from .kdf2 import (
|
||||
pbkdf2, argon2id_hash, argon2id_verify, argon2i_hash, argon2d_hash,
|
||||
argon2id_hash_encoded, scrypt_simple,
|
||||
)
|
||||
_HAS_KDF2 = True
|
||||
except ImportError:
|
||||
_HAS_KDF2 = False
|
||||
|
||||
try:
|
||||
from .encoding import (
|
||||
b64encode, b64decode, b64encode_urlsafe, b64decode_urlsafe,
|
||||
b64encode_nopad, b64decode_nopad,
|
||||
b32encode, b32decode, b32encode_hex, b32decode_hex,
|
||||
hex_encode, hex_decode, hex_encode_sep, hex_decode_sep,
|
||||
b58encode, b58decode,
|
||||
)
|
||||
_HAS_ENCODING = True
|
||||
except ImportError:
|
||||
_HAS_ENCODING = False
|
||||
|
||||
try:
|
||||
from .rand import (
|
||||
random_bytes, random_int, random_below, random_bit, random_bits,
|
||||
token_bytes, token_hex, token_urlsafe,
|
||||
random_string, random_password, random_uuid4,
|
||||
random_choice, random_sample,
|
||||
)
|
||||
_HAS_RAND = True
|
||||
except ImportError:
|
||||
_HAS_RAND = False
|
||||
|
||||
try:
|
||||
from ._version import __version__
|
||||
except ImportError: # fallback when _version.py has not been generated in a dev environment
|
||||
__version__ = "3.2.0"
|
||||
|
||||
__author__ = "Dvs(DvsXT)"
|
||||
__license__ = "MIT"
|
||||
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Entry points: reuse the single-file build from build_single or the in-package entry modules
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def run_tui(argv=None):
|
||||
"""Start the interactive TUI.
|
||||
|
||||
Prefers the in-package ``purepycrypto.cli``; if unavailable (e.g. a trimmed distribution),
|
||||
it falls back to generating and running a single-file TUI build via ``scripts.build_single``.
|
||||
"""
|
||||
try:
|
||||
from . import cli
|
||||
return cli._tui_main()
|
||||
except ImportError:
|
||||
return _run_from_build_single("tui", argv)
|
||||
|
||||
|
||||
def run_cli(argv=None):
|
||||
"""Run the command-line argument version (subcommands: hash/kdf/aes/x25519/rsa/...).
|
||||
|
||||
Prefers the in-package ``purepycrypto.cli_args``; otherwise falls back to the single-file CLI build from build_single.
|
||||
"""
|
||||
try:
|
||||
from . import cli_args
|
||||
return cli_args._cli_main(argv)
|
||||
except ImportError:
|
||||
return _run_from_build_single("cli", argv)
|
||||
|
||||
|
||||
def _run_from_build_single(mode, argv=None):
|
||||
"""Fallback path: generate and execute a single-file build of the given mode via scripts/build_single.
|
||||
|
||||
This guarantees that even if the package layout is trimmed, as long as scripts/build_single.py is
|
||||
reachable, the full TUI / CLI remains available. build_single itself can also be run standalone.
|
||||
"""
|
||||
import os
|
||||
import runpy
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
here = os.path.dirname(os.path.abspath(__file__))
|
||||
build_script = os.path.join(here, "scripts", "build_single.py")
|
||||
if not os.path.exists(build_script):
|
||||
raise SystemExit(
|
||||
"[✗] Neither the cli/cli_args module nor scripts/build_single.py is available; "
|
||||
"cannot start " + mode + "."
|
||||
)
|
||||
|
||||
out_dir = tempfile.mkdtemp(prefix="purepycrypto_")
|
||||
out_file = os.path.join(out_dir, "purepycrypto_%s.py" % mode)
|
||||
|
||||
# Invoke build_single to generate the single file (subprocess, avoids polluting this namespace)
|
||||
rc = subprocess.call([sys.executable, build_script, "--mode", mode, "-o", out_file])
|
||||
if rc != 0 or not os.path.exists(out_file):
|
||||
raise SystemExit("[✗] build_single failed to generate " + mode)
|
||||
|
||||
# Run the single file; in CLI mode pass argv through
|
||||
if mode == "cli" and argv is not None:
|
||||
return subprocess.call([sys.executable, out_file] + list(argv))
|
||||
return runpy.run_path(out_file, run_name="__main__")
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
"""Unified entry point (serves both the console script ``purepycrypto`` and ``python -m purepycrypto``).
|
||||
|
||||
Behavior
|
||||
----
|
||||
* ``purepycrypto`` (no args) -> start the interactive TUI
|
||||
* ``purepycrypto --help`` (with args) -> CLI help
|
||||
* ``purepycrypto hash --algo ...``(with args) -> CLI mode
|
||||
* ``purepycrypto tui`` (explicit) -> start the TUI
|
||||
* ``purepycrypto cli ...`` (legacy form) -> CLI mode
|
||||
|
||||
That is: **one command -- no args enters the TUI, args go to the CLI**.
|
||||
"""
|
||||
import sys
|
||||
|
||||
argv = list(sys.argv[1:] if argv is None else argv)
|
||||
|
||||
# No args -> TUI
|
||||
if not argv:
|
||||
return run_tui([])
|
||||
|
||||
first = argv[0]
|
||||
|
||||
# Explicit legacy form compatibility
|
||||
if first == "tui":
|
||||
return run_tui(argv[1:])
|
||||
if first == "cli":
|
||||
return run_cli(argv[1:])
|
||||
|
||||
# Any other args (subcommand, or --help/-h/-V/--version, etc.) -> CLI mode
|
||||
return run_cli(argv)
|
||||
|
||||
|
||||
__all__ = [
|
||||
# Unified error system
|
||||
"PPYC_ERR", "PPYCError", "CryptoError", "DecryptionError", "Ed25519Error",
|
||||
"ok", "err", "is_ok", "is_err", "raise_ppyc", "OK_TUPLE", "PPYCResult",
|
||||
"ALL_ERROR_CODES", "PPYC_ERR_PREFIX",
|
||||
# common
|
||||
"rand_int", "rand_bytes",
|
||||
"MASK32", "MASK64", "MASK128", "POLY1305_P", "GHASH_R", "R_CONST",
|
||||
# hash
|
||||
"sha256", "sha512", "blake2b",
|
||||
# kdf
|
||||
"hmac_sha256", "hmac_sha512", "pbkdf2_hmac",
|
||||
"hkdf", "hkdf_extract", "hkdf_expand", "scrypt", "argon2id",
|
||||
# aes
|
||||
"AES",
|
||||
# chacha
|
||||
"poly1305_mac",
|
||||
"chacha20poly1305_encrypt", "chacha20poly1305_decrypt",
|
||||
"xchacha20poly1305_encrypt", "xchacha20poly1305_decrypt",
|
||||
# x25519
|
||||
"x25519", "x25519_base", "x25519_shared", "x25519_generate_keypair",
|
||||
# rsa
|
||||
"RSAPublicKey", "RSAPrivateKey", "rsa_keygen",
|
||||
"rsa_oaep_encrypt", "rsa_oaep_decrypt", "rsa_pss_sign", "rsa_pss_verify",
|
||||
# der
|
||||
"private_key_to_pkcs1_der", "public_key_to_pkcs1_der",
|
||||
"private_key_to_pkcs8_der", "public_key_to_spki_der",
|
||||
"private_key_to_pem", "public_key_to_pem", "parse_private_pem",
|
||||
# Entry points
|
||||
"run_tui", "run_cli", "main",
|
||||
# meta
|
||||
"__version__", "__author__", "__license__",
|
||||
]
|
||||
|
||||
# v1.1 algorithms (added to __all__ when present)
|
||||
if _HAS_SHA3:
|
||||
__all__ += ["sha3_224", "sha3_256", "sha3_384", "sha3_512",
|
||||
"shake128", "shake256", "hmac_sha3_256", "hmac_sha3_512",
|
||||
"sha3_batch"]
|
||||
if _HAS_ED25519:
|
||||
__all__ += ["ed25519_keygen", "ed25519_publickey",
|
||||
"ed25519_sign", "ed25519_verify"]
|
||||
if _HAS_GCM_SIV:
|
||||
__all__ += ["aes128_gcm_siv_encrypt", "aes128_gcm_siv_decrypt",
|
||||
"aes256_gcm_siv_encrypt", "aes256_gcm_siv_decrypt",
|
||||
"aes_gcm_siv_encrypt", "aes_gcm_siv_decrypt",
|
||||
"set_cache_enabled", "cache_enabled", "clear_caches"]
|
||||
|
||||
# v3.2.0 module exports
|
||||
if _HAS_KDF2:
|
||||
__all__ += ["pbkdf2", "argon2id_hash", "argon2id_verify",
|
||||
"argon2i_hash", "argon2d_hash", "argon2id_hash_encoded",
|
||||
"scrypt_simple"]
|
||||
if _HAS_ENCODING:
|
||||
__all__ += ["b64encode", "b64decode", "b64encode_urlsafe", "b64decode_urlsafe",
|
||||
"b64encode_nopad", "b64decode_nopad",
|
||||
"b32encode", "b32decode", "b32encode_hex", "b32decode_hex",
|
||||
"hex_encode", "hex_decode", "hex_encode_sep", "hex_decode_sep",
|
||||
"b58encode", "b58decode"]
|
||||
if _HAS_RAND:
|
||||
__all__ += ["random_bytes", "random_int", "random_below", "random_bit",
|
||||
"random_bits", "token_bytes", "token_hex", "token_urlsafe",
|
||||
"random_string", "random_password", "random_uuid4",
|
||||
"random_choice", "random_sample"]
|
||||
|
||||
# Export all error code constants (PPYC_ERR_xxx) so users can reference them directly
|
||||
# Note: the constant names must actually be imported into this namespace for "from purepycrypto import PPYC_ERR_xxx" to work
|
||||
from . import _ppyc_error as _ppyc_error_mod
|
||||
for _name in dir(_ppyc_error_mod):
|
||||
if _name.startswith("PPYC_ERR_") and _name != "PPYC_ERR_PREFIX":
|
||||
globals()[_name] = getattr(_ppyc_error_mod, _name)
|
||||
if _name not in __all__:
|
||||
__all__.append(_name)
|
||||
del _name
|
||||
|
||||
__version_tuple__ = tuple(int(x) for x in __version__.split(".")[:3])
|
||||
@@ -0,0 +1,20 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""``python -m purepycrypto`` entry point (behaves the same as the console script ``purepycrypto``).
|
||||
|
||||
Usage
|
||||
-----
|
||||
python -m purepycrypto # no arguments -> interactive TUI
|
||||
python -m purepycrypto hash --algo sha256 --text abc --hex # with arguments -> CLI
|
||||
python -m purepycrypto --help # help for the argument-based CLI
|
||||
|
||||
After installation you can use the same-named command (located in the Python Scripts directory):
|
||||
|
||||
purepycrypto # TUI
|
||||
purepycrypto hash --text abc --hex # CLI
|
||||
"""
|
||||
import sys
|
||||
|
||||
from . import main
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main() or 0)
|
||||
@@ -0,0 +1,330 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
purepycrypto._ppyc_error
|
||||
========================
|
||||
purepycrypto - Pure-Python cryptography library (zero dependencies)
|
||||
[Unified error system] -- the single error definition and return contract for the whole library.
|
||||
|
||||
Design principles
|
||||
--------
|
||||
This library strictly divides errors into two classes, with clear and non-overlapping semantics:
|
||||
|
||||
1) **Fatal errors (unrecoverable) -> raise ``PPYC_ERR``**
|
||||
Raised when the program can no longer run safely. Typical cases:
|
||||
- internal logic inconsistency / broken invariant (a bug in this library)
|
||||
- fatal environment problem (e.g. cannot allocate memory, or a required dependency is missing)
|
||||
- caller-supplied data at initialization time makes the whole object impossible to build
|
||||
Callers **must not** use try/except to "swallow" such errors and continue; let them bubble up to expose the problem.
|
||||
|
||||
2) **Non-fatal errors (expected, recoverable) -> return a 3-tuple**
|
||||
``(error_code, error_message, suggestion)``
|
||||
Returned for **expected** conditions such as invalid input, failed validation, authentication failure or a missing file,
|
||||
instead of raising an exception. Callers can handle it cleanly by checking the return value:
|
||||
|
||||
code, msg, hint = ppyc_result(...)
|
||||
if code is not None:
|
||||
print(code, msg, hint) # e.g. PPYC_ERR_INVALID_KEY_LEN ...
|
||||
else:
|
||||
... # continue normally
|
||||
|
||||
Contract:
|
||||
- ``error_code`` : ``str``, always formatted as ``PPYC_ERR_xxx``; **None on success**
|
||||
- ``error_message`` : ``str``, short human-readable reason
|
||||
- ``suggestion`` : ``str``, human-readable remediation hint ("what to do"), may be an empty string
|
||||
|
||||
On success all three elements are ``None``: ``(None, None, None)``.
|
||||
|
||||
Error code naming
|
||||
----------
|
||||
A common prefix ``PPYC_ERR_`` followed by an upper-case snake_case category, for example:
|
||||
|
||||
PPYC_ERR_INVALID_KEY_LEN invalid key length
|
||||
PPYC_ERR_INVALID_NONCE_LEN invalid nonce length
|
||||
PPYC_ERR_INVALID_ARG invalid generic argument
|
||||
PPYC_ERR_AUTH_FAILED authentication failure (AEAD tag / signature check failed)
|
||||
PPYC_ERR_INVALID_PADDING invalid padding
|
||||
PPYC_ERR_FILE_NOT_FOUND file not found
|
||||
PPYC_ERR_UNSUPPORTED unsupported feature / value
|
||||
PPYC_ERR_INTERNAL internal error (should raise PPYC_ERR, not return)
|
||||
|
||||
Usage
|
||||
----
|
||||
from purepycrypto._ppyc_error import (
|
||||
PPYC_ERR, ok, err, is_ok, raise_ppyc,
|
||||
PPYC_ERR_INVALID_KEY_LEN,
|
||||
)
|
||||
|
||||
# 1) Fatal error
|
||||
raise PPYC_ERR(PPYC_ERR_INTERNAL, "inconsistent state machine", "please file an issue")
|
||||
|
||||
# 2) Non-fatal error (returns a tuple)
|
||||
if len(key) not in (16, 24, 32):
|
||||
return err(PPYC_ERR_INVALID_KEY_LEN,
|
||||
f"AES key length must be 16/24/32 bytes, got {len(key)}",
|
||||
"pass a 16, 24 or 32 byte key")
|
||||
...
|
||||
return ok(value)
|
||||
|
||||
Notes
|
||||
----
|
||||
- This module is the **single** place where errors are defined; all other modules import
|
||||
from here and must not define their own exception classes or error-code string literals.
|
||||
- For backward compatibility, legacy names such as ``CryptoError`` / ``DecryptionError`` still exist,
|
||||
but they are now **aliases** of ``PPYC_ERR`` (see the alias section below) and carry
|
||||
the ``code`` / ``message`` / ``suggestion`` attributes.
|
||||
"""
|
||||
|
||||
from typing import Any, Optional, Tuple
|
||||
|
||||
__all__ = [
|
||||
# Exception classes
|
||||
"PPYC_ERR",
|
||||
"CryptoError", "DecryptionError", "Ed25519Error", "PPYCError",
|
||||
# Tuple helpers
|
||||
"ok", "err", "is_ok", "is_err", "raise_ppyc",
|
||||
"PPYCResult",
|
||||
# Error code base
|
||||
"PPYC_ERR_PREFIX",
|
||||
# Error code constants (see the full list below)
|
||||
] + [] # error code constants are appended to __all__ at the end of the file
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# 1. Fatal errors: PPYC_ERR
|
||||
# ======================================================================
|
||||
|
||||
class PPYC_ERR(Exception):
|
||||
"""Unified purepycrypto exception (**fatal error**).
|
||||
|
||||
Raised only when the program can no longer run safely. For expected input errors /
|
||||
authentication failures, use :func:`err` to return an ``(error_code, error_message, suggestion)`` tuple instead.
|
||||
|
||||
Parameters
|
||||
----
|
||||
code : str
|
||||
Error code formatted as ``PPYC_ERR_xxx``. Use the constants below, or a custom string with the same prefix.
|
||||
message : str
|
||||
Human-readable reason.
|
||||
suggestion : str
|
||||
Human-readable remediation hint; may be an empty string.
|
||||
|
||||
Attributes
|
||||
----
|
||||
code / message / suggestion : str
|
||||
"""
|
||||
|
||||
def __init__(self, code: str = "PPYC_ERR_INTERNAL",
|
||||
message: str = "", suggestion: str = ""):
|
||||
self.code = code
|
||||
self.message = message
|
||||
self.suggestion = suggestion
|
||||
super().__init__(self._format())
|
||||
|
||||
def _format(self) -> str:
|
||||
parts = [f"[{self.code}] {self.message}"]
|
||||
if self.suggestion:
|
||||
parts.append(f"Suggestion: {self.suggestion}")
|
||||
return " ".join(parts)
|
||||
|
||||
def as_tuple(self) -> Tuple[str, str, str]:
|
||||
"""Convert to a ``(code, message, suggestion)`` tuple."""
|
||||
return (self.code, self.message, self.suggestion)
|
||||
|
||||
def __str__(self) -> str: # pragma: no cover - for debugging convenience
|
||||
return self._format()
|
||||
|
||||
def __repr__(self) -> str: # pragma: no cover
|
||||
return (f"PPYC_ERR(code={self.code!r}, message={self.message!r}, "
|
||||
f"suggestion={self.suggestion!r})")
|
||||
|
||||
|
||||
def raise_ppyc(code: str, message: str, suggestion: str = "") -> None:
|
||||
"""Raise :class:`PPYC_ERR` (helper for `if ...: return raise_ppyc(...)` style usage)."""
|
||||
raise PPYC_ERR(code, message, suggestion)
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# Legacy exception name compatibility (all aliases of PPYC_ERR, carrying code/message/suggestion)
|
||||
# ----------------------------------------------------------------------
|
||||
class CryptoError(PPYC_ERR):
|
||||
"""Generic cryptography error (legacy name, equivalent to :class:`PPYC_ERR`)."""
|
||||
def __init__(self, message: str = "", code: str = "PPYC_ERR_INTERNAL",
|
||||
suggestion: str = ""):
|
||||
# Supports both call styles: CryptoError("msg") / CryptoError(code, msg, hint)
|
||||
super().__init__(code, message, suggestion)
|
||||
|
||||
|
||||
class DecryptionError(PPYC_ERR):
|
||||
"""Decryption / authentication failure (legacy name).
|
||||
|
||||
Note: per the library-wide contract, "authentication failure" is a **non-fatal error**;
|
||||
prefer :func:`err`, which returns a tuple. This class is kept only for compatibility with existing APIs and code.
|
||||
"""
|
||||
def __init__(self, message: str = "", code: str = "PPYC_ERR_AUTH_FAILED",
|
||||
suggestion: str = "check that the key and nonce/AAD match, or whether the data was tampered with"):
|
||||
super().__init__(code, message, suggestion)
|
||||
|
||||
|
||||
class Ed25519Error(PPYC_ERR):
|
||||
"""Ed25519 parameter / encoding error (legacy name)."""
|
||||
def __init__(self, message: str = "", code: str = "PPYC_ERR_INVALID_ARG",
|
||||
suggestion: str = ""):
|
||||
super().__init__(code, message, suggestion)
|
||||
|
||||
|
||||
# Generic alias (easier to remember)
|
||||
PPYCError = PPYC_ERR
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# 2. Non-fatal errors: 3-tuple return
|
||||
# ======================================================================
|
||||
|
||||
#: Return type for non-fatal errors: ``(error_code | None, error_message | None, suggestion | None)``
|
||||
PPYCResult = Tuple[Optional[str], Optional[str], Optional[str]]
|
||||
|
||||
_OK: PPYCResult = (None, None, None)
|
||||
|
||||
|
||||
def ok(value: Any = None) -> Any:
|
||||
"""Construct a success return.
|
||||
|
||||
Note: this library represents "non-fatal errors" as a 3-tuple, while the **form of a successful
|
||||
return value is decided by each API** (it may be plaintext bytes, a ciphertext tuple, a digest, etc.).
|
||||
|
||||
return ok(value) # equivalent to return value
|
||||
|
||||
For pure validation-style APIs where "success means (None,None,None)", return :data:`OK_TUPLE` directly.
|
||||
"""
|
||||
return value
|
||||
|
||||
|
||||
#: Success return value for pure validation-style APIs: ``(None, None, None)``
|
||||
OK_TUPLE: PPYCResult = _OK
|
||||
|
||||
|
||||
def err(code: str, message: str, suggestion: str = "") -> PPYCResult:
|
||||
"""Construct a **non-fatal error** 3-tuple return value ``(code, message, suggestion)``.
|
||||
|
||||
Parameters
|
||||
----
|
||||
code : str
|
||||
Error code, must look like ``PPYC_ERR_xxx`` (using the constants provided by this module is recommended).
|
||||
message : str
|
||||
Human-readable reason.
|
||||
suggestion : str
|
||||
Human-readable remediation hint; may be empty.
|
||||
|
||||
Returns
|
||||
----
|
||||
(str, str, str)
|
||||
"""
|
||||
if not isinstance(code, str) or not code.startswith(PPYC_ERR_PREFIX):
|
||||
# Unified prefix check: avoid inconsistent error code styles (a library-usage bug -> fatal)
|
||||
raise PPYC_ERR(
|
||||
"PPYC_ERR_INTERNAL",
|
||||
f"error code must look like {PPYC_ERR_PREFIX}xxx, got: {code!r}",
|
||||
"use the error code constants defined in _ppyc_error",
|
||||
)
|
||||
return (code, message, suggestion)
|
||||
|
||||
|
||||
def is_ok(result: Any) -> bool:
|
||||
"""Determine whether a return value indicates "success".
|
||||
|
||||
Success conditions (any of):
|
||||
* the value is ``None`` (no error)
|
||||
* the value is ``(None, None, None)`` (the success tuple of validation-style APIs)
|
||||
|
||||
Note: ordinary business success values (e.g. plaintext bytes) also return True,
|
||||
because the library uses 3-tuples only for errors; every other return value is treated as success.
|
||||
"""
|
||||
if result is None:
|
||||
return True
|
||||
if isinstance(result, tuple) and len(result) == 3:
|
||||
return result[0] is None
|
||||
return True
|
||||
|
||||
|
||||
def is_err(result: Any) -> bool:
|
||||
"""Determine whether a return value is a **non-fatal error** tuple (``(code,msg,hint)`` with a non-None code)."""
|
||||
return (isinstance(result, tuple) and len(result) == 3
|
||||
and isinstance(result[0], str) and result[0].startswith(PPYC_ERR_PREFIX))
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# 3. Error code constant table
|
||||
# ======================================================================
|
||||
# Naming rule: PPYC_ERR_ + upper-case snake_case
|
||||
# Groups: general / argument / key / authentication / encoding / file / environment / internal
|
||||
# ======================================================================
|
||||
|
||||
PPYC_ERR_PREFIX = "PPYC_ERR_"
|
||||
|
||||
# ---- General ----
|
||||
PPYC_ERR_UNKNOWN = "PPYC_ERR_UNKNOWN" # uncategorized error
|
||||
PPYC_ERR_INTERNAL = "PPYC_ERR_INTERNAL" # internal inconsistency (should raise PPYC_ERR)
|
||||
PPYC_ERR_UNSUPPORTED = "PPYC_ERR_UNSUPPORTED" # unsupported feature / value
|
||||
PPYC_ERR_NOT_IMPLEMENTED = "PPYC_ERR_NOT_IMPLEMENTED" # not yet implemented
|
||||
|
||||
# ---- Argument validation ----
|
||||
PPYC_ERR_INVALID_ARG = "PPYC_ERR_INVALID_ARG" # invalid generic argument
|
||||
PPYC_ERR_INVALID_TYPE = "PPYC_ERR_INVALID_TYPE" # invalid type (e.g. not bytes)
|
||||
PPYC_ERR_INVALID_LENGTH = "PPYC_ERR_INVALID_LENGTH" # invalid length (generic)
|
||||
PPYC_ERR_INVALID_HEX = "PPYC_ERR_INVALID_HEX" # invalid hexadecimal format
|
||||
PPYC_ERR_OUT_OF_RANGE = "PPYC_ERR_OUT_OF_RANGE" # value out of range
|
||||
PPYC_ERR_MESSAGE_TOO_LONG = "PPYC_ERR_MESSAGE_TOO_LONG" # message too long (exceeds encoding limit)
|
||||
PPYC_ERR_INPUT_TOO_LARGE = "PPYC_ERR_INPUT_TOO_LARGE" # input exceeds algorithm limit
|
||||
|
||||
# ---- Key / nonce / IV ----
|
||||
PPYC_ERR_INVALID_KEY = "PPYC_ERR_INVALID_KEY" # invalid key (generic)
|
||||
PPYC_ERR_INVALID_KEY_LEN = "PPYC_ERR_INVALID_KEY_LEN" # invalid key length
|
||||
PPYC_ERR_INVALID_NONCE = "PPYC_ERR_INVALID_NONCE" # invalid nonce
|
||||
PPYC_ERR_INVALID_NONCE_LEN = "PPYC_ERR_INVALID_NONCE_LEN" # invalid nonce length
|
||||
PPYC_ERR_INVALID_IV = "PPYC_ERR_INVALID_IV" # invalid IV
|
||||
PPYC_ERR_INVALID_IV_LEN = "PPYC_ERR_INVALID_IV_LEN" # invalid IV length
|
||||
PPYC_ERR_INVALID_SALT = "PPYC_ERR_INVALID_SALT" # invalid salt
|
||||
|
||||
# ---- Authentication / decryption ----
|
||||
PPYC_ERR_AUTH_FAILED = "PPYC_ERR_AUTH_FAILED" # authentication failure (AEAD / signature)
|
||||
PPYC_ERR_DECRYPT_FAILED = "PPYC_ERR_DECRYPT_FAILED" # decryption failed
|
||||
PPYC_ERR_INVALID_PADDING = "PPYC_ERR_INVALID_PADDING" # invalid padding (PKCS#7, etc.)
|
||||
PPYC_ERR_INVALID_SIGNATURE= "PPYC_ERR_INVALID_SIGNATURE" # invalid signature / verification failed
|
||||
PPYC_ERR_INVALID_TAG = "PPYC_ERR_INVALID_TAG" # invalid authentication tag
|
||||
|
||||
# ---- Encoding / parsing ----
|
||||
PPYC_ERR_INVALID_ENCODING = "PPYC_ERR_INVALID_ENCODING" # invalid encoding format (DER / PEM)
|
||||
PPYC_ERR_PARSE_FAILED = "PPYC_ERR_PARSE_FAILED" # parsing failed
|
||||
PPYC_ERR_INVALID_POINT = "PPYC_ERR_INVALID_POINT" # invalid curve point (decoding / low order)
|
||||
PPYC_ERR_INVALID_KEY_MATERIAL = "PPYC_ERR_INVALID_KEY_MATERIAL" # invalid key material
|
||||
|
||||
# ---- File / IO ----
|
||||
PPYC_ERR_FILE_NOT_FOUND = "PPYC_ERR_FILE_NOT_FOUND" # file not found
|
||||
PPYC_ERR_IO = "PPYC_ERR_IO" # read/write failed
|
||||
PPYC_ERR_PERMISSION = "PPYC_ERR_PERMISSION" # insufficient permissions
|
||||
|
||||
# ---- Environment / dependencies ----
|
||||
PPYC_ERR_NO_MULTIPROCESS = "PPYC_ERR_NO_MULTIPROCESS" # multiprocessing unavailable
|
||||
PPYC_ERR_ENV = "PPYC_ERR_ENV" # runtime environment problem
|
||||
|
||||
# ---- Algorithm / parameter domain ----
|
||||
PPYC_ERR_INVALID_PARAM = "PPYC_ERR_INVALID_PARAM" # invalid algorithm parameter (e.g. iterations/N/r/p)
|
||||
PPYC_ERR_INVALID_KDF_PARAM= "PPYC_ERR_INVALID_KDF_PARAM" # invalid KDF parameter
|
||||
PPYC_ERR_INVALID_RSA_BITS = "PPYC_ERR_INVALID_RSA_BITS" # invalid RSA bit length
|
||||
PPYC_ERR_INVALID_ALGO = "PPYC_ERR_INVALID_ALGO" # invalid algorithm name
|
||||
PPYC_ERR_INVALID_MODE = "PPYC_ERR_INVALID_MODE" # invalid mode (e.g. ECB/CBC/GCM)
|
||||
PPYC_ERR_INVALID_OPERATION= "PPYC_ERR_INVALID_OPERATION" # invalid operation (e.g. enc/dec)
|
||||
|
||||
# ---- CLI / TUI ----
|
||||
PPYC_ERR_CLI_USAGE = "PPYC_ERR_CLI_USAGE" # command-line usage error
|
||||
PPYC_ERR_CLI_INPUT = "PPYC_ERR_CLI_INPUT" # invalid interactive input
|
||||
PPYC_ERR_EOF = "PPYC_ERR_EOF" # end of input stream (pipe/redirect)
|
||||
|
||||
#: All error code constants (used for documentation generation and self-test)
|
||||
# Excludes PPYC_ERR_PREFIX itself (it is a prefix constant, not an error code)
|
||||
ALL_ERROR_CODES = tuple(
|
||||
v for k, v in sorted(globals().items())
|
||||
if k.startswith("PPYC_ERR_") and k != "PPYC_ERR_PREFIX" and isinstance(v, str)
|
||||
)
|
||||
|
||||
__all__ += [k for k in globals() if k.startswith("PPYC_ERR_")] + ["OK_TUPLE", "ALL_ERROR_CODES"]
|
||||
@@ -0,0 +1 @@
|
||||
__version__ = "3.2.0"
|
||||
@@ -0,0 +1,869 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""purepycrypto.aes
|
||||
========================================
|
||||
purepycrypto - Pure-Python cryptography library (zero dependencies)
|
||||
AES-128/192/256 (T-table implementation), supporting ECB/CBC/CTR/CFB/OFB and AES-GCM (with parallel GHASH).
|
||||
|
||||
Unified error system (see purepycrypto._ppyc_error)
|
||||
------------------------------------------
|
||||
All caller-facing APIs in this module follow this contract:
|
||||
* Argument validation failure (invalid key/IV/nonce/length, invalid padding) -> **return** a 3-tuple
|
||||
``(error_code, error_message, suggestion)`` instead of raising an exception;
|
||||
* Authentication failure (GCM tag mismatch) -> **return** ``err(PPYC_ERR_AUTH_FAILED, ...)``;
|
||||
* On success returns bytes; a successful ``gcm_encrypt`` returns a ``(ciphertext, tag)`` pair,
|
||||
``gcm_decrypt`` returns plaintext bytes on success and an error 3-tuple on failure;
|
||||
* :class:`PPYC_ERR` is raised only when the AES object receives an invalid key at
|
||||
**initialization time** (so the object cannot be constructed).
|
||||
Callers should check the return value: an error is indicated when the first element is a ``str`` starting with ``PPYC_ERR_``.
|
||||
"""
|
||||
|
||||
from typing import Tuple
|
||||
|
||||
from .common import (
|
||||
MASK32, R_CONST,
|
||||
_consttime_eq, _xor_bytes, _pad_pkcs7, _unpad_pkcs7,
|
||||
)
|
||||
from ._ppyc_error import (
|
||||
PPYC_ERR, err, ok, OK_TUPLE, is_err,
|
||||
PPYC_ERR_INVALID_KEY_LEN, PPYC_ERR_INVALID_IV_LEN,
|
||||
PPYC_ERR_INVALID_NONCE_LEN, PPYC_ERR_INVALID_LENGTH,
|
||||
PPYC_ERR_INVALID_PADDING, PPYC_ERR_INVALID_TAG,
|
||||
PPYC_ERR_AUTH_FAILED, PPYC_ERR_INTERNAL,
|
||||
)
|
||||
from .parallel import _HAS_MP, _get_pool
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 7. AES core (LibTomCrypt T-table)
|
||||
# ============================================================
|
||||
|
||||
TE0 = [
|
||||
0xc66363a5,0xf87c7c84,0xee777799,0xf67b7b8d,0xfff2f20d,0xd66b6bbd,0xde6f6fb1,0x91c5c554,
|
||||
0x60303050,0x02010103,0xce6767a9,0x562b2b7d,0xe7fefe19,0xb5d7d762,0x4dababe6,0xec76769a,
|
||||
0x8fcaca45,0x1f82829d,0x89c9c940,0xfa7d7d87,0xeffafa15,0xb25959eb,0x8e4747c9,0xfbf0f00b,
|
||||
0x41adadec,0xb3d4d467,0x5fa2a2fd,0x45afafea,0x239c9cbf,0x53a4a4f7,0xe4727296,0x9bc0c05b,
|
||||
0x75b7b7c2,0xe1fdfd1c,0x3d9393ae,0x4c26266a,0x6c36365a,0x7e3f3f41,0xf5f7f702,0x83cccc4f,
|
||||
0x6834345c,0x51a5a5f4,0xd1e5e534,0xf9f1f108,0xe2717193,0xabd8d873,0x62313153,0x2a15153f,
|
||||
0x0804040c,0x95c7c752,0x46232365,0x9dc3c35e,0x30181828,0x379696a1,0x0a05050f,0x2f9a9ab5,
|
||||
0x0e070709,0x24121236,0x1b80809b,0xdfe2e23d,0xcdebeb26,0x4e272769,0x7fb2b2cd,0xea75759f,
|
||||
0x1209091b,0x1d83839e,0x582c2c74,0x341a1a2e,0x361b1b2d,0xdc6e6eb2,0xb45a5aee,0x5ba0a0fb,
|
||||
0xa45252f6,0x763b3b4d,0xb7d6d661,0x7db3b3ce,0x5229297b,0xdde3e33e,0x5e2f2f71,0x13848497,
|
||||
0xa65353f5,0xb9d1d168,0x00000000,0xc1eded2c,0x40202060,0xe3fcfc1f,0x79b1b1c8,0xb65b5bed,
|
||||
0xd46a6abe,0x8dcbcb46,0x67bebed9,0x7239394b,0x944a4ade,0x984c4cd4,0xb05858e8,0x85cfcf4a,
|
||||
0xbbd0d06b,0xc5efef2a,0x4faaaae5,0xedfbfb16,0x864343c5,0x9a4d4dd7,0x66333355,0x11858594,
|
||||
0x8a4545cf,0xe9f9f910,0x04020206,0xfe7f7f81,0xa05050f0,0x783c3c44,0x259f9fba,0x4ba8a8e3,
|
||||
0xa25151f3,0x5da3a3fe,0x804040c0,0x058f8f8a,0x3f9292ad,0x219d9dbc,0x70383848,0xf1f5f504,
|
||||
0x63bcbcdf,0x77b6b6c1,0xafdada75,0x42212163,0x20101030,0xe5ffff1a,0xfdf3f30e,0xbfd2d26d,
|
||||
0x81cdcd4c,0x180c0c14,0x26131335,0xc3ecec2f,0xbe5f5fe1,0x359797a2,0x884444cc,0x2e171739,
|
||||
0x93c4c457,0x55a7a7f2,0xfc7e7e82,0x7a3d3d47,0xc86464ac,0xba5d5de7,0x3219192b,0xe6737395,
|
||||
0xc06060a0,0x19818198,0x9e4f4fd1,0xa3dcdc7f,0x44222266,0x542a2a7e,0x3b9090ab,0x0b888883,
|
||||
0x8c4646ca,0xc7eeee29,0x6bb8b8d3,0x2814143c,0xa7dede79,0xbc5e5ee2,0x160b0b1d,0xaddbdb76,
|
||||
0xdbe0e03b,0x64323256,0x743a3a4e,0x140a0a1e,0x924949db,0x0c06060a,0x4824246c,0xb85c5ce4,
|
||||
0x9fc2c25d,0xbdd3d36e,0x43acacef,0xc46262a6,0x399191a8,0x319595a4,0xd3e4e437,0xf279798b,
|
||||
0xd5e7e732,0x8bc8c843,0x6e373759,0xda6d6db7,0x018d8d8c,0xb1d5d564,0x9c4e4ed2,0x49a9a9e0,
|
||||
0xd86c6cb4,0xac5656fa,0xf3f4f407,0xcfeaea25,0xca6565af,0xf47a7a8e,0x47aeaee9,0x10080818,
|
||||
0x6fbabad5,0xf0787888,0x4a25256f,0x5c2e2e72,0x381c1c24,0x57a6a6f1,0x73b4b4c7,0x97c6c651,
|
||||
0xcbe8e823,0xa1dddd7c,0xe874749c,0x3e1f1f21,0x964b4bdd,0x61bdbddc,0x0d8b8b86,0x0f8a8a85,
|
||||
0xe0707090,0x7c3e3e42,0x71b5b5c4,0xcc6666aa,0x904848d8,0x06030305,0xf7f6f601,0x1c0e0e12,
|
||||
0xc26161a3,0x6a35355f,0xae5757f9,0x69b9b9d0,0x17868691,0x99c1c158,0x3a1d1d27,0x279e9eb9,
|
||||
0xd9e1e138,0xebf8f813,0x2b9898b3,0x22111133,0xd26969bb,0xa9d9d970,0x078e8e89,0x339494a7,
|
||||
0x2d9b9bb6,0x3c1e1e22,0x15878792,0xc9e9e920,0x87cece49,0xaa5555ff,0x50282878,0xa5dfdf7a,
|
||||
0x038c8c8f,0x59a1a1f8,0x09898980,0x1a0d0d17,0x65bfbfda,0xd7e6e631,0x844242c6,0xd06868b8,
|
||||
0x824141c3,0x299999b0,0x5a2d2d77,0x1e0f0f11,0x7bb0b0cb,0xa85454fc,0x6dbbbbd6,0x2c16163a,
|
||||
]
|
||||
|
||||
TD0 = [
|
||||
0x51f4a750,0x7e416553,0x1a17a4c3,0x3a275e96,0x3bab6bcb,0x1f9d45f1,0xacfa58ab,0x4be30393,
|
||||
0x2030fa55,0xad766df6,0x88cc7691,0xf5024c25,0x4fe5d7fc,0xc52acbd7,0x26354480,0xb562a38f,
|
||||
0xdeb15a49,0x25ba1b67,0x45ea0e98,0x5dfec0e1,0xc32f7502,0x814cf012,0x8d4697a3,0x6bd3f9c6,
|
||||
0x038f5fe7,0x15929c95,0xbf6d7aeb,0x955259da,0xd4be832d,0x587421d3,0x49e06929,0x8ec9c844,
|
||||
0x75c2896a,0xf48e7978,0x99583e6b,0x27b971dd,0xbee14fb6,0xf088ad17,0xc920ac66,0x7dce3ab4,
|
||||
0x63df4a18,0xe51a3182,0x97513360,0x62537f45,0xb16477e0,0xbb6bae84,0xfe81a01c,0xf9082b94,
|
||||
0x70486858,0x8f45fd19,0x94de6c87,0x527bf8b7,0xab73d323,0x724b02e2,0xe31f8f57,0x6655ab2a,
|
||||
0xb2eb2807,0x2fb5c203,0x86c57b9a,0xd33708a5,0x302887f2,0x23bfa5b2,0x02036aba,0xed16825c,
|
||||
0x8acf1c2b,0xa779b492,0xf307f2f0,0x4e69e2a1,0x65daf4cd,0x0605bed5,0xd134621f,0xc4a6fe8a,
|
||||
0x342e539d,0xa2f355a0,0x058ae132,0xa4f6eb75,0x0b83ec39,0x4060efaa,0x5e719f06,0xbd6e1051,
|
||||
0x3e218af9,0x96dd063d,0xdd3e05ae,0x4de6bd46,0x91548db5,0x71c45d05,0x0406d46f,0x605015ff,
|
||||
0x1998fb24,0xd6bde997,0x894043cc,0x67d99e77,0xb0e842bd,0x07898b88,0xe7195b38,0x79c8eedb,
|
||||
0xa17c0a47,0x7c420fe9,0xf8841ec9,0x00000000,0x09808683,0x322bed48,0x1e1170ac,0x6c5a724e,
|
||||
0xfd0efffb,0x0f853856,0x3daed51e,0x362d3927,0x0a0fd964,0x685ca621,0x9b5b54d1,0x24362e3a,
|
||||
0x0c0a67b1,0x9357e70f,0xb4ee96d2,0x1b9b919e,0x80c0c54f,0x61dc20a2,0x5a774b69,0x1c121a16,
|
||||
0xe293ba0a,0xc0a02ae5,0x3c22e043,0x121b171d,0x0e090d0b,0xf28bc7ad,0x2db6a8b9,0x141ea9c8,
|
||||
0x57f11985,0xaf75074c,0xee99ddbb,0xa37f60fd,0xf701269f,0x5c72f5bc,0x44663bc5,0x5bfb7e34,
|
||||
0x8b432976,0xcb23c6dc,0xb6edfc68,0xb8e4f163,0xd731dcca,0x42638510,0x13972240,0x84c61120,
|
||||
0x854a247d,0xd2bb3df8,0xaef93211,0xc729a16d,0x1d9e2f4b,0xdcb230f3,0x0d8652ec,0x77c1e3d0,
|
||||
0x2bb3166c,0xa970b999,0x119448fa,0x47e96422,0xa8fc8cc4,0xa0f03f1a,0x567d2cd8,0x223390ef,
|
||||
0x87494ec7,0xd938d1c1,0x8ccaa2fe,0x98d40b36,0xa6f581cf,0xa57ade28,0xdab78e26,0x3fadbfa4,
|
||||
0x2c3a9de4,0x5078920d,0x6a5fcc9b,0x547e4662,0xf68d13c2,0x90d8b8e8,0x2e39f75e,0x82c3aff5,
|
||||
0x9f5d80be,0x69d0937c,0x6fd52da9,0xcf2512b3,0xc8ac993b,0x10187da7,0xe89c636e,0xdb3bbb7b,
|
||||
0xcd267809,0x6e5918f4,0xec9ab701,0x834f9aa8,0xe6956e65,0xaaffe67e,0x21bccf08,0xef15e8e6,
|
||||
0xbae79bd9,0x4a6f36ce,0xea9f09d4,0x29b07cd6,0x31a4b2af,0x2a3f2331,0xc6a59430,0x35a266c0,
|
||||
0x744ebc37,0xfc82caa6,0xe090d0b0,0x33a7d815,0xf104984a,0x41ecdaf7,0x7fcd500e,0x1791f62f,
|
||||
0x764dd68d,0x43efb04d,0xccaa4d54,0xe49604df,0x9ed1b5e3,0x4c6a881b,0xc12c1fb8,0x4665517f,
|
||||
0x9d5eea04,0x018c355d,0xfa877473,0xfb0b412e,0xb3671d5a,0x92dbd252,0xe9105633,0x6dd64713,
|
||||
0x9ad7618c,0x37a10c7a,0x59f8148e,0xeb133c89,0xcea927ee,0xb761c935,0xe11ce5ed,0x7a47b13c,
|
||||
0x9cd2df59,0x55f2733f,0x1814ce79,0x73c737bf,0x53f7cdea,0x5ffdaa5b,0xdf3d6f14,0x7844db86,
|
||||
0xcaaff381,0xb968c43e,0x3824342c,0xc2a3405f,0x161dc372,0xbce2250c,0x283c498b,0xff0d9541,
|
||||
0x39a80171,0x080cb3de,0xd8b4e49c,0x6456c190,0x7bcb8461,0xd532b670,0x486c5c74,0xd0b85742,
|
||||
]
|
||||
|
||||
|
||||
def _ror(x, n):
|
||||
return ((x >> n) | ((x << (32 - n)) & MASK32)) & MASK32
|
||||
|
||||
|
||||
TE1 = [_ror(x, 8) for x in TE0]
|
||||
TE2 = [_ror(x, 16) for x in TE0]
|
||||
TE3 = [_ror(x, 24) for x in TE0]
|
||||
TD1 = [_ror(x, 8) for x in TD0]
|
||||
TD2 = [_ror(x, 16) for x in TD0]
|
||||
TD3 = [_ror(x, 24) for x in TD0]
|
||||
|
||||
|
||||
def _make_sbox():
|
||||
s = [0] * 256
|
||||
for i in range(256):
|
||||
v = TE0[i]
|
||||
s[i] = ((v >> 24) ^ (v & 0xff)) & 0xff
|
||||
return bytes(s)
|
||||
|
||||
|
||||
SBOX = _make_sbox()
|
||||
|
||||
|
||||
def _make_inv_sbox():
|
||||
inv = [0] * 256
|
||||
for i in range(256):
|
||||
inv[SBOX[i]] = i
|
||||
return bytes(inv)
|
||||
|
||||
|
||||
INV_SBOX = _make_inv_sbox()
|
||||
TE4_0 = [s for s in SBOX]
|
||||
TE4_1 = [(s << 8) & MASK32 for s in SBOX]
|
||||
TE4_2 = [(s << 16) & MASK32 for s in SBOX]
|
||||
TE4_3 = [(s << 24) & MASK32 for s in SBOX]
|
||||
TD4 = [(s << 24) | (s << 16) | (s << 8) | s for s in INV_SBOX]
|
||||
|
||||
|
||||
def _gmul(a, b):
|
||||
p = 0
|
||||
for _ in range(8):
|
||||
if b & 1: p ^= a
|
||||
hi = a & 0x80
|
||||
a = (a << 1) & 0xff
|
||||
if hi: a ^= 0x1b
|
||||
b >>= 1
|
||||
return p & 0xff
|
||||
|
||||
|
||||
def _imc(x):
|
||||
return ((_gmul(14, x) << 24) | (_gmul(9, x) << 16) |
|
||||
(_gmul(13, x) << 8) | _gmul(11, x))
|
||||
|
||||
|
||||
Tks0 = [_imc(x) for x in range(256)]
|
||||
Tks1 = [_ror(x, 8) for x in Tks0]
|
||||
Tks2 = [_ror(x, 16) for x in Tks0]
|
||||
Tks3 = [_ror(x, 24) for x in Tks0]
|
||||
|
||||
RCON = [0x01000000, 0x02000000, 0x04000000, 0x08000000, 0x10000000,
|
||||
0x20000000, 0x40000000, 0x80000000, 0x1B000000, 0x36000000]
|
||||
|
||||
|
||||
def _B(x, n):
|
||||
return (x >> (8 * n)) & 0xFF
|
||||
|
||||
|
||||
def _ld32(b, off):
|
||||
return (b[off] << 24) | (b[off + 1] << 16) | (b[off + 2] << 8) | b[off + 3]
|
||||
|
||||
|
||||
def _st32(x):
|
||||
return bytes([(x >> 24) & 0xFF, (x >> 16) & 0xFF, (x >> 8) & 0xFF, x & 0xFF])
|
||||
|
||||
|
||||
def _setup_mix(t):
|
||||
return (TE4_3[_B(t, 2)] ^ TE4_2[_B(t, 1)] ^ TE4_1[_B(t, 0)] ^ TE4_0[_B(t, 3)])
|
||||
|
||||
|
||||
def _unpad_or_err(data: bytes):
|
||||
"""PKCS#7 unpadding; returns an error 3-tuple instead of raising an exception on invalid padding.
|
||||
|
||||
Returns
|
||||
----
|
||||
bytes : the plaintext with padding removed;
|
||||
or (code, message, suggestion): code = PPYC_ERR_INVALID_PADDING when the padding is invalid.
|
||||
"""
|
||||
try:
|
||||
return _unpad_pkcs7(data)
|
||||
except (ValueError, IndexError):
|
||||
return err(PPYC_ERR_INVALID_PADDING,
|
||||
"invalid PKCS#7 padding",
|
||||
"the ciphertext may have been tampered with, the key/IV is wrong, or the data was not encrypted by this library")
|
||||
|
||||
|
||||
def aes_key_expansion(key: bytes):
|
||||
"""AES key expansion: derive the encrypt/decrypt round key schedules from the master key.
|
||||
|
||||
Parameters
|
||||
----
|
||||
key : 16 / 24 / 32 byte master key (for AES-128/192/256).
|
||||
|
||||
Returns
|
||||
----
|
||||
(eK, dK, Nr) : encrypt round keys, decrypt round keys, number of rounds (10/12/14).
|
||||
or an error 3-tuple (error_code, error_message, suggestion):
|
||||
PPYC_ERR_INVALID_KEY_LEN the key length is not 16/24/32 bytes.
|
||||
"""
|
||||
keylen = len(key)
|
||||
if keylen == 16:
|
||||
Nr = 10
|
||||
elif keylen == 24:
|
||||
Nr = 12
|
||||
elif keylen == 32:
|
||||
Nr = 14
|
||||
else:
|
||||
return err(PPYC_ERR_INVALID_KEY_LEN,
|
||||
f"AES key length must be 16/24/32 bytes, got {keylen}",
|
||||
"pass a 16, 24 or 32 byte key")
|
||||
|
||||
eK = [0] * (4 * (Nr + 1) + 8)
|
||||
dK = [0] * (4 * (Nr + 1) + 8)
|
||||
eK[0] = _ld32(key, 0); eK[1] = _ld32(key, 4)
|
||||
eK[2] = _ld32(key, 8); eK[3] = _ld32(key, 12)
|
||||
|
||||
i = 0; rk = 0
|
||||
if keylen == 16:
|
||||
while True:
|
||||
t = eK[rk + 3]
|
||||
eK[rk + 4] = eK[rk + 0] ^ _setup_mix(t) ^ RCON[i]
|
||||
eK[rk + 5] = eK[rk + 1] ^ eK[rk + 4]
|
||||
eK[rk + 6] = eK[rk + 2] ^ eK[rk + 5]
|
||||
eK[rk + 7] = eK[rk + 3] ^ eK[rk + 6]
|
||||
i += 1
|
||||
if i == 10: break
|
||||
rk += 4
|
||||
elif keylen == 24:
|
||||
eK[4] = _ld32(key, 16); eK[5] = _ld32(key, 20)
|
||||
while True:
|
||||
t = eK[rk + 5]
|
||||
eK[rk + 6] = eK[rk + 0] ^ _setup_mix(t) ^ RCON[i]
|
||||
eK[rk + 7] = eK[rk + 1] ^ eK[rk + 6]
|
||||
eK[rk + 8] = eK[rk + 2] ^ eK[rk + 7]
|
||||
eK[rk + 9] = eK[rk + 3] ^ eK[rk + 8]
|
||||
i += 1
|
||||
if i == 8: break
|
||||
eK[rk + 10] = eK[rk + 4] ^ eK[rk + 9]
|
||||
eK[rk + 11] = eK[rk + 5] ^ eK[rk + 10]
|
||||
rk += 6
|
||||
else:
|
||||
eK[4] = _ld32(key, 16); eK[5] = _ld32(key, 20)
|
||||
eK[6] = _ld32(key, 24); eK[7] = _ld32(key, 28)
|
||||
while True:
|
||||
t = eK[rk + 7]
|
||||
eK[rk + 8] = eK[rk + 0] ^ _setup_mix(t) ^ RCON[i]
|
||||
eK[rk + 9] = eK[rk + 1] ^ eK[rk + 8]
|
||||
eK[rk + 10] = eK[rk + 2] ^ eK[rk + 9]
|
||||
eK[rk + 11] = eK[rk + 3] ^ eK[rk + 10]
|
||||
i += 1
|
||||
if i == 7: break
|
||||
t = eK[rk + 11]
|
||||
eK[rk + 12] = eK[rk + 4] ^ _setup_mix(_ror(t, 8))
|
||||
eK[rk + 13] = eK[rk + 5] ^ eK[rk + 12]
|
||||
eK[rk + 14] = eK[rk + 6] ^ eK[rk + 13]
|
||||
eK[rk + 15] = eK[rk + 7] ^ eK[rk + 14]
|
||||
rk += 8
|
||||
|
||||
rrk = (28 + keylen) - 4
|
||||
dK[0] = eK[rrk + 0]; dK[1] = eK[rrk + 1]
|
||||
dK[2] = eK[rrk + 2]; dK[3] = eK[rrk + 3]
|
||||
rk = 0
|
||||
for _ in range(1, Nr):
|
||||
rrk -= 4; rk += 4
|
||||
for j in range(4):
|
||||
t = eK[rrk + j]
|
||||
dK[rk + j] = (Tks0[_B(t, 3)] ^ Tks1[_B(t, 2)] ^
|
||||
Tks2[_B(t, 1)] ^ Tks3[_B(t, 0)])
|
||||
rrk -= 4; rk += 4
|
||||
dK[rk + 0] = eK[rrk + 0]; dK[rk + 1] = eK[rrk + 1]
|
||||
dK[rk + 2] = eK[rrk + 2]; dK[rk + 3] = eK[rrk + 3]
|
||||
return eK, dK, Nr
|
||||
|
||||
|
||||
def aes_encrypt_block(pt: bytes, eK, Nr: int) -> bytes:
|
||||
s0 = _ld32(pt, 0) ^ eK[0]
|
||||
s1 = _ld32(pt, 4) ^ eK[1]
|
||||
s2 = _ld32(pt, 8) ^ eK[2]
|
||||
s3 = _ld32(pt, 12) ^ eK[3]
|
||||
rk = 0; r = Nr >> 1
|
||||
while True:
|
||||
t0 = TE0[_B(s0, 3)] ^ TE1[_B(s1, 2)] ^ TE2[_B(s2, 1)] ^ TE3[_B(s3, 0)] ^ eK[rk + 4]
|
||||
t1 = TE0[_B(s1, 3)] ^ TE1[_B(s2, 2)] ^ TE2[_B(s3, 1)] ^ TE3[_B(s0, 0)] ^ eK[rk + 5]
|
||||
t2 = TE0[_B(s2, 3)] ^ TE1[_B(s3, 2)] ^ TE2[_B(s0, 1)] ^ TE3[_B(s1, 0)] ^ eK[rk + 6]
|
||||
t3 = TE0[_B(s3, 3)] ^ TE1[_B(s0, 2)] ^ TE2[_B(s1, 1)] ^ TE3[_B(s2, 0)] ^ eK[rk + 7]
|
||||
rk += 8; r -= 1
|
||||
if r == 0: break
|
||||
s0 = TE0[_B(t0, 3)] ^ TE1[_B(t1, 2)] ^ TE2[_B(t2, 1)] ^ TE3[_B(t3, 0)] ^ eK[rk + 0]
|
||||
s1 = TE0[_B(t1, 3)] ^ TE1[_B(t2, 2)] ^ TE2[_B(t3, 1)] ^ TE3[_B(t0, 0)] ^ eK[rk + 1]
|
||||
s2 = TE0[_B(t2, 3)] ^ TE1[_B(t3, 2)] ^ TE2[_B(t0, 1)] ^ TE3[_B(t1, 0)] ^ eK[rk + 2]
|
||||
s3 = TE0[_B(t3, 3)] ^ TE1[_B(t0, 2)] ^ TE2[_B(t1, 1)] ^ TE3[_B(t2, 0)] ^ eK[rk + 3]
|
||||
t0, t1, t2, t3 = s0, s1, s2, s3
|
||||
r0 = TE4_3[_B(t0, 3)] ^ TE4_2[_B(t1, 2)] ^ TE4_1[_B(t2, 1)] ^ TE4_0[_B(t3, 0)] ^ eK[rk + 0]
|
||||
r1 = TE4_3[_B(t1, 3)] ^ TE4_2[_B(t2, 2)] ^ TE4_1[_B(t3, 1)] ^ TE4_0[_B(t0, 0)] ^ eK[rk + 1]
|
||||
r2 = TE4_3[_B(t2, 3)] ^ TE4_2[_B(t3, 2)] ^ TE4_1[_B(t0, 1)] ^ TE4_0[_B(t1, 0)] ^ eK[rk + 2]
|
||||
r3 = TE4_3[_B(t3, 3)] ^ TE4_2[_B(t0, 2)] ^ TE4_1[_B(t1, 1)] ^ TE4_0[_B(t2, 0)] ^ eK[rk + 3]
|
||||
return _st32(r0) + _st32(r1) + _st32(r2) + _st32(r3)
|
||||
|
||||
|
||||
def aes_decrypt_block(ct: bytes, dK, Nr: int) -> bytes:
|
||||
s0 = _ld32(ct, 0) ^ dK[0]
|
||||
s1 = _ld32(ct, 4) ^ dK[1]
|
||||
s2 = _ld32(ct, 8) ^ dK[2]
|
||||
s3 = _ld32(ct, 12) ^ dK[3]
|
||||
rk = 0; r = Nr >> 1
|
||||
while True:
|
||||
t0 = TD0[_B(s0, 3)] ^ TD1[_B(s3, 2)] ^ TD2[_B(s2, 1)] ^ TD3[_B(s1, 0)] ^ dK[rk + 4]
|
||||
t1 = TD0[_B(s1, 3)] ^ TD1[_B(s0, 2)] ^ TD2[_B(s3, 1)] ^ TD3[_B(s2, 0)] ^ dK[rk + 5]
|
||||
t2 = TD0[_B(s2, 3)] ^ TD1[_B(s1, 2)] ^ TD2[_B(s0, 1)] ^ TD3[_B(s3, 0)] ^ dK[rk + 6]
|
||||
t3 = TD0[_B(s3, 3)] ^ TD1[_B(s2, 2)] ^ TD2[_B(s1, 1)] ^ TD3[_B(s0, 0)] ^ dK[rk + 7]
|
||||
rk += 8; r -= 1
|
||||
if r == 0: break
|
||||
s0 = TD0[_B(t0, 3)] ^ TD1[_B(t3, 2)] ^ TD2[_B(t2, 1)] ^ TD3[_B(t1, 0)] ^ dK[rk + 0]
|
||||
s1 = TD0[_B(t1, 3)] ^ TD1[_B(t0, 2)] ^ TD2[_B(t3, 1)] ^ TD3[_B(t2, 0)] ^ dK[rk + 1]
|
||||
s2 = TD0[_B(t2, 3)] ^ TD1[_B(t1, 2)] ^ TD2[_B(t0, 1)] ^ TD3[_B(t3, 0)] ^ dK[rk + 2]
|
||||
s3 = TD0[_B(t3, 3)] ^ TD1[_B(t2, 2)] ^ TD2[_B(t1, 1)] ^ TD3[_B(t0, 0)] ^ dK[rk + 3]
|
||||
t0, t1, t2, t3 = s0, s1, s2, s3
|
||||
r0 = ((TD4[_B(t0, 3)] & 0xff000000) ^ (TD4[_B(t3, 2)] & 0x00ff0000) ^
|
||||
(TD4[_B(t2, 1)] & 0x0000ff00) ^ (TD4[_B(t1, 0)] & 0x000000ff) ^ dK[rk + 0])
|
||||
r1 = ((TD4[_B(t1, 3)] & 0xff000000) ^ (TD4[_B(t0, 2)] & 0x00ff0000) ^
|
||||
(TD4[_B(t3, 1)] & 0x0000ff00) ^ (TD4[_B(t2, 0)] & 0x000000ff) ^ dK[rk + 1])
|
||||
r2 = ((TD4[_B(t2, 3)] & 0xff000000) ^ (TD4[_B(t1, 2)] & 0x00ff0000) ^
|
||||
(TD4[_B(t0, 1)] & 0x0000ff00) ^ (TD4[_B(t3, 0)] & 0x000000ff) ^ dK[rk + 2])
|
||||
r3 = ((TD4[_B(t3, 3)] & 0xff000000) ^ (TD4[_B(t2, 2)] & 0x00ff0000) ^
|
||||
(TD4[_B(t1, 1)] & 0x0000ff00) ^ (TD4[_B(t0, 0)] & 0x000000ff) ^ dK[rk + 3])
|
||||
return _st32(r0) + _st32(r1) + _st32(r2) + _st32(r3)
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 8. GHASH (4-bit table + parallel)
|
||||
# ============================================================
|
||||
|
||||
def _gf_mul_bit(x, y):
|
||||
z = 0
|
||||
v = y
|
||||
for i in range(128):
|
||||
if (x >> (127 - i)) & 1:
|
||||
z ^= v
|
||||
if v & 1:
|
||||
v = (v >> 1) ^ R_CONST
|
||||
else:
|
||||
v >>= 1
|
||||
return z
|
||||
|
||||
|
||||
def _ghash_chunk_worker(args):
|
||||
s, e, data, H = args
|
||||
_ghash_init(H)
|
||||
y = 0
|
||||
for i in range(s, e, 16):
|
||||
blk = data[i:i + 16]
|
||||
if len(blk) < 16:
|
||||
blk = blk + b"\x00" * (16 - len(blk))
|
||||
y = _ghash_step(y, int.from_bytes(blk, "big"))
|
||||
return y
|
||||
|
||||
|
||||
def _ghash_parallel(data: bytes, H: int, n_workers: int) -> int:
|
||||
total_len = len(data)
|
||||
n_blocks = (total_len + 15) // 16
|
||||
if n_blocks < n_workers * 4:
|
||||
return _ghash_serial(data, H)
|
||||
per = (n_blocks + n_workers - 1) // n_workers
|
||||
ranges = []
|
||||
block_meta = []
|
||||
for k in range(n_workers):
|
||||
s_blk = k * per
|
||||
e_blk = min(s_blk + per, n_blocks)
|
||||
if s_blk >= n_blocks:
|
||||
break
|
||||
s = s_blk * 16
|
||||
e = min(e_blk * 16, total_len)
|
||||
ranges.append((s, e, data, H))
|
||||
block_meta.append((s_blk, e_blk))
|
||||
pool = _get_pool(n_workers)
|
||||
if pool is None:
|
||||
return _ghash_serial(data, H)
|
||||
T_list = list(pool.imap(_ghash_chunk_worker, ranges))
|
||||
_ghash_init(H)
|
||||
S = 0
|
||||
for k, T in enumerate(T_list):
|
||||
s_blk, e_blk = block_meta[k]
|
||||
suffix = n_blocks - e_blk
|
||||
for _ in range(suffix):
|
||||
T = _ghash_mul_H(T)
|
||||
S ^= T
|
||||
return S
|
||||
|
||||
|
||||
def _build_ghash_tables(H):
|
||||
vs = [H]
|
||||
for _ in range(127):
|
||||
v = vs[-1]
|
||||
if v & 1:
|
||||
v = (v >> 1) ^ R_CONST
|
||||
else:
|
||||
v >>= 1
|
||||
vs.append(v)
|
||||
tables = []
|
||||
for j in range(32):
|
||||
tbl = [0] * 16
|
||||
for n in range(16):
|
||||
r = 0
|
||||
for i in range(4):
|
||||
if (n >> i) & 1:
|
||||
r ^= vs[127 - 4*j - i]
|
||||
tbl[n] = r
|
||||
tables.append(tbl)
|
||||
return tables
|
||||
|
||||
|
||||
def _ghash_init(H):
|
||||
global _GHASH_H, _GHASH_TABLES
|
||||
_GHASH_H = H
|
||||
_GHASH_TABLES = _build_ghash_tables(H)
|
||||
|
||||
|
||||
def _ghash_step(y, blk_int):
|
||||
y ^= blk_int
|
||||
z = 0
|
||||
T = _GHASH_TABLES
|
||||
for j in range(32):
|
||||
z ^= T[j][(y >> (4 * j)) & 0xF]
|
||||
return z
|
||||
|
||||
|
||||
def _ghash_mul_H(x):
|
||||
z = 0
|
||||
T = _GHASH_TABLES
|
||||
for j in range(32):
|
||||
z ^= T[j][(x >> (4 * j)) & 0xF]
|
||||
return z
|
||||
|
||||
|
||||
def _ghash_serial(data, H):
|
||||
_ghash_init(H)
|
||||
y = 0
|
||||
for i in range(0, len(data), 16):
|
||||
blk = data[i:i+16]
|
||||
if len(blk) < 16:
|
||||
blk = blk + b"\x00" * (16 - len(blk))
|
||||
y = _ghash_step(y, int.from_bytes(blk, "big"))
|
||||
return y
|
||||
|
||||
|
||||
class AES:
|
||||
"""AES block cipher (ECB/CBC/CTR/CFB/OFB/GCM).
|
||||
|
||||
Unified error contract: argument validation failure / authentication failure both **return** an error 3-tuple
|
||||
``(error_code, error_message, suggestion)`` (see the module docstring for details).
|
||||
"""
|
||||
|
||||
def __init__(self, key: bytes):
|
||||
# Invalid key at initialization time -> the object cannot be constructed, a fatal error (see the _ppyc_error contract).
|
||||
_res = aes_key_expansion(key)
|
||||
if is_err(_res):
|
||||
raise PPYC_ERR(_res[0], _res[1], _res[2])
|
||||
self.key = key
|
||||
self.eK, self.dK, self.Nr = _res
|
||||
|
||||
# ---------- Block encryption ----------
|
||||
def encrypt_block(self, block: bytes) -> bytes:
|
||||
return aes_encrypt_block(block, self.eK, self.Nr)
|
||||
|
||||
def decrypt_block(self, block: bytes) -> bytes:
|
||||
return aes_decrypt_block(block, self.dK, self.Nr)
|
||||
|
||||
# ---------- ECB ----------
|
||||
def encrypt_ecb(self, data: bytes, n_workers: int = None) -> bytes:
|
||||
"""ECB encryption (PKCS#7 padding).
|
||||
|
||||
Returns
|
||||
----
|
||||
bytes : ciphertext (16-byte aligned).
|
||||
"""
|
||||
data = _pad_pkcs7(data)
|
||||
if n_workers and n_workers > 1 and len(data) > 64 * 1024 and _HAS_MP:
|
||||
chunks = self._split_chunks(data, n_workers)
|
||||
pool = _get_pool(n_workers)
|
||||
if pool is not None:
|
||||
args = [(c, self.eK, self.Nr) for c in chunks]
|
||||
return b"".join(pool.imap(_aes_enc_chunk_worker, args))
|
||||
out = bytearray()
|
||||
for i in range(0, len(data), 16):
|
||||
out += aes_encrypt_block(data[i:i + 16], self.eK, self.Nr)
|
||||
return bytes(out)
|
||||
|
||||
def decrypt_ecb(self, data: bytes, n_workers: int = None) -> bytes:
|
||||
"""ECB decryption (PKCS#7 unpadding).
|
||||
|
||||
Returns
|
||||
----
|
||||
bytes : plaintext.
|
||||
or an error 3-tuple:
|
||||
PPYC_ERR_INVALID_LENGTH the ciphertext length is not a multiple of 16;
|
||||
PPYC_ERR_INVALID_PADDING invalid PKCS#7 padding.
|
||||
"""
|
||||
if len(data) % 16:
|
||||
return err(PPYC_ERR_INVALID_LENGTH,
|
||||
f"ECB ciphertext length must be a multiple of 16, got {len(data)}",
|
||||
"pass a 16-byte aligned ciphertext produced by this library")
|
||||
if n_workers and n_workers > 1 and len(data) > 64 * 1024 and _HAS_MP:
|
||||
chunks = self._split_chunks(data, n_workers)
|
||||
pool = _get_pool(n_workers)
|
||||
if pool is not None:
|
||||
args = [(c, self.dK, self.Nr) for c in chunks]
|
||||
out = b"".join(pool.imap(_aes_dec_chunk_worker, args))
|
||||
return _unpad_or_err(out)
|
||||
out = bytearray()
|
||||
for i in range(0, len(data), 16):
|
||||
out += aes_decrypt_block(data[i:i + 16], self.dK, self.Nr)
|
||||
return _unpad_or_err(bytes(out))
|
||||
|
||||
# ---------- CBC ----------
|
||||
def encrypt_cbc(self, data: bytes, iv: bytes) -> bytes:
|
||||
"""CBC encryption (PKCS#7 padding).
|
||||
|
||||
Returns
|
||||
----
|
||||
bytes : ciphertext (16-byte aligned).
|
||||
or an error 3-tuple:
|
||||
PPYC_ERR_INVALID_IV_LEN the IV length is not 16 bytes.
|
||||
"""
|
||||
if len(iv) != 16:
|
||||
return err(PPYC_ERR_INVALID_IV_LEN,
|
||||
f"CBC IV must be 16 bytes, got {len(iv)}",
|
||||
"pass a 16 byte IV")
|
||||
data = _pad_pkcs7(data)
|
||||
out = bytearray()
|
||||
prev = iv
|
||||
for i in range(0, len(data), 16):
|
||||
blk = _xor_bytes(data[i:i + 16], prev)
|
||||
enc = aes_encrypt_block(blk, self.eK, self.Nr)
|
||||
out += enc
|
||||
prev = enc
|
||||
return bytes(out)
|
||||
|
||||
def decrypt_cbc(self, data: bytes, iv: bytes, n_workers: int = None) -> bytes:
|
||||
"""CBC decryption (PKCS#7 unpadding).
|
||||
|
||||
Returns
|
||||
----
|
||||
bytes : plaintext.
|
||||
or an error 3-tuple:
|
||||
PPYC_ERR_INVALID_IV_LEN the IV length is not 16 bytes;
|
||||
PPYC_ERR_INVALID_LENGTH the ciphertext length is not a multiple of 16;
|
||||
PPYC_ERR_INVALID_PADDING invalid PKCS#7 padding.
|
||||
"""
|
||||
if len(iv) != 16:
|
||||
return err(PPYC_ERR_INVALID_IV_LEN,
|
||||
f"CBC IV must be 16 bytes, got {len(iv)}",
|
||||
"pass a 16 byte IV")
|
||||
if len(data) % 16:
|
||||
return err(PPYC_ERR_INVALID_LENGTH,
|
||||
f"CBC ciphertext length must be a multiple of 16, got {len(data)}",
|
||||
"pass a 16-byte aligned ciphertext produced by this library")
|
||||
if n_workers and n_workers > 1 and len(data) > 64 * 1024 and _HAS_MP:
|
||||
chunks = self._split_chunks(data, n_workers)
|
||||
pool = _get_pool(n_workers)
|
||||
if pool is not None:
|
||||
args = [(c, self.dK, self.Nr) for c in chunks]
|
||||
dec = b"".join(pool.imap(_aes_dec_chunk_worker, args))
|
||||
else:
|
||||
dec = self._dec_blocks(data)
|
||||
else:
|
||||
dec = self._dec_blocks(data)
|
||||
out = bytearray()
|
||||
prev = iv
|
||||
for i in range(0, len(data), 16):
|
||||
out += _xor_bytes(dec[i:i + 16], prev)
|
||||
prev = data[i:i + 16]
|
||||
return _unpad_or_err(bytes(out))
|
||||
|
||||
def _dec_blocks(self, data: bytes) -> bytes:
|
||||
out = bytearray()
|
||||
for i in range(0, len(data), 16):
|
||||
out += aes_decrypt_block(data[i:i + 16], self.dK, self.Nr)
|
||||
return bytes(out)
|
||||
|
||||
# ---------- CTR ----------
|
||||
def encrypt_ctr(self, data: bytes, nonce: bytes, n_workers: int = None) -> bytes:
|
||||
"""CTR encryption (counter block = nonce(8) || counter(8), counter increments from 0).
|
||||
|
||||
Returns
|
||||
----
|
||||
bytes : ciphertext (same length as the plaintext).
|
||||
or an error 3-tuple:
|
||||
PPYC_ERR_INVALID_NONCE_LEN the nonce length is not 8 bytes.
|
||||
"""
|
||||
if len(nonce) != 8:
|
||||
return err(PPYC_ERR_INVALID_NONCE_LEN,
|
||||
f"CTR nonce must be 8 bytes, got {len(nonce)}",
|
||||
"pass an 8 byte nonce")
|
||||
nb = (len(data) + 15) // 16
|
||||
if not (n_workers and n_workers > 1 and nb > 4096 and _HAS_MP):
|
||||
out = bytearray()
|
||||
for i in range(nb):
|
||||
ks = aes_encrypt_block(nonce + i.to_bytes(8, "big"), self.eK, self.Nr)
|
||||
s = i * 16
|
||||
e = min(s + 16, len(data))
|
||||
out += _xor_bytes(data[s:e], ks[:e - s])
|
||||
return bytes(out)
|
||||
pool = _get_pool(n_workers)
|
||||
if pool is None:
|
||||
return self.encrypt_ctr(data, nonce, None)
|
||||
per = (nb + n_workers - 1) // n_workers
|
||||
ranges = []
|
||||
i = 0
|
||||
while i < nb:
|
||||
n = min(per, nb - i)
|
||||
ranges.append((i, n, self.eK, self.Nr, nonce))
|
||||
i += n
|
||||
ks = b"".join(pool.imap(_aes_ctr_chunk_worker, ranges))[:len(data)]
|
||||
return _xor_bytes(data, ks)
|
||||
|
||||
def decrypt_ctr(self, data: bytes, nonce: bytes, n_workers: int = None) -> bytes:
|
||||
"""CTR decryption (CTR encryption/decryption is symmetric; reuses encrypt_ctr internally).
|
||||
|
||||
Returns
|
||||
----
|
||||
bytes : plaintext;
|
||||
or an error 3-tuple: PPYC_ERR_INVALID_NONCE_LEN (the nonce is not 8 bytes).
|
||||
"""
|
||||
return self.encrypt_ctr(data, nonce, n_workers)
|
||||
|
||||
# ---------- CFB ----------
|
||||
def encrypt_cfb(self, data: bytes, iv: bytes) -> bytes:
|
||||
"""CFB encryption (128-bit segments).
|
||||
|
||||
Returns
|
||||
----
|
||||
bytes : ciphertext;
|
||||
or an error 3-tuple: PPYC_ERR_INVALID_IV_LEN (the IV is not 16 bytes).
|
||||
"""
|
||||
if len(iv) != 16:
|
||||
return err(PPYC_ERR_INVALID_IV_LEN,
|
||||
f"CFB IV must be 16 bytes, got {len(iv)}",
|
||||
"pass a 16 byte IV")
|
||||
out = bytearray()
|
||||
prev = iv
|
||||
for i in range(0, len(data), 16):
|
||||
ks = aes_encrypt_block(prev, self.eK, self.Nr)
|
||||
chunk = data[i:i + 16]
|
||||
blk = _xor_bytes(chunk, ks[:len(chunk)])
|
||||
out += blk
|
||||
prev = blk
|
||||
return bytes(out)
|
||||
|
||||
def decrypt_cfb(self, data: bytes, iv: bytes) -> bytes:
|
||||
"""CFB decryption.
|
||||
|
||||
Returns
|
||||
----
|
||||
bytes : plaintext;
|
||||
or an error 3-tuple: PPYC_ERR_INVALID_IV_LEN (the IV is not 16 bytes).
|
||||
"""
|
||||
if len(iv) != 16:
|
||||
return err(PPYC_ERR_INVALID_IV_LEN,
|
||||
f"CFB IV must be 16 bytes, got {len(iv)}",
|
||||
"pass a 16 byte IV")
|
||||
out = bytearray()
|
||||
prev = iv
|
||||
for i in range(0, len(data), 16):
|
||||
ks = aes_encrypt_block(prev, self.eK, self.Nr)
|
||||
chunk = data[i:i + 16]
|
||||
out += _xor_bytes(chunk, ks[:len(chunk)])
|
||||
prev = chunk
|
||||
return bytes(out)
|
||||
|
||||
# ---------- OFB ----------
|
||||
def encrypt_ofb(self, data: bytes, iv: bytes) -> bytes:
|
||||
"""OFB encryption.
|
||||
|
||||
Returns
|
||||
----
|
||||
bytes : ciphertext;
|
||||
or an error 3-tuple: PPYC_ERR_INVALID_IV_LEN (the IV is not 16 bytes).
|
||||
"""
|
||||
if len(iv) != 16:
|
||||
return err(PPYC_ERR_INVALID_IV_LEN,
|
||||
f"OFB IV must be 16 bytes, got {len(iv)}",
|
||||
"pass a 16 byte IV")
|
||||
out = bytearray()
|
||||
ks = iv
|
||||
for i in range(0, len(data), 16):
|
||||
ks = aes_encrypt_block(ks, self.eK, self.Nr)
|
||||
chunk = data[i:i + 16]
|
||||
out += _xor_bytes(chunk, ks[:len(chunk)])
|
||||
return bytes(out)
|
||||
|
||||
def decrypt_ofb(self, data: bytes, iv: bytes) -> bytes:
|
||||
"""OFB decryption (OFB encryption/decryption is symmetric; reuses encrypt_ofb internally).
|
||||
|
||||
Returns
|
||||
----
|
||||
bytes : plaintext;
|
||||
or an error 3-tuple: PPYC_ERR_INVALID_IV_LEN (the IV is not 16 bytes).
|
||||
"""
|
||||
return self.encrypt_ofb(data, iv)
|
||||
|
||||
# ---------- GCM ----------
|
||||
def gcm_encrypt(self, nonce: bytes, plaintext: bytes, aad: bytes = b"",
|
||||
n_workers: int = None) -> Tuple[bytes, bytes]:
|
||||
"""AES-GCM authenticated encryption.
|
||||
|
||||
Returns
|
||||
----
|
||||
(ct, tag) : a pair of the ciphertext and the 16-byte authentication tag;
|
||||
or an error 3-tuple:
|
||||
PPYC_ERR_INVALID_NONCE_LEN the nonce length is not 12 bytes.
|
||||
"""
|
||||
if len(nonce) != 12:
|
||||
return err(PPYC_ERR_INVALID_NONCE_LEN,
|
||||
f"GCM nonce must be 12 bytes, got {len(nonce)}",
|
||||
"pass a 12 byte nonce")
|
||||
H = int.from_bytes(aes_encrypt_block(b"\x00" * 16, self.eK, self.Nr), "big")
|
||||
J0 = nonce + b"\x00\x00\x00\x01"
|
||||
|
||||
nb = (len(plaintext) + 15) // 16
|
||||
if n_workers and n_workers > 1 and nb > 4096 and _HAS_MP:
|
||||
pool = _get_pool(n_workers)
|
||||
if pool is not None:
|
||||
per = (nb + n_workers - 1) // n_workers
|
||||
ranges = []
|
||||
for k in range(n_workers):
|
||||
s = k * per
|
||||
if s >= nb:
|
||||
break
|
||||
e = min(s + per, nb)
|
||||
ranges.append((2 + s, e - s, self.eK, self.Nr, nonce))
|
||||
ks = b"".join(pool.imap(_gcm_ctr_chunk_worker, ranges))[:len(plaintext)]
|
||||
ct = _xor_bytes(plaintext, ks)
|
||||
else:
|
||||
ct = self._gcm_ctr_serial(nonce, plaintext)
|
||||
else:
|
||||
ct = self._gcm_ctr_serial(nonce, plaintext)
|
||||
|
||||
aad_pad = aad + b"\x00" * ((16 - len(aad) % 16) % 16)
|
||||
ct_pad = ct + b"\x00" * ((16 - len(ct) % 16) % 16)
|
||||
lens = (len(aad) * 8).to_bytes(8, "big") + (len(ct) * 8).to_bytes(8, "big")
|
||||
ghash_data = aad_pad + ct_pad + lens
|
||||
|
||||
if n_workers and n_workers > 1 and len(ghash_data) > 64 * 1024 and _HAS_MP:
|
||||
S = _ghash_parallel(ghash_data, H, n_workers)
|
||||
else:
|
||||
S = _ghash_serial(ghash_data, H)
|
||||
|
||||
ek_j0 = aes_encrypt_block(J0, self.eK, self.Nr)
|
||||
tag = _xor_bytes(ek_j0, S.to_bytes(16, "big"))
|
||||
return ct, tag
|
||||
|
||||
def _gcm_ctr_serial(self, nonce: bytes, plaintext: bytes) -> bytes:
|
||||
ks = bytearray()
|
||||
ctr = 2
|
||||
nb = (len(plaintext) + 15) // 16
|
||||
for _ in range(nb):
|
||||
ks += aes_encrypt_block(nonce + ctr.to_bytes(4, "big"), self.eK, self.Nr)
|
||||
ctr += 1
|
||||
return _xor_bytes(plaintext, ks[:len(plaintext)])
|
||||
|
||||
def gcm_decrypt(self, nonce: bytes, ct: bytes, tag: bytes, aad: bytes = b"") -> bytes:
|
||||
"""AES-GCM authenticated decryption.
|
||||
|
||||
Returns
|
||||
----
|
||||
bytes : the plaintext when authentication succeeds;
|
||||
or an error 3-tuple (**no exception raised**):
|
||||
PPYC_ERR_INVALID_NONCE_LEN the nonce length is not 12 bytes;
|
||||
PPYC_ERR_INVALID_TAG the tag length is not 16 bytes;
|
||||
PPYC_ERR_AUTH_FAILED authentication failure (tag mismatch).
|
||||
|
||||
Note: success returns plaintext bytes and failure returns an error 3-tuple -- callers must first
|
||||
check whether the return value is an error tuple (first element is a string starting with ``PPYC_ERR_``).
|
||||
"""
|
||||
if len(nonce) != 12:
|
||||
return err(PPYC_ERR_INVALID_NONCE_LEN,
|
||||
f"GCM nonce must be 12 bytes, got {len(nonce)}",
|
||||
"pass a 12 byte nonce")
|
||||
# The authentication tag must be computed over the CIPHERTEXT directly; do not re-encrypt ct as plaintext.
|
||||
H = int.from_bytes(aes_encrypt_block(b"\x00" * 16, self.eK, self.Nr), "big")
|
||||
J0 = nonce + b"\x00\x00\x00\x01"
|
||||
aad_pad = aad + b"\x00" * ((16 - len(aad) % 16) % 16)
|
||||
ct_pad = ct + b"\x00" * ((16 - len(ct) % 16) % 16)
|
||||
lens = (len(aad) * 8).to_bytes(8, "big") + (len(ct) * 8).to_bytes(8, "big")
|
||||
ghash_data = aad_pad + ct_pad + lens
|
||||
S = _ghash_serial(ghash_data, H)
|
||||
ek_j0 = aes_encrypt_block(J0, self.eK, self.Nr)
|
||||
tag2 = _xor_bytes(ek_j0, S.to_bytes(16, "big"))
|
||||
if len(tag) != 16:
|
||||
return err(PPYC_ERR_INVALID_TAG,
|
||||
f"GCM authentication tag must be 16 bytes, got {len(tag)}",
|
||||
"pass a 16 byte GCM tag")
|
||||
if not _consttime_eq(tag, tag2):
|
||||
return err(PPYC_ERR_AUTH_FAILED,
|
||||
"GCM authentication failed: tag mismatch",
|
||||
"check that the key, nonce and AAD match, or whether the data was tampered with")
|
||||
return self._gcm_ctr_serial(nonce, ct)
|
||||
|
||||
# ---------- Helpers ----------
|
||||
@staticmethod
|
||||
def _split_chunks(data: bytes, n: int):
|
||||
total = len(data)
|
||||
if total == 0:
|
||||
return []
|
||||
chunk = (total // n + 15) // 16 * 16
|
||||
out = []
|
||||
i = 0
|
||||
while i < total:
|
||||
j = min(i + chunk, total)
|
||||
if j < total and j % 16 != 0:
|
||||
j = (j // 16) * 16
|
||||
out.append(data[i:j])
|
||||
i = j
|
||||
return out
|
||||
|
||||
|
||||
# ---- AES multiprocessing worker (top level) ----
|
||||
|
||||
def _aes_enc_chunk_worker(args):
|
||||
chunk, eK, Nr = args
|
||||
out = bytearray()
|
||||
for i in range(0, len(chunk), 16):
|
||||
out += aes_encrypt_block(chunk[i:i + 16], eK, Nr)
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def _aes_dec_chunk_worker(args):
|
||||
chunk, dK, Nr = args
|
||||
out = bytearray()
|
||||
for i in range(0, len(chunk), 16):
|
||||
out += aes_decrypt_block(chunk[i:i + 16], dK, Nr)
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def _aes_ctr_chunk_worker(args):
|
||||
start_i, n_blocks, eK, Nr, nonce = args
|
||||
out = bytearray()
|
||||
for j in range(n_blocks):
|
||||
i = start_i + j
|
||||
out += aes_encrypt_block(nonce + i.to_bytes(8, "big"), eK, Nr)
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def _gcm_ctr_chunk_worker(args):
|
||||
ctr, n_blocks, eK, Nr, nonce = args
|
||||
out = bytearray()
|
||||
for j in range(n_blocks):
|
||||
ctr_block = nonce + ((ctr + j) & MASK32).to_bytes(4, "big")
|
||||
out += aes_encrypt_block(ctr_block, eK, Nr)
|
||||
return bytes(out)
|
||||
@@ -0,0 +1,644 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""purepycrypto.aes_gcm_siv
|
||||
========================================
|
||||
purepycrypto - Pure-Python cryptography library (zero dependencies)
|
||||
AES-GCM-SIV (RFC 8452) -- a nonce-misuse resistant AEAD.
|
||||
|
||||
Standard
|
||||
----
|
||||
This module implements the two AEADs defined by IETF RFC 8452:
|
||||
AEAD_AES_128_GCM_SIV (16-byte key)
|
||||
AEAD_AES_256_GCM_SIV (32-byte key)
|
||||
The key is a "key-generating key", the nonce is fixed at 96 (12) bits, and the authentication tag is fixed at 16 bytes.
|
||||
AES block encryption, the POLYVAL polynomial authenticator and CTR counter mode all follow RFC 8452 sections 4/5 strictly.
|
||||
|
||||
How nonce-misuse resistance works
|
||||
------------------
|
||||
With classic AES-GCM, once a (key, nonce) pair is reused, keystream reuse directly leaks the XOR of the plaintexts, and the GHASH
|
||||
authentication subkey H is reused as well, allowing an attacker to forge tags -- a catastrophic failure.
|
||||
AES-GCM-SIV uses the "SIV (Synthetic IV)" construction, which avoids this flaw:
|
||||
|
||||
1. First derive a *per-message* message-authentication-key and message-encryption-key
|
||||
from the key-generating key and the nonce:
|
||||
DERIVE = AES(K, LE32(counter) || nonce), taking the first half (8 bytes) of each ciphertext block and concatenating.
|
||||
2. Use the authentication-key to run POLYVAL over (AAD || plaintext || length block), yielding the synthetic value S_s;
|
||||
XOR the first 12 bytes of S_s with the nonce, clear the top bit of the last byte, then encrypt with the encryption-key
|
||||
to obtain the tag (the synthetic IV).
|
||||
3. Encrypt the plaintext using the tag as the initial CTR counter value (with the top bit of the last byte set).
|
||||
|
||||
So even if the nonce repeats, as long as the plaintext / AAD differ the tag (i.e. the effective CTR initial value) differs too,
|
||||
and the keystream is never reused; under a repeated nonce an attacker can at most tell whether two messages are identical --
|
||||
exactly the minimal information a deterministic algorithm can leak. The cost is that encryption needs two passes (authenticate, then encrypt),
|
||||
which is slower than AES-GCM, in exchange for strong security under offline nonce attacks.
|
||||
|
||||
Usage
|
||||
----
|
||||
from purepycrypto.aes_gcm_siv import (
|
||||
aes128_gcm_siv_encrypt, aes128_gcm_siv_decrypt,
|
||||
aes256_gcm_siv_encrypt, aes256_gcm_siv_decrypt,
|
||||
aes_gcm_siv_encrypt, aes_gcm_siv_decrypt,
|
||||
)
|
||||
|
||||
key = b"0" * 16
|
||||
nonce = b"\x00" * 12 # must be 12 bytes
|
||||
ct, tag = aes128_gcm_siv_encrypt(key, nonce, b"hello", aad=b"header")
|
||||
pt = aes128_gcm_siv_decrypt(key, nonce, ct, tag, aad=b"header") # b"hello"
|
||||
|
||||
# The unified entry point dispatches automatically by key length (16 / 32)
|
||||
ct, tag = aes_gcm_siv_encrypt(key, nonce, b"hello")
|
||||
|
||||
Unified error system (see purepycrypto._ppyc_error)
|
||||
------------------------------------------
|
||||
* Argument validation failure (invalid key / nonce / tag / length) -> **return** a 3-tuple
|
||||
``(error_code, error_message, suggestion)`` instead of raising an exception;
|
||||
* Authentication failure (tampered ciphertext / tag / AAD) -> **return**
|
||||
``err(PPYC_ERR_AUTH_FAILED, ...)``;
|
||||
* On success ``encrypt`` returns a ``(ct, tag)`` pair and ``decrypt`` returns plaintext bytes.
|
||||
|
||||
Windows multiprocessing note (important)
|
||||
---------------------------------
|
||||
For large inputs (default >= 128KB) with `n_workers=None` (auto) or `n_workers>1`, this module
|
||||
generates the CTR keystream in parallel using a `multiprocessing` pool. On Windows child processes
|
||||
are started with **spawn** (the main module is re-imported), so **the caller script must be wrapped
|
||||
in `if __name__ == "__main__":`**, otherwise the following is raised:
|
||||
|
||||
RuntimeError: An attempt has been made to start a new process before
|
||||
the current process has finished its bootstrapping phase.
|
||||
... you have forgotten to use the proper idiom in the main module:
|
||||
if __name__ == '__main__':
|
||||
freeze_support()
|
||||
|
||||
Correct form:
|
||||
|
||||
from purepycrypto import aes256_gcm_siv_encrypt
|
||||
|
||||
def main():
|
||||
ct, tag = aes256_gcm_siv_encrypt(key, nonce, data) # large inputs use multiprocessing automatically
|
||||
|
||||
if __name__ == "__main__": # <- REQUIRED on Windows
|
||||
main()
|
||||
|
||||
Workarounds:
|
||||
* Add the `if __name__ == "__main__":` guard (recommended);
|
||||
* Or pass `n_workers=1` explicitly to force serial execution (no multiprocessing startup cost, faster for small data).
|
||||
|
||||
Linux / macOS use fork and usually have no such restriction (adding the guard is still recommended for cross-platform consistency).
|
||||
|
||||
References
|
||||
--------
|
||||
RFC 8452: AES-GCM-SIV: Nonce Misuse-Resistant Authenticated Encryption.
|
||||
"""
|
||||
|
||||
import os
|
||||
from typing import Tuple
|
||||
|
||||
from .aes import AES, aes_encrypt_block
|
||||
from .common import MASK32, _consttime_eq
|
||||
from ._ppyc_error import (
|
||||
PPYC_ERR, err, ok, OK_TUPLE, is_err,
|
||||
PPYC_ERR_INVALID_KEY_LEN, PPYC_ERR_INVALID_NONCE_LEN,
|
||||
PPYC_ERR_INVALID_LENGTH, PPYC_ERR_INVALID_TAG,
|
||||
PPYC_ERR_INPUT_TOO_LARGE, PPYC_ERR_AUTH_FAILED,
|
||||
)
|
||||
from .parallel import _HAS_MP, _get_pool
|
||||
|
||||
|
||||
__all__ = [
|
||||
"aes128_gcm_siv_encrypt", "aes128_gcm_siv_decrypt",
|
||||
"aes256_gcm_siv_encrypt", "aes256_gcm_siv_decrypt",
|
||||
"aes_gcm_siv_encrypt", "aes_gcm_siv_decrypt",
|
||||
"polyval",
|
||||
"set_cache_enabled", "cache_enabled", "clear_caches",
|
||||
"_SIV_TAG_LEN", "_SIV_NONCE_LEN", "MAX_INPUT_BYTES",
|
||||
]
|
||||
|
||||
_SIV_TAG_LEN = 16
|
||||
_SIV_NONCE_LEN = 12
|
||||
# Minimum block size at which multiprocessing is enabled automatically (128KB); below this the startup cost is not worthwhile.
|
||||
_AUTO_MP_MIN_BLOCKS = 8192
|
||||
# RFC 8452 sections 4/5: the AAD, plaintext and ciphertext lengths must not exceed 2^36 bytes; longer inputs must be rejected.
|
||||
MAX_INPUT_BYTES = 1 << 36
|
||||
|
||||
_SIV_MASK128 = (1 << 128) - 1
|
||||
|
||||
# GF(2^128), irreducible polynomial x^128 + x^127 + x^126 + x^121 + 1.
|
||||
# Bit convention of RFC 8452 section 3: bit i of the integer is the coefficient of x^i
|
||||
# (the lowest bit of the first byte is x^0 and the highest bit of the last byte is x^127),
|
||||
# so a 16-byte block <-> integer converts directly with int.from_bytes(bs, "little").
|
||||
_POLY = (1 << 128) | (1 << 127) | (1 << 126) | (1 << 121) | 1
|
||||
# x^-128 = x^127 + x^124 + x^121 + x^114 + 1 (RFC 8452 section 3)
|
||||
_INV128 = (1 << 127) | (1 << 124) | (1 << 121) | (1 << 114) | 1
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 11. POLYVAL (RFC 8452 section 3)
|
||||
# ============================================================
|
||||
#
|
||||
# POLYVAL shares the field with GHASH (the same polynomial P) but uses the opposite bit/byte order convention (little-endian).
|
||||
# Definition: S_0 = 0; S_j = dot(S_{j-1} + X_j, H), j = 1..s.
|
||||
# dot(a, b) = a * b * x^-128 (field multiplication)
|
||||
# Implemented directly from the definition: for a fixed key H, dot(., H) is a linear map over GF(2),
|
||||
# so it can be accelerated with a 4-bit lookup table (32 tables of 16 entries), like the GHASH table method in aes.py.
|
||||
|
||||
def _poly_mul(a: int, b: int) -> int:
|
||||
"""Polynomial multiplication in GF(2^128) modulo _POLY (little-endian bit convention)."""
|
||||
p = 0
|
||||
while b:
|
||||
if b & 1:
|
||||
p ^= a
|
||||
b >>= 1
|
||||
a <<= 1
|
||||
# Reduction: cancel bits from the high end down to 128 bits, one bit at a time
|
||||
for i in range(p.bit_length() - 1, 127, -1):
|
||||
if (p >> i) & 1:
|
||||
p ^= _POLY << (i - 128)
|
||||
return p & _SIV_MASK128
|
||||
|
||||
|
||||
_POLYVAL_TABLE_CACHE = {} # h -> tables; avoids rebuilding the table for the same authentication key
|
||||
_POLYVAL_TABLE_CACHE_MAX = 8
|
||||
|
||||
# Master cache switch (performance vs. key material residing in memory).
|
||||
# Default True: performance first. If your threat model does not allow derived keys / lookup tables to reside in
|
||||
# process memory, call set_cache_enabled(False) to disable it (this significantly reduces small-message performance).
|
||||
_CACHE_ENABLED = True
|
||||
|
||||
|
||||
def set_cache_enabled(enabled: bool) -> None:
|
||||
"""Toggle the internal caches (POLYVAL lookup table cache + derived key cache).
|
||||
|
||||
Parameters
|
||||
----
|
||||
enabled : True = enabled (default, best performance); False = disabled, and existing caches are cleared.
|
||||
|
||||
Notes
|
||||
----
|
||||
The cache keeps derived keys and lookup table results in process memory in exchange for a significant
|
||||
performance gain (up to 8x for small messages; large multiprocessing workloads benefit from avoiding rebuilds).
|
||||
When disabled, everything is re-derived / rebuilt on every call: safer but noticeably slower.
|
||||
"""
|
||||
global _CACHE_ENABLED
|
||||
_CACHE_ENABLED = bool(enabled)
|
||||
if not _CACHE_ENABLED:
|
||||
_POLYVAL_TABLE_CACHE.clear()
|
||||
_DERIVE_CACHE.clear()
|
||||
|
||||
|
||||
def cache_enabled() -> bool:
|
||||
"""Return the current cache switch state."""
|
||||
return _CACHE_ENABLED
|
||||
|
||||
|
||||
def clear_caches() -> None:
|
||||
"""Manually clear the internal caches (does not change the switch state)."""
|
||||
_POLYVAL_TABLE_CACHE.clear()
|
||||
_DERIVE_CACHE.clear()
|
||||
|
||||
|
||||
def _polyval_tables(h: int):
|
||||
"""Precompute the POLYVAL lookup table for key H: T[i] = dot(x^i, H), then fold by nibble.
|
||||
|
||||
Performance: building the table takes 128 shifts + 512 table-entry combinations, which for **small messages**
|
||||
costs far more than the actual POLYVAL computation, so it is cached per H (LRU-style, capacity _POLYVAL_TABLE_CACHE_MAX).
|
||||
"""
|
||||
if _CACHE_ENABLED:
|
||||
cached = _POLYVAL_TABLE_CACHE.get(h)
|
||||
if cached is not None:
|
||||
return cached
|
||||
# base = dot(x^0, H) = H * x^-128
|
||||
base = _poly_mul(h, _INV128)
|
||||
vs = [base]
|
||||
for _ in range(127):
|
||||
v = vs[-1] << 1
|
||||
if v & (1 << 128):
|
||||
v ^= _POLY
|
||||
vs.append(v & _SIV_MASK128)
|
||||
tables = []
|
||||
for j in range(32):
|
||||
tbl = [0] * 16
|
||||
for n in range(16):
|
||||
r = 0
|
||||
for k in range(4):
|
||||
if (n >> k) & 1:
|
||||
r ^= vs[4 * j + k]
|
||||
tbl[n] = r
|
||||
tables.append(tbl)
|
||||
if _CACHE_ENABLED:
|
||||
if len(_POLYVAL_TABLE_CACHE) >= _POLYVAL_TABLE_CACHE_MAX:
|
||||
_POLYVAL_TABLE_CACHE.pop(next(iter(_POLYVAL_TABLE_CACHE)))
|
||||
_POLYVAL_TABLE_CACHE[h] = tables
|
||||
return tables
|
||||
|
||||
|
||||
def _polyval_lookup(y: int, tables) -> int:
|
||||
"""dot(y, H) = XOR_j tables[j][ (y >> 4j) & 0xF ]."""
|
||||
z = 0
|
||||
for j in range(32):
|
||||
z ^= tables[j][(y >> (4 * j)) & 0xF]
|
||||
return z
|
||||
|
||||
|
||||
def polyval(h: bytes, data: bytes) -> bytes:
|
||||
"""POLYVAL(H, data): the data length must be a multiple of 16; returns a 16-byte digest.
|
||||
|
||||
Standalone public interface (useful for unit tests / cross-validation); the AEAD reuses the precomputed table internally.
|
||||
|
||||
Returns
|
||||
----
|
||||
bytes : 16-byte digest;
|
||||
or an error 3-tuple:
|
||||
PPYC_ERR_INVALID_KEY_LEN the key is not 16 bytes;
|
||||
PPYC_ERR_INVALID_LENGTH the data length is not a multiple of 16.
|
||||
"""
|
||||
if len(h) != 16:
|
||||
return err(PPYC_ERR_INVALID_KEY_LEN,
|
||||
f"POLYVAL key must be 16 bytes, got {len(h)}",
|
||||
"pass a 16 byte POLYVAL authentication key")
|
||||
if len(data) % 16:
|
||||
return err(PPYC_ERR_INVALID_LENGTH,
|
||||
f"POLYVAL input length must be a multiple of 16, got {len(data)}",
|
||||
"pad the input to a multiple of 16 bytes")
|
||||
tables = _polyval_tables(int.from_bytes(h, "little"))
|
||||
y = 0
|
||||
for i in range(0, len(data), 16):
|
||||
y = _polyval_lookup(y ^ int.from_bytes(data[i:i + 16], "little"), tables)
|
||||
return y.to_bytes(16, "little")
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 12. AES-GCM-SIV (RFC 8452 sections 4/5)
|
||||
# ============================================================
|
||||
|
||||
_DERIVE_CACHE = {} # key -> (auth_key, enc_key); avoids re-deriving for the same key
|
||||
_DERIVE_CACHE_MAX = 8
|
||||
|
||||
|
||||
def _derive_keys(key: bytes, nonce: bytes) -> Tuple[bytes, bytes]:
|
||||
"""Derive (message_authentication_key, message_encryption_key).
|
||||
|
||||
DERIVE = AES(K, LE32(counter) ++ nonce), taking the first 8 bytes of each block:
|
||||
auth = blk[0][:8] ++ blk[1][:8] (128 bit)
|
||||
enc = blk[2][:8] ++ blk[3][:8] (+ blk[4][:8] ++ blk[5][:8]) (128/256 bit)
|
||||
counter is a 4-byte little-endian value in the range 0..3 (AES-128) or 0..5 (AES-256).
|
||||
|
||||
Performance: repeated calls with the same (key, nonce) hit the cache (LRU-style, capacity _DERIVE_CACHE_MAX),
|
||||
saving one AES key expansion (about 72us for AES-128 / 107us for AES-256),
|
||||
which is especially noticeable for small messages. The cache stores only derivation results; no extra key material is kept.
|
||||
"""
|
||||
ck = (key, nonce)
|
||||
if _CACHE_ENABLED:
|
||||
hit = _DERIVE_CACHE.get(ck)
|
||||
if hit is not None:
|
||||
return hit
|
||||
aes = AES(key)
|
||||
n_blocks = 6 if len(key) == 32 else 4
|
||||
stream = bytearray()
|
||||
for ctr in range(n_blocks):
|
||||
stream += aes.encrypt_block(ctr.to_bytes(4, "little") + nonce)
|
||||
auth_key = bytes(stream[0:8] + stream[16:24])
|
||||
enc_key = bytes(stream[32:40] + stream[48:56])
|
||||
if len(key) == 32:
|
||||
enc_key += bytes(stream[64:72] + stream[80:88])
|
||||
if _CACHE_ENABLED:
|
||||
if len(_DERIVE_CACHE) >= _DERIVE_CACHE_MAX:
|
||||
_DERIVE_CACHE.pop(next(iter(_DERIVE_CACHE)))
|
||||
_DERIVE_CACHE[ck] = (auth_key, enc_key)
|
||||
return auth_key, enc_key
|
||||
|
||||
|
||||
def _auth_tag(auth_key: bytes, enc_aes: AES, nonce: bytes,
|
||||
aad: bytes, plaintext: bytes) -> bytes:
|
||||
"""Compute the 16-byte tag per RFC 8452 section 4.
|
||||
|
||||
length_block = LE64(len(aad)*8) ++ LE64(len(pt)*8)
|
||||
S_s = POLYVAL(auth_key, pad16(aad) ++ pad16(pt) ++ length_block)
|
||||
S_s[0:12] ^= nonce; S_s[15] &= 0x7f; tag = AES(enc_key, S_s)
|
||||
|
||||
Full-block (length exactly a multiple of 16) boundary convention -- matching RFC 8452 section 4 step by step:
|
||||
* pad16(n) adds **no block at all** when n is already a multiple of 16 (zero bytes of padding),
|
||||
rather than appending an all-zero block; a length of 0 likewise produces no block.
|
||||
Hence len%16==0 and len%16==8 may produce the same padding,
|
||||
and the real distinction comes from the **bit** length in length_block.
|
||||
* length_block = LE64(len(aad)*8) || LE64(len(pt)*8),
|
||||
in bits (not bytes), each as an 8-byte little-endian value.
|
||||
* The total POLYVAL input length is a multiple of 16, because aad and pt are each zero-padded to whole blocks,
|
||||
plus the 16-byte length_block.
|
||||
"""
|
||||
tables = _polyval_tables(int.from_bytes(auth_key, "little"))
|
||||
pad_aad = aad + b"\x00" * ((16 - (len(aad) & 15)) & 15)
|
||||
pad_pt = plaintext + b"\x00" * ((16 - (len(plaintext) & 15)) & 15)
|
||||
length_block = ((len(aad) * 8).to_bytes(8, "little") +
|
||||
(len(plaintext) * 8).to_bytes(8, "little"))
|
||||
|
||||
y = 0
|
||||
buf = pad_aad + pad_pt + length_block
|
||||
for i in range(0, len(buf), 16):
|
||||
y = _polyval_lookup(y ^ int.from_bytes(buf[i:i + 16], "little"), tables)
|
||||
|
||||
block = bytearray(y.to_bytes(16, "little"))
|
||||
for i in range(_SIV_NONCE_LEN):
|
||||
block[i] ^= nonce[i]
|
||||
block[15] &= 0x7F
|
||||
return enc_aes.encrypt_block(bytes(block))
|
||||
|
||||
|
||||
# ---- Multiprocessing CTR worker (top-level function so the pool can pickle it) ----
|
||||
|
||||
def _ctr_chunk_worker(args):
|
||||
"""CTR shard worker: processes the keystream for [start_block, start_block+n).
|
||||
|
||||
Args: (eK, Nr, tail, start_ctr, n_blocks)
|
||||
Returns: the keystream bytes for this shard (16*n_blocks bytes).
|
||||
"""
|
||||
eK, Nr, tail, start_ctr, n_blocks = args
|
||||
to_bytes = int.to_bytes
|
||||
M32 = 0xFFFFFFFF
|
||||
out = bytearray()
|
||||
ctr = start_ctr
|
||||
for _ in range(n_blocks):
|
||||
out += aes_encrypt_block(to_bytes(ctr & M32, 4, "little") + tail, eK, Nr)
|
||||
ctr += 1
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def _ctr_xor(enc_aes: AES, tag: bytes, data: bytes, n_workers: int = None) -> bytes:
|
||||
"""AES-CTR initialized with the tag (top bit of the last byte set).
|
||||
|
||||
RFC 8452 section 4:
|
||||
|
||||
counter_block = tag; counter_block[15] |= 0x80
|
||||
counter = counter_block[0:4] interpreted as a little-endian unsigned 32-bit integer;
|
||||
each block increments the counter by 1, **wrapping at 2^32**,
|
||||
counter block = LE32(counter) || tag[4:16].
|
||||
|
||||
* Empty data -> no CTR block is produced (the tag is still computed as for an empty plaintext).
|
||||
* Counter wrap-around is specifically covered by RFC 8452 Appendix C.3 (Counter Wrap Tests);
|
||||
the block after an initial value of 0xffffffff must be 0x00000000 -- guaranteed here with & MASK32.
|
||||
* When the data length is exactly a multiple of 16, the last block is a full block and no extra block is computed.
|
||||
"""
|
||||
if not data:
|
||||
return b""
|
||||
init = bytearray(tag)
|
||||
init[15] |= 0x80
|
||||
tail = bytes(init[4:16])
|
||||
ctr = int.from_bytes(init[:4], "little")
|
||||
|
||||
# ---- Multiprocessing branch: split keystream generation across processes for large inputs ----
|
||||
n = len(data)
|
||||
n_blocks = (n + 15) // 16
|
||||
if n_workers is None and _HAS_MP and n_blocks >= _AUTO_MP_MIN_BLOCKS:
|
||||
# Default auto: enable multiprocessing for large inputs (process count = CPU count, capped at 8, where gains saturate)
|
||||
n_workers = min(os.cpu_count() or 1, 8)
|
||||
if (n_workers and n_workers > 1 and n_blocks >= _AUTO_MP_MIN_BLOCKS and _HAS_MP):
|
||||
pool = _get_pool(n_workers)
|
||||
if pool is not None:
|
||||
per = (n_blocks + n_workers - 1) // n_workers
|
||||
jobs = []
|
||||
b = 0
|
||||
while b < n_blocks:
|
||||
cnt = min(per, n_blocks - b)
|
||||
jobs.append((enc_aes.eK, enc_aes.Nr, tail, (ctr + b) & 0xFFFFFFFF, cnt))
|
||||
b += cnt
|
||||
ks = b"".join(pool.imap(_ctr_chunk_worker, jobs))[:n]
|
||||
# Integer XOR (little-endian), then restore to n bytes
|
||||
return (int.from_bytes(data, "little") ^
|
||||
int.from_bytes(ks, "little")).to_bytes(n, "little")
|
||||
|
||||
encrypt_block = enc_aes.encrypt_block # bind to a local name to reduce attribute lookups
|
||||
to_bytes = int.to_bytes
|
||||
from_bytes = int.from_bytes
|
||||
M32 = 0xFFFFFFFF
|
||||
n = len(data)
|
||||
out = bytearray(n)
|
||||
pos = 0
|
||||
full = n - (n & 15) # length of the whole-block part
|
||||
while pos < full:
|
||||
ks = encrypt_block(to_bytes(ctr & M32, 4, "little") + tail)
|
||||
ctr += 1
|
||||
# Integer XOR: 16 bytes at once, avoiding a per-byte Python loop
|
||||
out[pos:pos + 16] = to_bytes(
|
||||
from_bytes(data[pos:pos + 16], "little") ^ from_bytes(ks, "little"),
|
||||
16, "little")
|
||||
pos += 16
|
||||
if pos < n: # trailing partial block of fewer than 16 bytes
|
||||
ks = encrypt_block(to_bytes(ctr & M32, 4, "little") + tail)
|
||||
rem = n - pos
|
||||
chunk = data[pos:]
|
||||
out[pos:] = bytes(x ^ y for x, y in zip(chunk, ks[:rem]))
|
||||
ctr = (ctr + 1) & MASK32
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def _check_key_nonce(key: bytes, nonce: bytes):
|
||||
"""Validate the key / nonce lengths.
|
||||
|
||||
Returns
|
||||
----
|
||||
None : validation passed;
|
||||
or an error 3-tuple: PPYC_ERR_INVALID_KEY_LEN / PPYC_ERR_INVALID_NONCE_LEN.
|
||||
"""
|
||||
if len(key) not in (16, 32):
|
||||
return err(PPYC_ERR_INVALID_KEY_LEN,
|
||||
f"AES-GCM-SIV key length must be 16 or 32 bytes, got {len(key)}",
|
||||
"pass a 16 or 32 byte key")
|
||||
if len(nonce) != _SIV_NONCE_LEN:
|
||||
return err(PPYC_ERR_INVALID_NONCE_LEN,
|
||||
f"AES-GCM-SIV nonce must be 12 bytes, got {len(nonce)}",
|
||||
"pass a 12 byte nonce")
|
||||
return None
|
||||
|
||||
|
||||
def _check_length(*parts: bytes):
|
||||
"""RFC 8452 sections 4/5: any input exceeding 2^36 bytes must fail.
|
||||
|
||||
Returns
|
||||
----
|
||||
None : all valid;
|
||||
or an error 3-tuple: PPYC_ERR_INPUT_TOO_LARGE.
|
||||
"""
|
||||
for p in parts:
|
||||
if len(p) > MAX_INPUT_BYTES:
|
||||
return err(PPYC_ERR_INPUT_TOO_LARGE,
|
||||
f"AES-GCM-SIV input length exceeds the RFC 8452 limit (2^36 bytes), "
|
||||
f"got {len(p)}",
|
||||
"shorten the AAD / plaintext / ciphertext so each part is at most 2^36 bytes")
|
||||
return None
|
||||
|
||||
|
||||
def _seal(key: bytes, nonce: bytes, plaintext: bytes, aad: bytes,
|
||||
n_workers: int = None):
|
||||
_len_err = _check_length(aad, plaintext)
|
||||
if _len_err is not None:
|
||||
return _len_err
|
||||
auth_key, enc_key = _derive_keys(key, nonce)
|
||||
enc_aes = AES(enc_key)
|
||||
tag = _auth_tag(auth_key, enc_aes, nonce, aad, plaintext)
|
||||
ct = _ctr_xor(enc_aes, tag, plaintext, n_workers)
|
||||
return ct, tag
|
||||
|
||||
|
||||
def _open(key: bytes, nonce: bytes, ct: bytes, tag: bytes, aad: bytes,
|
||||
n_workers: int = None) -> bytes:
|
||||
if len(tag) != _SIV_TAG_LEN:
|
||||
return err(PPYC_ERR_INVALID_TAG,
|
||||
f"AES-GCM-SIV tag length must be 16 bytes, got {len(tag)}",
|
||||
"pass a 16 byte authentication tag")
|
||||
_len_err = _check_length(aad, ct)
|
||||
if _len_err is not None:
|
||||
return _len_err
|
||||
auth_key, enc_key = _derive_keys(key, nonce)
|
||||
enc_aes = AES(enc_key)
|
||||
# Decrypt first (untrusted), then verify; plaintext is never returned when verification fails
|
||||
plaintext = _ctr_xor(enc_aes, tag, ct, n_workers)
|
||||
expected = _auth_tag(auth_key, enc_aes, nonce, aad, plaintext)
|
||||
if not _consttime_eq(expected, tag):
|
||||
return err(PPYC_ERR_AUTH_FAILED,
|
||||
"AES-GCM-SIV authentication failed: tag mismatch",
|
||||
"check that the key, nonce and AAD match, or whether the data was tampered with")
|
||||
return plaintext
|
||||
|
||||
|
||||
# ---------- AES-128 ----------
|
||||
|
||||
def aes128_gcm_siv_encrypt(key: bytes, nonce: bytes, plaintext: bytes,
|
||||
aad: bytes = b"",
|
||||
n_workers: int = None) -> Tuple[bytes, bytes]:
|
||||
"""AEAD_AES_128_GCM_SIV encryption.
|
||||
|
||||
Returns
|
||||
----
|
||||
(ct, tag) : ciphertext and 16-byte tag;
|
||||
or an error 3-tuple:
|
||||
PPYC_ERR_INVALID_KEY_LEN the key is not 16 bytes;
|
||||
PPYC_ERR_INVALID_NONCE_LEN the nonce is not 12 bytes;
|
||||
PPYC_ERR_INPUT_TOO_LARGE the AAD / plaintext exceeds 2^36 bytes.
|
||||
"""
|
||||
if len(key) != 16:
|
||||
return err(PPYC_ERR_INVALID_KEY_LEN,
|
||||
f"AES-128-GCM-SIV key must be 16 bytes, got {len(key)}",
|
||||
"pass a 16 byte key")
|
||||
if len(nonce) != _SIV_NONCE_LEN:
|
||||
return err(PPYC_ERR_INVALID_NONCE_LEN,
|
||||
f"AES-128-GCM-SIV nonce must be 12 bytes, got {len(nonce)}",
|
||||
"pass a 12 byte nonce")
|
||||
return _seal(bytes(key), bytes(nonce), bytes(plaintext), bytes(aad), n_workers)
|
||||
|
||||
|
||||
def aes128_gcm_siv_decrypt(key: bytes, nonce: bytes, ct: bytes, tag: bytes,
|
||||
aad: bytes = b"",
|
||||
n_workers: int = None) -> bytes:
|
||||
"""AEAD_AES_128_GCM_SIV decryption.
|
||||
|
||||
Returns
|
||||
----
|
||||
bytes : the plaintext when authentication succeeds;
|
||||
or an error 3-tuple (**no exception raised**):
|
||||
PPYC_ERR_INVALID_KEY_LEN the key is not 16 bytes;
|
||||
PPYC_ERR_INVALID_NONCE_LEN the nonce is not 12 bytes;
|
||||
PPYC_ERR_INVALID_TAG the tag is not 16 bytes;
|
||||
PPYC_ERR_INPUT_TOO_LARGE the AAD / ciphertext exceeds 2^36 bytes;
|
||||
PPYC_ERR_AUTH_FAILED authentication failure.
|
||||
"""
|
||||
if len(key) != 16:
|
||||
return err(PPYC_ERR_INVALID_KEY_LEN,
|
||||
f"AES-128-GCM-SIV key must be 16 bytes, got {len(key)}",
|
||||
"pass a 16 byte key")
|
||||
if len(nonce) != _SIV_NONCE_LEN:
|
||||
return err(PPYC_ERR_INVALID_NONCE_LEN,
|
||||
f"AES-128-GCM-SIV nonce must be 12 bytes, got {len(nonce)}",
|
||||
"pass a 12 byte nonce")
|
||||
return _open(bytes(key), bytes(nonce), bytes(ct), bytes(tag), bytes(aad), n_workers)
|
||||
|
||||
|
||||
# ---------- AES-256 ----------
|
||||
|
||||
def aes256_gcm_siv_encrypt(key: bytes, nonce: bytes, plaintext: bytes,
|
||||
aad: bytes = b"",
|
||||
n_workers: int = None) -> Tuple[bytes, bytes]:
|
||||
"""AEAD_AES_256_GCM_SIV encryption.
|
||||
|
||||
Returns
|
||||
----
|
||||
(ct, tag) : ciphertext and 16-byte tag;
|
||||
or an error 3-tuple:
|
||||
PPYC_ERR_INVALID_KEY_LEN the key is not 32 bytes;
|
||||
PPYC_ERR_INVALID_NONCE_LEN the nonce is not 12 bytes;
|
||||
PPYC_ERR_INPUT_TOO_LARGE the AAD / plaintext exceeds 2^36 bytes.
|
||||
"""
|
||||
if len(key) != 32:
|
||||
return err(PPYC_ERR_INVALID_KEY_LEN,
|
||||
f"AES-256-GCM-SIV key must be 32 bytes, got {len(key)}",
|
||||
"pass a 32 byte key")
|
||||
if len(nonce) != _SIV_NONCE_LEN:
|
||||
return err(PPYC_ERR_INVALID_NONCE_LEN,
|
||||
f"AES-256-GCM-SIV nonce must be 12 bytes, got {len(nonce)}",
|
||||
"pass a 12 byte nonce")
|
||||
return _seal(bytes(key), bytes(nonce), bytes(plaintext), bytes(aad), n_workers)
|
||||
|
||||
|
||||
def aes256_gcm_siv_decrypt(key: bytes, nonce: bytes, ct: bytes, tag: bytes,
|
||||
aad: bytes = b"",
|
||||
n_workers: int = None) -> bytes:
|
||||
"""AEAD_AES_256_GCM_SIV decryption.
|
||||
|
||||
Returns
|
||||
----
|
||||
bytes : the plaintext when authentication succeeds;
|
||||
or an error 3-tuple (**no exception raised**):
|
||||
PPYC_ERR_INVALID_KEY_LEN the key is not 32 bytes;
|
||||
PPYC_ERR_INVALID_NONCE_LEN the nonce is not 12 bytes;
|
||||
PPYC_ERR_INVALID_TAG the tag is not 16 bytes;
|
||||
PPYC_ERR_INPUT_TOO_LARGE the AAD / ciphertext exceeds 2^36 bytes;
|
||||
PPYC_ERR_AUTH_FAILED authentication failure.
|
||||
"""
|
||||
if len(key) != 32:
|
||||
return err(PPYC_ERR_INVALID_KEY_LEN,
|
||||
f"AES-256-GCM-SIV key must be 32 bytes, got {len(key)}",
|
||||
"pass a 32 byte key")
|
||||
if len(nonce) != _SIV_NONCE_LEN:
|
||||
return err(PPYC_ERR_INVALID_NONCE_LEN,
|
||||
f"AES-256-GCM-SIV nonce must be 12 bytes, got {len(nonce)}",
|
||||
"pass a 12 byte nonce")
|
||||
return _open(bytes(key), bytes(nonce), bytes(ct), bytes(tag), bytes(aad), n_workers)
|
||||
|
||||
|
||||
# ---------- Unified entry point (dispatches by key length) ----------
|
||||
|
||||
def aes_gcm_siv_encrypt(key: bytes, nonce: bytes, plaintext: bytes,
|
||||
aad: bytes = b"",
|
||||
n_workers: int = None) -> Tuple[bytes, bytes]:
|
||||
"""Unified encryption entry point: a 16-byte key uses AES-128, a 32-byte key uses AES-256.
|
||||
|
||||
Returns
|
||||
----
|
||||
(ct, tag) : ciphertext and 16-byte tag;
|
||||
or an error 3-tuple:
|
||||
PPYC_ERR_INVALID_KEY_LEN the key is not 16 / 32 bytes;
|
||||
PPYC_ERR_INVALID_NONCE_LEN the nonce is not 12 bytes;
|
||||
PPYC_ERR_INPUT_TOO_LARGE the AAD / plaintext exceeds 2^36 bytes.
|
||||
"""
|
||||
_kn_err = _check_key_nonce(key, nonce)
|
||||
if _kn_err is not None:
|
||||
return _kn_err
|
||||
return _seal(bytes(key), bytes(nonce), bytes(plaintext), bytes(aad), n_workers)
|
||||
|
||||
|
||||
def aes_gcm_siv_decrypt(key: bytes, nonce: bytes, ct: bytes, tag: bytes,
|
||||
aad: bytes = b"",
|
||||
n_workers: int = None) -> bytes:
|
||||
"""Unified decryption entry point: dispatches by key length.
|
||||
|
||||
Returns
|
||||
----
|
||||
bytes : the plaintext when authentication succeeds;
|
||||
or an error 3-tuple (**no exception raised**):
|
||||
PPYC_ERR_INVALID_KEY_LEN the key is not 16 / 32 bytes;
|
||||
PPYC_ERR_INVALID_NONCE_LEN the nonce is not 12 bytes;
|
||||
PPYC_ERR_INVALID_TAG the tag is not 16 bytes;
|
||||
PPYC_ERR_INPUT_TOO_LARGE the AAD / ciphertext exceeds 2^36 bytes;
|
||||
PPYC_ERR_AUTH_FAILED authentication failure.
|
||||
"""
|
||||
_kn_err = _check_key_nonce(key, nonce)
|
||||
if _kn_err is not None:
|
||||
return _kn_err
|
||||
return _open(bytes(key), bytes(nonce), bytes(ct), bytes(tag), bytes(aad), n_workers)
|
||||
@@ -0,0 +1,349 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""purepycrypto.chacha
|
||||
========================================
|
||||
purepycrypto - Pure-Python cryptography library (zero dependencies)
|
||||
ChaCha20 / Poly1305 / XChaCha20-Poly1305 AEAD (RFC 8439).
|
||||
"""
|
||||
|
||||
import struct
|
||||
|
||||
from .common import (
|
||||
MASK32, MASK128, POLY1305_P,
|
||||
_consttime_eq, _xor_bytes, _xor_bytes_fast, _pad16,
|
||||
)
|
||||
from ._ppyc_error import (
|
||||
PPYC_ERR, err, ok, OK_TUPLE,
|
||||
PPYC_ERR_INVALID_KEY_LEN, PPYC_ERR_INVALID_NONCE_LEN,
|
||||
PPYC_ERR_AUTH_FAILED, PPYC_ERR_INVALID_LENGTH,
|
||||
)
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 10. ChaCha20 / Poly1305 / XChaCha20-Poly1305
|
||||
# ============================================================
|
||||
|
||||
def _chacha20_block(key: bytes, counter: int, nonce: bytes) -> bytes:
|
||||
k0, k1, k2, k3, k4, k5, k6, k7 = struct.unpack("<8I", key)
|
||||
n0, n1, n2 = struct.unpack("<3I", nonce)
|
||||
M = MASK32
|
||||
x0 = 0x61707865; x1 = 0x3320646e; x2 = 0x79622d32; x3 = 0x6b206574
|
||||
x4, x5, x6, x7 = k0, k1, k2, k3
|
||||
x8, x9, x10, x11 = k4, k5, k6, k7
|
||||
x12 = counter & M; x13, x14, x15 = n0, n1, n2
|
||||
o0, o1, o2, o3 = x0, x1, x2, x3
|
||||
o4, o5, o6, o7 = x4, x5, x6, x7
|
||||
o8, o9, o10, o11 = x8, x9, x10, x11
|
||||
o12, o13, o14, o15 = x12, x13, x14, x15
|
||||
for _ in range(10):
|
||||
x0 = (x0 + x4) & M; x12 = ((x12 ^ x0) << 16 | (x12 ^ x0) >> 16) & M
|
||||
x8 = (x8 + x12) & M; x4 = ((x4 ^ x8) << 12 | (x4 ^ x8) >> 20) & M
|
||||
x0 = (x0 + x4) & M; x12 = ((x12 ^ x0) << 8 | (x12 ^ x0) >> 24) & M
|
||||
x8 = (x8 + x12) & M; x4 = ((x4 ^ x8) << 7 | (x4 ^ x8) >> 25) & M
|
||||
x1 = (x1 + x5) & M; x13 = ((x13 ^ x1) << 16 | (x13 ^ x1) >> 16) & M
|
||||
x9 = (x9 + x13) & M; x5 = ((x5 ^ x9) << 12 | (x5 ^ x9) >> 20) & M
|
||||
x1 = (x1 + x5) & M; x13 = ((x13 ^ x1) << 8 | (x13 ^ x1) >> 24) & M
|
||||
x9 = (x9 + x13) & M; x5 = ((x5 ^ x9) << 7 | (x5 ^ x9) >> 25) & M
|
||||
x2 = (x2 + x6) & M; x14 = ((x14 ^ x2) << 16 | (x14 ^ x2) >> 16) & M
|
||||
x10 = (x10 + x14) & M; x6 = ((x6 ^ x10) << 12 | (x6 ^ x10) >> 20) & M
|
||||
x2 = (x2 + x6) & M; x14 = ((x14 ^ x2) << 8 | (x14 ^ x2) >> 24) & M
|
||||
x10 = (x10 + x14) & M; x6 = ((x6 ^ x10) << 7 | (x6 ^ x10) >> 25) & M
|
||||
x3 = (x3 + x7) & M; x15 = ((x15 ^ x3) << 16 | (x15 ^ x3) >> 16) & M
|
||||
x11 = (x11 + x15) & M; x7 = ((x7 ^ x11) << 12 | (x7 ^ x11) >> 20) & M
|
||||
x3 = (x3 + x7) & M; x15 = ((x15 ^ x3) << 8 | (x15 ^ x3) >> 24) & M
|
||||
x11 = (x11 + x15) & M; x7 = ((x7 ^ x11) << 7 | (x7 ^ x11) >> 25) & M
|
||||
x0 = (x0 + x5) & M; x15 = ((x15 ^ x0) << 16 | (x15 ^ x0) >> 16) & M
|
||||
x10 = (x10 + x15) & M; x5 = ((x5 ^ x10) << 12 | (x5 ^ x10) >> 20) & M
|
||||
x0 = (x0 + x5) & M; x15 = ((x15 ^ x0) << 8 | (x15 ^ x0) >> 24) & M
|
||||
x10 = (x10 + x15) & M; x5 = ((x5 ^ x10) << 7 | (x5 ^ x10) >> 25) & M
|
||||
x1 = (x1 + x6) & M; x12 = ((x12 ^ x1) << 16 | (x12 ^ x1) >> 16) & M
|
||||
x11 = (x11 + x12) & M; x6 = ((x6 ^ x11) << 12 | (x6 ^ x11) >> 20) & M
|
||||
x1 = (x1 + x6) & M; x12 = ((x12 ^ x1) << 8 | (x12 ^ x1) >> 24) & M
|
||||
x11 = (x11 + x12) & M; x6 = ((x6 ^ x11) << 7 | (x6 ^ x11) >> 25) & M
|
||||
x2 = (x2 + x7) & M; x13 = ((x13 ^ x2) << 16 | (x13 ^ x2) >> 16) & M
|
||||
x8 = (x8 + x13) & M; x7 = ((x7 ^ x8) << 12 | (x7 ^ x8) >> 20) & M
|
||||
x2 = (x2 + x7) & M; x13 = ((x13 ^ x2) << 8 | (x13 ^ x2) >> 24) & M
|
||||
x8 = (x8 + x13) & M; x7 = ((x7 ^ x8) << 7 | (x7 ^ x8) >> 25) & M
|
||||
x3 = (x3 + x4) & M; x14 = ((x14 ^ x3) << 16 | (x14 ^ x3) >> 16) & M
|
||||
x9 = (x9 + x14) & M; x4 = ((x4 ^ x9) << 12 | (x4 ^ x9) >> 20) & M
|
||||
x3 = (x3 + x4) & M; x14 = ((x14 ^ x3) << 8 | (x14 ^ x3) >> 24) & M
|
||||
x9 = (x9 + x14) & M; x4 = ((x4 ^ x9) << 7 | (x4 ^ x9) >> 25) & M
|
||||
return struct.pack("<16I",
|
||||
(x0 + o0) & M, (x1 + o1) & M, (x2 + o2) & M, (x3 + o3) & M,
|
||||
(x4 + o4) & M, (x5 + o5) & M, (x6 + o6) & M, (x7 + o7) & M,
|
||||
(x8 + o8) & M, (x9 + o9) & M, (x10 + o10) & M, (x11 + o11) & M,
|
||||
(x12 + o12) & M, (x13 + o13) & M, (x14 + o14) & M, (x15 + o15) & M)
|
||||
|
||||
|
||||
def _chacha20_keystream(key: bytes, nonce: bytes, counter_start: int, n_bytes: int) -> bytes:
|
||||
out = bytearray()
|
||||
counter = counter_start
|
||||
remaining = n_bytes
|
||||
while remaining > 0:
|
||||
block = _chacha20_block(key, counter, nonce)
|
||||
take = min(remaining, 64)
|
||||
out += block[:take]
|
||||
counter = (counter + 1) & MASK32
|
||||
remaining -= take
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def _hchacha20(key: bytes, nonce16: bytes) -> bytes:
|
||||
k0, k1, k2, k3, k4, k5, k6, k7 = struct.unpack("<8I", key)
|
||||
n0, n1, n2, n3 = struct.unpack("<4I", nonce16)
|
||||
M = MASK32
|
||||
x0 = 0x61707865; x1 = 0x3320646e; x2 = 0x79622d32; x3 = 0x6b206574
|
||||
x4, x5, x6, x7 = k0, k1, k2, k3
|
||||
x8, x9, x10, x11 = k4, k5, k6, k7
|
||||
x12, x13, x14, x15 = n0, n1, n2, n3
|
||||
for _ in range(10):
|
||||
x0 = (x0 + x4) & M; x12 = ((x12 ^ x0) << 16 | (x12 ^ x0) >> 16) & M
|
||||
x8 = (x8 + x12) & M; x4 = ((x4 ^ x8) << 12 | (x4 ^ x8) >> 20) & M
|
||||
x0 = (x0 + x4) & M; x12 = ((x12 ^ x0) << 8 | (x12 ^ x0) >> 24) & M
|
||||
x8 = (x8 + x12) & M; x4 = ((x4 ^ x8) << 7 | (x4 ^ x8) >> 25) & M
|
||||
x1 = (x1 + x5) & M; x13 = ((x13 ^ x1) << 16 | (x13 ^ x1) >> 16) & M
|
||||
x9 = (x9 + x13) & M; x5 = ((x5 ^ x9) << 12 | (x5 ^ x9) >> 20) & M
|
||||
x1 = (x1 + x5) & M; x13 = ((x13 ^ x1) << 8 | (x13 ^ x1) >> 24) & M
|
||||
x9 = (x9 + x13) & M; x5 = ((x5 ^ x9) << 7 | (x5 ^ x9) >> 25) & M
|
||||
x2 = (x2 + x6) & M; x14 = ((x14 ^ x2) << 16 | (x14 ^ x2) >> 16) & M
|
||||
x10 = (x10 + x14) & M; x6 = ((x6 ^ x10) << 12 | (x6 ^ x10) >> 20) & M
|
||||
x2 = (x2 + x6) & M; x14 = ((x14 ^ x2) << 8 | (x14 ^ x2) >> 24) & M
|
||||
x10 = (x10 + x14) & M; x6 = ((x6 ^ x10) << 7 | (x6 ^ x10) >> 25) & M
|
||||
x3 = (x3 + x7) & M; x15 = ((x15 ^ x3) << 16 | (x15 ^ x3) >> 16) & M
|
||||
x11 = (x11 + x15) & M; x7 = ((x7 ^ x11) << 12 | (x7 ^ x11) >> 20) & M
|
||||
x3 = (x3 + x7) & M; x15 = ((x15 ^ x3) << 8 | (x15 ^ x3) >> 24) & M
|
||||
x11 = (x11 + x15) & M; x7 = ((x7 ^ x11) << 7 | (x7 ^ x11) >> 25) & M
|
||||
x0 = (x0 + x5) & M; x15 = ((x15 ^ x0) << 16 | (x15 ^ x0) >> 16) & M
|
||||
x10 = (x10 + x15) & M; x5 = ((x5 ^ x10) << 12 | (x5 ^ x10) >> 20) & M
|
||||
x0 = (x0 + x5) & M; x15 = ((x15 ^ x0) << 8 | (x15 ^ x0) >> 24) & M
|
||||
x10 = (x10 + x15) & M; x5 = ((x5 ^ x10) << 7 | (x5 ^ x10) >> 25) & M
|
||||
x1 = (x1 + x6) & M; x12 = ((x12 ^ x1) << 16 | (x12 ^ x1) >> 16) & M
|
||||
x11 = (x11 + x12) & M; x6 = ((x6 ^ x11) << 12 | (x6 ^ x11) >> 20) & M
|
||||
x1 = (x1 + x6) & M; x12 = ((x12 ^ x1) << 8 | (x12 ^ x1) >> 24) & M
|
||||
x11 = (x11 + x12) & M; x6 = ((x6 ^ x11) << 7 | (x6 ^ x11) >> 25) & M
|
||||
x2 = (x2 + x7) & M; x13 = ((x13 ^ x2) << 16 | (x13 ^ x2) >> 16) & M
|
||||
x8 = (x8 + x13) & M; x7 = ((x7 ^ x8) << 12 | (x7 ^ x8) >> 20) & M
|
||||
x2 = (x2 + x7) & M; x13 = ((x13 ^ x2) << 8 | (x13 ^ x2) >> 24) & M
|
||||
x8 = (x8 + x13) & M; x7 = ((x7 ^ x8) << 7 | (x7 ^ x8) >> 25) & M
|
||||
x3 = (x3 + x4) & M; x14 = ((x14 ^ x3) << 16 | (x14 ^ x3) >> 16) & M
|
||||
x9 = (x9 + x14) & M; x4 = ((x4 ^ x9) << 12 | (x4 ^ x9) >> 20) & M
|
||||
x3 = (x3 + x4) & M; x14 = ((x14 ^ x3) << 8 | (x14 ^ x3) >> 24) & M
|
||||
x9 = (x9 + x14) & M; x4 = ((x4 ^ x9) << 7 | (x4 ^ x9) >> 25) & M
|
||||
return struct.pack("<8I", x0, x1, x2, x3, x12, x13, x14, x15)
|
||||
|
||||
|
||||
# ---- Poly1305 ----
|
||||
|
||||
def _poly1305_clamp(r: int) -> int:
|
||||
return r & 0x0ffffffc0ffffffc0ffffffc0fffffff
|
||||
|
||||
|
||||
def poly1305_mac(key32: bytes, msg: bytes) -> bytes:
|
||||
"""Poly1305 one-time MAC (RFC 8439 section 2.5).
|
||||
|
||||
Parameters
|
||||
----
|
||||
key32 : 32-byte one-time key (r(16) || s(16));
|
||||
msg : message to authenticate (arbitrary length).
|
||||
|
||||
Returns
|
||||
----
|
||||
bytes : 16-byte tag.
|
||||
or an error 3-tuple:
|
||||
PPYC_ERR_INVALID_KEY_LEN the key is not 32 bytes.
|
||||
"""
|
||||
if len(key32) != 32:
|
||||
return err(PPYC_ERR_INVALID_KEY_LEN,
|
||||
f"Poly1305 key must be 32 bytes, got {len(key32)}",
|
||||
"pass a 32 byte one-time key (r || s)")
|
||||
r = int.from_bytes(key32[:16], "little")
|
||||
s = int.from_bytes(key32[16:32], "little")
|
||||
r = _poly1305_clamp(r)
|
||||
acc = 0
|
||||
p = POLY1305_P
|
||||
|
||||
n_full = len(msg) // 16
|
||||
for i in range(n_full):
|
||||
n = int.from_bytes(msg[i * 16:(i + 1) * 16], "little") | (1 << 128)
|
||||
acc = ((acc + n) * r) % p
|
||||
|
||||
rem = len(msg) - n_full * 16
|
||||
if rem:
|
||||
block = msg[n_full * 16:] + b"\x01" + b"\x00" * (15 - rem)
|
||||
n = int.from_bytes(block, "little")
|
||||
acc = ((acc + n) * r) % p
|
||||
|
||||
acc = (acc + s) & MASK128
|
||||
return acc.to_bytes(16, "little")
|
||||
|
||||
|
||||
# ---- XChaCha20-Poly1305 AEAD ----
|
||||
|
||||
_CC_TAG_LEN = 16
|
||||
_CC_KEY_LEN = 32
|
||||
_CC_NONCE_LEN = 24
|
||||
|
||||
|
||||
def _poly1305_aead_data(aad: bytes, ct: bytes) -> bytes:
|
||||
return _pad16(aad) + _pad16(ct) + (
|
||||
len(aad).to_bytes(8, "little") + len(ct).to_bytes(8, "little")
|
||||
)
|
||||
|
||||
|
||||
def xchacha20poly1305_encrypt(key: bytes, nonce: bytes, plaintext: bytes,
|
||||
aad: bytes = b"") -> bytes:
|
||||
"""XChaCha20-Poly1305 authenticated encryption (24-byte nonce).
|
||||
|
||||
Parameters
|
||||
----
|
||||
key : 32-byte key;
|
||||
nonce : 24-byte nonce;
|
||||
plaintext : plaintext to encrypt;
|
||||
aad : additional authenticated data (optional).
|
||||
|
||||
Returns
|
||||
----
|
||||
bytes : ciphertext + 16-byte Poly1305 tag;
|
||||
or an error 3-tuple:
|
||||
PPYC_ERR_INVALID_KEY_LEN the key is not 32 bytes;
|
||||
PPYC_ERR_INVALID_NONCE_LEN the nonce is not 24 bytes.
|
||||
"""
|
||||
if len(key) != _CC_KEY_LEN:
|
||||
return err(PPYC_ERR_INVALID_KEY_LEN,
|
||||
f"XChaCha20-Poly1305 key must be 32 bytes, got {len(key)}",
|
||||
"pass a 32 byte key")
|
||||
if len(nonce) != _CC_NONCE_LEN:
|
||||
return err(PPYC_ERR_INVALID_NONCE_LEN,
|
||||
f"XChaCha20-Poly1305 nonce must be 24 bytes, got {len(nonce)}",
|
||||
"pass a 24 byte nonce")
|
||||
subkey = _hchacha20(key, nonce[:16])
|
||||
chacha_nonce = b"\x00" * 4 + nonce[16:24]
|
||||
block0 = _chacha20_block(subkey, 0, chacha_nonce)
|
||||
poly_key = block0[:32]
|
||||
if plaintext:
|
||||
ks = _chacha20_keystream(subkey, chacha_nonce, 1, len(plaintext))
|
||||
ct = _xor_bytes_fast(plaintext, ks)
|
||||
else:
|
||||
ct = b""
|
||||
tag = poly1305_mac(poly_key, _poly1305_aead_data(aad, ct))
|
||||
return ct + tag
|
||||
|
||||
|
||||
def xchacha20poly1305_decrypt(key: bytes, nonce: bytes, ct_with_tag: bytes,
|
||||
aad: bytes = b"") -> bytes:
|
||||
"""XChaCha20-Poly1305 authenticated decryption.
|
||||
|
||||
Returns
|
||||
----
|
||||
bytes : the plaintext when authentication succeeds;
|
||||
or an error 3-tuple (**no exception raised**):
|
||||
PPYC_ERR_INVALID_KEY_LEN the key is not 32 bytes;
|
||||
PPYC_ERR_INVALID_NONCE_LEN the nonce is not 24 bytes;
|
||||
PPYC_ERR_INVALID_LENGTH the ciphertext is shorter than the 16-byte tag;
|
||||
PPYC_ERR_AUTH_FAILED authentication failure (tag mismatch).
|
||||
"""
|
||||
if len(key) != _CC_KEY_LEN:
|
||||
return err(PPYC_ERR_INVALID_KEY_LEN,
|
||||
f"XChaCha20-Poly1305 key must be 32 bytes, got {len(key)}",
|
||||
"pass a 32 byte key")
|
||||
if len(nonce) != _CC_NONCE_LEN:
|
||||
return err(PPYC_ERR_INVALID_NONCE_LEN,
|
||||
f"XChaCha20-Poly1305 nonce must be 24 bytes, got {len(nonce)}",
|
||||
"pass a 24 byte nonce")
|
||||
if len(ct_with_tag) < _CC_TAG_LEN:
|
||||
return err(PPYC_ERR_INVALID_LENGTH,
|
||||
f"ciphertext is shorter than the 16-byte tag, got {len(ct_with_tag)}",
|
||||
"pass ct||tag (at least 16 bytes long)")
|
||||
ct = ct_with_tag[:-_CC_TAG_LEN]
|
||||
tag = ct_with_tag[-_CC_TAG_LEN:]
|
||||
subkey = _hchacha20(key, nonce[:16])
|
||||
chacha_nonce = b"\x00" * 4 + nonce[16:24]
|
||||
block0 = _chacha20_block(subkey, 0, chacha_nonce)
|
||||
poly_key = block0[:32]
|
||||
expected = poly1305_mac(poly_key, _poly1305_aead_data(aad, ct))
|
||||
if not _consttime_eq(tag, expected):
|
||||
return err(PPYC_ERR_AUTH_FAILED,
|
||||
"XChaCha20-Poly1305 authentication failed: tag mismatch",
|
||||
"check that the key, nonce and AAD match, or whether the data was tampered with")
|
||||
if not ct:
|
||||
return b""
|
||||
ks = _chacha20_keystream(subkey, chacha_nonce, 1, len(ct))
|
||||
return _xor_bytes_fast(ct, ks)
|
||||
|
||||
|
||||
# ---- ChaCha20-Poly1305 AEAD (IETF, 96-bit nonce, RFC 8439) ----
|
||||
|
||||
def chacha20poly1305_encrypt(key: bytes, nonce: bytes, plaintext: bytes,
|
||||
aad: bytes = b"") -> bytes:
|
||||
"""ChaCha20-Poly1305 authenticated encryption (RFC 8439).
|
||||
|
||||
Parameters
|
||||
----
|
||||
key : 32-byte key
|
||||
nonce : 12-byte nonce
|
||||
plaintext : plaintext to encrypt
|
||||
aad : additional authenticated data (optional)
|
||||
|
||||
Returns
|
||||
----
|
||||
bytes : ciphertext + 16-byte Poly1305 tag;
|
||||
or an error 3-tuple:
|
||||
PPYC_ERR_INVALID_KEY_LEN the key is not 32 bytes;
|
||||
PPYC_ERR_INVALID_NONCE_LEN the nonce is not 12 bytes.
|
||||
"""
|
||||
if len(key) != _CC_KEY_LEN:
|
||||
return err(PPYC_ERR_INVALID_KEY_LEN,
|
||||
f"ChaCha20-Poly1305 key must be 32 bytes, got {len(key)}",
|
||||
"pass a 32 byte key")
|
||||
if len(nonce) != 12:
|
||||
return err(PPYC_ERR_INVALID_NONCE_LEN,
|
||||
f"ChaCha20-Poly1305 nonce must be 12 bytes, got {len(nonce)}",
|
||||
"pass a 12 byte nonce")
|
||||
block0 = _chacha20_block(key, 0, nonce)
|
||||
poly_key = block0[:32]
|
||||
if plaintext:
|
||||
ks = _chacha20_keystream(key, nonce, 1, len(plaintext))
|
||||
ct = _xor_bytes_fast(plaintext, ks)
|
||||
else:
|
||||
ct = b""
|
||||
tag = poly1305_mac(poly_key, _poly1305_aead_data(aad, ct))
|
||||
return ct + tag
|
||||
|
||||
|
||||
def chacha20poly1305_decrypt(key: bytes, nonce: bytes, ct_with_tag: bytes,
|
||||
aad: bytes = b"") -> bytes:
|
||||
"""ChaCha20-Poly1305 authenticated decryption (RFC 8439).
|
||||
|
||||
Returns
|
||||
----
|
||||
bytes : the plaintext when authentication succeeds;
|
||||
or an error 3-tuple (**no exception raised**):
|
||||
PPYC_ERR_INVALID_KEY_LEN the key is not 32 bytes;
|
||||
PPYC_ERR_INVALID_NONCE_LEN the nonce is not 12 bytes;
|
||||
PPYC_ERR_INVALID_LENGTH the ciphertext is shorter than the 16-byte tag;
|
||||
PPYC_ERR_AUTH_FAILED authentication failure (tag mismatch).
|
||||
"""
|
||||
if len(key) != _CC_KEY_LEN:
|
||||
return err(PPYC_ERR_INVALID_KEY_LEN,
|
||||
f"ChaCha20-Poly1305 key must be 32 bytes, got {len(key)}",
|
||||
"pass a 32 byte key")
|
||||
if len(nonce) != 12:
|
||||
return err(PPYC_ERR_INVALID_NONCE_LEN,
|
||||
f"ChaCha20-Poly1305 nonce must be 12 bytes, got {len(nonce)}",
|
||||
"pass a 12 byte nonce")
|
||||
if len(ct_with_tag) < _CC_TAG_LEN:
|
||||
return err(PPYC_ERR_INVALID_LENGTH,
|
||||
f"ciphertext is shorter than the 16-byte tag, got {len(ct_with_tag)}",
|
||||
"pass ct||tag (at least 16 bytes long)")
|
||||
ct = ct_with_tag[:-_CC_TAG_LEN]
|
||||
tag = ct_with_tag[-_CC_TAG_LEN:]
|
||||
block0 = _chacha20_block(key, 0, nonce)
|
||||
poly_key = block0[:32]
|
||||
expected = poly1305_mac(poly_key, _poly1305_aead_data(aad, ct))
|
||||
if not _consttime_eq(tag, expected):
|
||||
return err(PPYC_ERR_AUTH_FAILED,
|
||||
"ChaCha20-Poly1305 authentication failed: tag mismatch",
|
||||
"check that the key, nonce and AAD match, or whether the data was tampered with")
|
||||
if not ct:
|
||||
return b""
|
||||
ks = _chacha20_keystream(key, nonce, 1, len(ct))
|
||||
return _xor_bytes_fast(ct, ks)
|
||||
+1177
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,794 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
purepycrypto.cli_args
|
||||
=====================
|
||||
purepycrypto — Pure-Python cryptography library (zero dependencies)
|
||||
Non-interactive CLI: suitable for scripting, pipelines, and CI.
|
||||
|
||||
Usage overview
|
||||
--------
|
||||
purepycrypto <command> [options]
|
||||
|
||||
Commands
|
||||
--------
|
||||
hash Compute a hash (sha256/sha512/blake2b)
|
||||
hmac Compute an HMAC (sha256/sha512)
|
||||
kdf Key derivation (pbkdf2/hkdf/scrypt/argon2id)
|
||||
aes AES encrypt/decrypt (ecb/cbc/ctr/cfb/ofb/gcm)
|
||||
chacha (X)ChaCha20-Poly1305 encrypt/decrypt
|
||||
x25519 X25519 key generation / shared secret
|
||||
rsa RSA key generation / OAEP / PSS / PEM conversion
|
||||
rand Generate random bytes
|
||||
selftest Run the built-in self-test
|
||||
version Show the version
|
||||
|
||||
General conventions
|
||||
--------
|
||||
- Binary input: use --in <file>, or --text <string>, or --hex <hex>;
|
||||
if none is given, read from standard input (handy for pipelines).
|
||||
- Binary output: use --out <file>, or --hex to print hex to stdout.
|
||||
- Keys/IV/nonce etc.: --key/--iv/--nonce accept hex (an 0x prefix or plain hex is auto-detected).
|
||||
|
||||
Examples
|
||||
----
|
||||
# Compute sha256 (pipeline)
|
||||
echo -n abc | purepycrypto hash --algo sha256 --hex
|
||||
|
||||
# File hash
|
||||
purepycrypto hash --algo sha512 --in data.bin --hex
|
||||
|
||||
# AES-256-GCM encrypt a file
|
||||
purepycrypto aes --mode gcm --op enc --in plain.txt \
|
||||
--out cipher.bin --key-hex 00112233... --nonce-hex aabbccddeeff
|
||||
|
||||
# RSA keypair generation
|
||||
purepycrypto rsa --op keygen --bits 2048 \
|
||||
--priv-out priv.pem --pub-out pub.pem
|
||||
|
||||
# X25519 shared secret
|
||||
purepycrypto x25519 --op shared --priv-hex <hex> --peer-pub-hex <hex> --hex
|
||||
"""
|
||||
import argparse
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
# ---- Windows GBK console compatibility: make stdout/stderr use UTF-8 or replace unencodable characters ----
|
||||
def _setup_console() -> None:
|
||||
"""Avoid raising UnicodeEncodeError when printing ✓/✗ etc. on narrow-encoding consoles such as GBK."""
|
||||
for stream_name in ("stdout", "stderr"):
|
||||
stream = getattr(sys, stream_name, None)
|
||||
if stream is None:
|
||||
continue
|
||||
try:
|
||||
stream.reconfigure(encoding="utf-8", errors="replace")
|
||||
except (AttributeError, ValueError, OSError):
|
||||
# Fall back to setting errors when reconfigure is unsupported
|
||||
try:
|
||||
stream.reconfigure(errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
_setup_console()
|
||||
|
||||
from . import (
|
||||
__version__,
|
||||
sha256, sha512, blake2b,
|
||||
hmac_sha256, hmac_sha512,
|
||||
pbkdf2_hmac, hkdf, scrypt, argon2id,
|
||||
AES,
|
||||
chacha20poly1305_encrypt, chacha20poly1305_decrypt,
|
||||
xchacha20poly1305_encrypt, xchacha20poly1305_decrypt,
|
||||
x25519, x25519_base, x25519_shared, x25519_generate_keypair,
|
||||
rsa_keygen, rsa_oaep_encrypt, rsa_oaep_decrypt,
|
||||
rsa_pss_sign, rsa_pss_verify,
|
||||
private_key_to_pem, public_key_to_pem, parse_private_pem,
|
||||
private_key_to_pkcs8_der, public_key_to_spki_der,
|
||||
rand_bytes,
|
||||
)
|
||||
from .common import DecryptionError
|
||||
|
||||
# ---- v3.2.0 new modules (tolerant import) ----
|
||||
try:
|
||||
from .encoding import (
|
||||
b64encode as _b64e, b64decode as _b64d,
|
||||
b64encode_urlsafe as _b64e_u, b64decode_urlsafe as _b64d_u,
|
||||
b32encode as _b32e, b32decode as _b32d,
|
||||
hex_encode as _hexe, hex_decode as _hexd,
|
||||
b58encode as _b58e, b58decode as _b58d,
|
||||
)
|
||||
_HAS_ENC = True
|
||||
except ImportError:
|
||||
_HAS_ENC = False
|
||||
|
||||
# Single-file merge fallback: treat as available when a same-named function already exists in the global namespace
|
||||
if not _HAS_ENC:
|
||||
try:
|
||||
_b64e = b64encode # noqa: F821 (available after single-file merge)
|
||||
_HAS_ENC = True
|
||||
except NameError:
|
||||
pass
|
||||
|
||||
try:
|
||||
from .rand import (
|
||||
random_bytes as _rbytes, token_hex as _token_hex,
|
||||
token_urlsafe as _token_urlsafe, random_password as _rpassword,
|
||||
random_uuid4 as _uuid4,
|
||||
)
|
||||
_HAS_RAND = True
|
||||
except ImportError:
|
||||
_HAS_RAND = False
|
||||
|
||||
if not _HAS_RAND:
|
||||
try:
|
||||
_rbytes = random_bytes # noqa: F821
|
||||
_HAS_RAND = True
|
||||
except NameError:
|
||||
pass
|
||||
|
||||
try:
|
||||
from .kdf2 import (
|
||||
argon2id_hash as _a2id, argon2id_hash_encoded as _a2enc,
|
||||
scrypt_simple as _scrypt_simple,
|
||||
)
|
||||
_HAS_KDF2 = True
|
||||
except ImportError:
|
||||
_HAS_KDF2 = False
|
||||
|
||||
if not _HAS_KDF2:
|
||||
try:
|
||||
_a2id = argon2id_hash # noqa: F821
|
||||
_HAS_KDF2 = True
|
||||
except NameError:
|
||||
pass
|
||||
from ._ppyc_error import (
|
||||
is_err,
|
||||
PPYC_ERR, PPYC_ERR_CLI_INPUT, PPYC_ERR_CLI_USAGE,
|
||||
PPYC_ERR_FILE_NOT_FOUND, PPYC_ERR_INVALID_HEX,
|
||||
PPYC_ERR_INVALID_ALGO, PPYC_ERR_INVALID_MODE, PPYC_ERR_INVALID_OPERATION,
|
||||
PPYC_ERR_INVALID_ARG, PPYC_ERR_INVALID_LENGTH, PPYC_ERR_UNKNOWN,
|
||||
)
|
||||
|
||||
|
||||
# -------------------------------------------------------------
|
||||
# Error handling
|
||||
# -------------------------------------------------------------
|
||||
|
||||
def _cli_err(result):
|
||||
"""Convert a non-fatal error tuple ``(code, msg, suggestion)`` into a raised PPYC_ERR.
|
||||
|
||||
In the CLI scenario errors must lead to a non-zero exit code, so they are uniformly raised as PPYC_ERR,
|
||||
which is caught by ``_cli_main`` and mapped to exit code 2.
|
||||
"""
|
||||
code, msg, hint = result
|
||||
raise PPYC_ERR(code, msg, hint or "")
|
||||
|
||||
|
||||
# -------------------------------------------------------------
|
||||
# Generic I/O helpers
|
||||
# -------------------------------------------------------------
|
||||
|
||||
def _read_binary(args, attr="infile", text_attr="text", hex_attr="hex_in"):
|
||||
"""Read binary input by priority: --in file > --text > --hex > stdin."""
|
||||
path = getattr(args, attr, None)
|
||||
if path:
|
||||
with open(path, "rb") as f:
|
||||
return f.read()
|
||||
text = getattr(args, text_attr, None)
|
||||
if text is not None:
|
||||
return text.encode("utf-8")
|
||||
hx = getattr(args, hex_attr, None)
|
||||
if hx:
|
||||
return bytes.fromhex(hx.replace("0x", "").replace(" ", ""))
|
||||
if not sys.stdin.isatty():
|
||||
data = sys.stdin.buffer.read()
|
||||
if data:
|
||||
return data
|
||||
raise PPYC_ERR(PPYC_ERR_CLI_INPUT, "no input", "please specify --in / --text / --hex, or provide data via a pipe")
|
||||
|
||||
|
||||
def _parse_hex(value, name="value"):
|
||||
if value is None:
|
||||
return None
|
||||
try:
|
||||
return bytes.fromhex(value.replace("0x", "").replace(" ", ""))
|
||||
except ValueError:
|
||||
raise PPYC_ERR(PPYC_ERR_INVALID_HEX, f"{name} is not a valid hexadecimal string", "please provide hex without spaces (an optional 0x prefix is allowed)")
|
||||
|
||||
|
||||
def _write_binary(data, args, default_hex=False):
|
||||
"""Output binary: --out file, or hex/base64 to stdout.
|
||||
|
||||
If ``data`` is a non-fatal error tuple ``(code, msg, suggestion)``,
|
||||
it is converted into a raised ``PPYC_ERR`` (uniformly mapped to an exit code by ``_cli_main``).
|
||||
"""
|
||||
if is_err(data):
|
||||
_cli_err(data)
|
||||
out = getattr(args, "out", None)
|
||||
if out:
|
||||
with open(out, "wb") as f:
|
||||
f.write(data)
|
||||
print(f"[✓] written to {out} ({len(data)} bytes)")
|
||||
return
|
||||
if getattr(args, "b64", False):
|
||||
print(base64.b64encode(data).decode("ascii"))
|
||||
return
|
||||
if getattr(args, "hex", default_hex) or default_hex:
|
||||
print(data.hex())
|
||||
return
|
||||
# By default try to output as UTF-8 text
|
||||
try:
|
||||
sys.stdout.write(data.decode("utf-8"))
|
||||
if not data.endswith(b"\n"):
|
||||
sys.stdout.write("\n")
|
||||
except UnicodeDecodeError:
|
||||
print(data.hex())
|
||||
|
||||
|
||||
def _read_secret(args, attr, hex_attr=None, required=True, name="key"):
|
||||
"""Read a secret: file first, then hex."""
|
||||
path = getattr(args, attr, None)
|
||||
if path:
|
||||
with open(path, "rb") as f:
|
||||
return f.read()
|
||||
hx = getattr(args, hex_attr, None) if hex_attr else None
|
||||
if hx:
|
||||
return _parse_hex(hx, name)
|
||||
if required:
|
||||
raise PPYC_ERR(PPYC_ERR_CLI_INPUT, f"missing {name}",
|
||||
f"use --{attr.replace('_', '-')} to specify a file, or --{hex_attr} to specify hex")
|
||||
return None
|
||||
|
||||
|
||||
# -------------------------------------------------------------
|
||||
# Subcommands
|
||||
# -------------------------------------------------------------
|
||||
|
||||
def _cmd_hash(args):
|
||||
data = _read_binary(args)
|
||||
algo = args.algo
|
||||
if algo == "sha256":
|
||||
digest = sha256(data)
|
||||
elif algo == "sha512":
|
||||
digest = sha512(data)
|
||||
elif algo == "blake2b":
|
||||
digest = blake2b(data, args.digest_size)
|
||||
else:
|
||||
raise PPYC_ERR(PPYC_ERR_INVALID_ALGO, f"unknown algorithm: {algo}", "available: sha256 / sha512 / blake2b")
|
||||
_write_binary(digest, args, default_hex=True)
|
||||
|
||||
|
||||
def _cmd_hmac(args):
|
||||
data = _read_binary(args)
|
||||
key = _read_secret(args, "key_file", "key_hex", name="HMAC key")
|
||||
if args.algo == "sha256":
|
||||
mac = hmac_sha256(key, data)
|
||||
elif args.algo == "sha512":
|
||||
mac = hmac_sha512(key, data)
|
||||
else:
|
||||
raise PPYC_ERR(PPYC_ERR_INVALID_ALGO, f"unknown algorithm: {args.algo}", "available: sha256 / sha512")
|
||||
_write_binary(mac, args, default_hex=True)
|
||||
|
||||
|
||||
def _cmd_kdf(args):
|
||||
password = _read_secret(args, "password_file", "password_hex",
|
||||
name="password / input key material")
|
||||
salt = _read_secret(args, "salt_file", "salt_hex", required=False, name="salt") or b""
|
||||
|
||||
if args.algo == "pbkdf2":
|
||||
out = pbkdf2_hmac(password, salt, args.iterations, args.length, args.hash_name)
|
||||
elif args.algo == "hkdf":
|
||||
info = _parse_hex(args.info_hex) if args.info_hex else (args.info or "").encode()
|
||||
out = hkdf(password, salt, info, args.length, args.hash_name)
|
||||
elif args.algo == "scrypt":
|
||||
out = scrypt(password, salt, N=args.n, r=args.r, p=args.p, dklen=args.length)
|
||||
elif args.algo == "argon2id":
|
||||
out = argon2id(password, salt, t=args.t, m=args.m, p=args.p,
|
||||
tag_length=args.length)
|
||||
else:
|
||||
raise PPYC_ERR(PPYC_ERR_INVALID_ALGO, f"unknown KDF: {args.algo}", "available: pbkdf2 / hkdf / scrypt / argon2id")
|
||||
_write_binary(out, args, default_hex=True)
|
||||
|
||||
|
||||
def _cmd_aes(args):
|
||||
key = _read_secret(args, "key_file", "key_hex", name="AES key")
|
||||
data = _read_binary(args)
|
||||
aes = AES(key)
|
||||
mode = args.mode
|
||||
op = args.op
|
||||
|
||||
if mode == "ecb":
|
||||
out = aes.encrypt_ecb(data) if op == "enc" else aes.decrypt_ecb(data)
|
||||
elif mode == "cbc":
|
||||
iv = _read_secret(args, "iv_file", "iv_hex", name="IV")
|
||||
out = aes.encrypt_cbc(data, iv) if op == "enc" else aes.decrypt_cbc(data, iv)
|
||||
elif mode == "ctr":
|
||||
nonce = _read_secret(args, "nonce_file", "nonce_hex", name="nonce")
|
||||
out = aes.encrypt_ctr(data, nonce) if op == "enc" else aes.decrypt_ctr(data, nonce)
|
||||
elif mode == "cfb":
|
||||
iv = _read_secret(args, "iv_file", "iv_hex", name="IV")
|
||||
out = aes.encrypt_cfb(data, iv) if op == "enc" else aes.decrypt_cfb(data, iv)
|
||||
elif mode == "ofb":
|
||||
iv = _read_secret(args, "iv_file", "iv_hex", name="IV")
|
||||
out = aes.encrypt_ofb(data, iv) if op == "enc" else aes.decrypt_ofb(data, iv)
|
||||
elif mode == "gcm":
|
||||
nonce = _read_secret(args, "nonce_file", "nonce_hex", name="nonce")
|
||||
aad = _parse_hex(args.aad_hex) if args.aad_hex else (args.aad or "").encode()
|
||||
if op == "enc":
|
||||
_r = aes.gcm_encrypt(nonce, data, aad)
|
||||
if is_err(_r):
|
||||
_cli_err(_r)
|
||||
ct, tag = _r
|
||||
# Output: ct || tag (use --tag-out to store the tag separately)
|
||||
if args.tag_out:
|
||||
with open(args.tag_out, "wb") as f:
|
||||
f.write(tag)
|
||||
print(f"[✓] tag written to {args.tag_out} ({len(tag)} bytes)")
|
||||
out = ct + tag
|
||||
else:
|
||||
if len(data) < 16:
|
||||
raise PPYC_ERR(PPYC_ERR_INVALID_LENGTH, "GCM ciphertext must be at least 16 bytes (including the tag)", "please check that the input is ct||tag")
|
||||
ct, tag = data[:-16], data[-16:]
|
||||
if args.tag_file:
|
||||
with open(args.tag_file, "rb") as f:
|
||||
tag = f.read()
|
||||
ct = data
|
||||
out = aes.gcm_decrypt(nonce, ct, tag, aad)
|
||||
else:
|
||||
raise PPYC_ERR(PPYC_ERR_INVALID_MODE, f"unknown mode: {mode}", "available: ecb/cbc/ctr/cfb/ofb/gcm")
|
||||
_write_binary(out, args)
|
||||
|
||||
|
||||
def _cmd_chacha(args):
|
||||
key = _read_secret(args, "key_file", "key_hex", name="ChaCha key")
|
||||
data = _read_binary(args)
|
||||
op = args.op
|
||||
aad = _parse_hex(args.aad_hex) if args.aad_hex else (args.aad or "").encode()
|
||||
nonce = _read_secret(args, "nonce_file", "nonce_hex", name="nonce")
|
||||
|
||||
if args.xchacha:
|
||||
if op == "enc":
|
||||
out = xchacha20poly1305_encrypt(key, nonce, data, aad)
|
||||
else:
|
||||
out = xchacha20poly1305_decrypt(key, nonce, data, aad)
|
||||
else:
|
||||
if op == "enc":
|
||||
out = chacha20poly1305_encrypt(key, nonce, data, aad)
|
||||
else:
|
||||
out = chacha20poly1305_decrypt(key, nonce, data, aad)
|
||||
_write_binary(out, args)
|
||||
|
||||
|
||||
def _cmd_x25519(args):
|
||||
op = args.op
|
||||
if op == "keygen":
|
||||
_r = x25519_generate_keypair()
|
||||
if is_err(_r):
|
||||
_cli_err(_r)
|
||||
priv, pub = _r
|
||||
if args.out:
|
||||
payload = {"private": priv.hex(), "public": pub.hex()}
|
||||
with open(args.out, "w", encoding="utf-8") as f:
|
||||
json.dump(payload, f, indent=2)
|
||||
print(f"[✓] keypair written to {args.out}")
|
||||
print(f" public_key = {pub.hex()}")
|
||||
else:
|
||||
print(f"private_key = {priv.hex()}")
|
||||
print(f"public_key = {pub.hex()}")
|
||||
elif op == "base":
|
||||
priv = _read_secret(args, "priv_file", "priv_hex", name="private key")
|
||||
r = x25519_base(priv)
|
||||
if is_err(r): # non-fatal error: handle uniformly
|
||||
_cli_err(r)
|
||||
return
|
||||
print(r.hex())
|
||||
elif op == "shared":
|
||||
priv = _read_secret(args, "priv_file", "priv_hex", name="private key")
|
||||
peer = _read_secret(args, "peer_pub_file", "peer_pub_hex", name="peer public key")
|
||||
r = x25519_shared(priv, peer)
|
||||
if is_err(r):
|
||||
_cli_err(r)
|
||||
return
|
||||
shared, is_zero = r
|
||||
if args.out:
|
||||
with open(args.out, "wb") as f:
|
||||
f.write(shared)
|
||||
print(f"[✓] shared secret written to {args.out}")
|
||||
else:
|
||||
print(shared.hex())
|
||||
if is_zero:
|
||||
print("[!] warning: shared secret is all zeros (the peer public key may be a low-order point)", file=sys.stderr)
|
||||
else:
|
||||
raise PPYC_ERR(PPYC_ERR_INVALID_OPERATION, f"unknown operation: {op}", "please check the --op value")
|
||||
|
||||
|
||||
def _cmd_rsa(args):
|
||||
op = args.op
|
||||
if op == "keygen":
|
||||
_r = rsa_keygen(bits=args.bits, parallel=not args.no_parallel)
|
||||
if is_err(_r):
|
||||
_cli_err(_r)
|
||||
pub, priv = _r
|
||||
priv_pem = private_key_to_pem(priv)
|
||||
pub_pem = public_key_to_pem(pub)
|
||||
if args.priv_out:
|
||||
with open(args.priv_out, "w", encoding="ascii") as f:
|
||||
f.write(priv_pem)
|
||||
print(f"[✓] private key written to {args.priv_out}")
|
||||
else:
|
||||
print(priv_pem)
|
||||
if args.pub_out:
|
||||
with open(args.pub_out, "w", encoding="ascii") as f:
|
||||
f.write(pub_pem)
|
||||
print(f"[✓] public key written to {args.pub_out}")
|
||||
elif op == "oaep-enc":
|
||||
pub = _load_pubkey(args)
|
||||
data = _read_binary(args)
|
||||
label = _parse_hex(args.label_hex) if args.label_hex else (args.label or "").encode()
|
||||
out = rsa_oaep_encrypt(data, pub, label)
|
||||
_write_binary(out, args)
|
||||
elif op == "oaep-dec":
|
||||
_, priv = _load_keypair(args)
|
||||
data = _read_binary(args)
|
||||
label = _parse_hex(args.label_hex) if args.label_hex else (args.label or "").encode()
|
||||
out = rsa_oaep_decrypt(data, priv, label)
|
||||
_write_binary(out, args)
|
||||
elif op == "sign":
|
||||
_, priv = _load_keypair(args)
|
||||
data = _read_binary(args)
|
||||
out = rsa_pss_sign(data, priv)
|
||||
_write_binary(out, args)
|
||||
elif op == "verify":
|
||||
pub = _load_pubkey(args)
|
||||
data = _read_binary(args)
|
||||
sig = _read_secret(args, "sig_file", "sig_hex", name="signature")
|
||||
ok = rsa_pss_verify(data, sig, pub)
|
||||
print("VERIFY: " + ("OK" if ok else "FAIL"))
|
||||
sys.exit(0 if ok else 1)
|
||||
elif op == "pem-to-der":
|
||||
_, priv = _load_keypair(args)
|
||||
der = private_key_to_pkcs8_der(priv)
|
||||
_write_binary(der, args)
|
||||
else:
|
||||
raise PPYC_ERR(PPYC_ERR_INVALID_OPERATION, f"unknown operation: {op}", "please check the --op value")
|
||||
|
||||
|
||||
def _load_pubkey(args):
|
||||
from .rsa import RSAPublicKey
|
||||
if args.pub_pem:
|
||||
with open(args.pub_pem, encoding="ascii") as f:
|
||||
pem = f.read()
|
||||
return _parse_public_pem(pem)
|
||||
if args.priv_pem:
|
||||
with open(args.priv_pem, encoding="ascii") as f:
|
||||
_r = parse_private_pem(f.read())
|
||||
if is_err(_r):
|
||||
_cli_err(_r)
|
||||
priv = _r
|
||||
return RSAPublicKey(priv.n, priv.e)
|
||||
raise PPYC_ERR(PPYC_ERR_CLI_INPUT, "public or private key PEM required", "please specify with --pub-pem or --priv-pem")
|
||||
|
||||
|
||||
def _load_keypair(args):
|
||||
from .rsa import RSAPublicKey
|
||||
if not args.priv_pem:
|
||||
raise PPYC_ERR(PPYC_ERR_CLI_INPUT, "private key PEM required", "please specify the private key file with --priv-pem")
|
||||
with open(args.priv_pem, encoding="ascii") as f:
|
||||
_r = parse_private_pem(f.read())
|
||||
if is_err(_r):
|
||||
_cli_err(_r)
|
||||
priv = _r
|
||||
return RSAPublicKey(priv.n, priv.e), priv
|
||||
|
||||
|
||||
def _parse_public_pem(pem):
|
||||
"""Parse an SPKI PEM public key (reusing the DER reading helpers from der.py)."""
|
||||
from .der import _b64_pem_to_der, _der_read, _der_read_int
|
||||
from .rsa import RSAPublicKey
|
||||
der = _b64_pem_to_der(pem)
|
||||
outer, _ = _der_read(der, 0)
|
||||
pos = 0
|
||||
_, pos = _der_read(outer, pos) # AlgorithmIdentifier
|
||||
bitstr, _ = _der_read(outer, pos) # BIT STRING
|
||||
body = bitstr[1:] # drop the unused-bits byte
|
||||
inner, _ = _der_read(body, 0) # PKCS#1 RSAPublicKey
|
||||
p2 = 0
|
||||
n, p2 = _der_read_int(inner, p2)
|
||||
e, p2 = _der_read_int(inner, p2)
|
||||
return RSAPublicKey(n, e)
|
||||
|
||||
|
||||
def _cmd_rand(args):
|
||||
data = rand_bytes(args.length)
|
||||
if args.alnum:
|
||||
import secrets
|
||||
import string
|
||||
alphabet = string.ascii_letters + string.digits
|
||||
print("".join(secrets.choice(alphabet) for _ in range(args.length)))
|
||||
return
|
||||
_write_binary(data, args, default_hex=True)
|
||||
|
||||
|
||||
def _cmd_selftest(args):
|
||||
"""Run the built-in self-test (compatible with package mode and single-file merge mode)."""
|
||||
try:
|
||||
from .cli import _self_test # package mode
|
||||
except ImportError:
|
||||
# Single-file mode: the merged cli module lives in the same namespace
|
||||
_self_test = globals().get("_self_test")
|
||||
if _self_test is None:
|
||||
raise PPYC_ERR(PPYC_ERR_UNKNOWN, "_self_test not found", "the single-file build should include the cli module")
|
||||
_self_test()
|
||||
|
||||
|
||||
def _cmd_encode(args):
|
||||
"""Encoding/decoding subcommand (v3.2.0)."""
|
||||
if not _HAS_ENC:
|
||||
raise PPYC_ERR(PPYC_ERR_UNKNOWN, "encoding module unavailable", "please upgrade to v3.2.0+")
|
||||
fmt = args.format
|
||||
op = args.op
|
||||
data = _read_binary(args)
|
||||
|
||||
if op == "enc":
|
||||
if fmt == "base64":
|
||||
out = _b64e(data)
|
||||
elif fmt == "base64url":
|
||||
out = _b64e_u(data)
|
||||
elif fmt == "base32":
|
||||
out = _b32e(data)
|
||||
elif fmt == "hex":
|
||||
out = _hexe(data)
|
||||
elif fmt == "base58":
|
||||
out = _b58e(data)
|
||||
else:
|
||||
raise PPYC_ERR(PPYC_ERR_INVALID_ARG, f"unknown encoding format: {fmt}",
|
||||
"available: base64 / base64url / base32 / hex / base58")
|
||||
print(out if isinstance(out, str) else out.decode("ascii", "replace"))
|
||||
else: # dec
|
||||
raw = data.decode("ascii", "replace").strip()
|
||||
if fmt == "base64":
|
||||
r = _b64d(raw)
|
||||
elif fmt == "base64url":
|
||||
r = _b64d_u(raw)
|
||||
elif fmt == "base32":
|
||||
r = _b32d(raw)
|
||||
elif fmt == "hex":
|
||||
r = _hexd(raw)
|
||||
elif fmt == "base58":
|
||||
r = _b58d(raw)
|
||||
else:
|
||||
raise PPYC_ERR(PPYC_ERR_INVALID_ARG, f"unknown encoding format: {fmt}", "see --help")
|
||||
if is_err(r):
|
||||
_cli_err(r)
|
||||
_write_binary(r, args)
|
||||
|
||||
|
||||
def _cmd_rand2(args):
|
||||
"""Random-number subcommand (v3.2.0)."""
|
||||
if not _HAS_RAND:
|
||||
raise PPYC_ERR(PPYC_ERR_UNKNOWN, "rand module unavailable", "please upgrade to v3.2.0+")
|
||||
kind = args.kind
|
||||
if kind == "bytes":
|
||||
r = _rbytes(args.length)
|
||||
if is_err(r):
|
||||
_cli_err(r)
|
||||
_write_binary(r, args, default_hex=True)
|
||||
elif kind == "token":
|
||||
n = args.length if args.length else None
|
||||
print(_token_hex(n))
|
||||
elif kind == "urlsafe":
|
||||
n = args.length if args.length else None
|
||||
print(_token_urlsafe(n))
|
||||
elif kind == "password":
|
||||
r = _rpassword(length=args.length or 16, special=args.special)
|
||||
if is_err(r):
|
||||
_cli_err(r)
|
||||
print(r)
|
||||
elif kind == "uuid":
|
||||
print(_uuid4())
|
||||
else:
|
||||
raise PPYC_ERR(PPYC_ERR_INVALID_ARG, f"unknown type: {kind}",
|
||||
"available: bytes / token / urlsafe / password / uuid")
|
||||
|
||||
|
||||
def _cmd_version(args):
|
||||
print(f"purepycrypto {__version__}")
|
||||
print(f"Python {sys.version.split()[0]}")
|
||||
|
||||
|
||||
# -------------------------------------------------------------
|
||||
# Argument parsing
|
||||
# -------------------------------------------------------------
|
||||
|
||||
def _add_io_args(p, with_out=True, hex_in=True):
|
||||
p.add_argument("--in", dest="infile", metavar="FILE", help="binary input file")
|
||||
p.add_argument("--text", metavar="STR", help="use UTF-8 text directly as input")
|
||||
if hex_in:
|
||||
p.add_argument("--hex-in", metavar="HEX", help="use a hexadecimal string as input")
|
||||
if with_out:
|
||||
p.add_argument("--out", metavar="FILE", help="output file (defaults to stdout)")
|
||||
p.add_argument("--hex", action="store_true", help="output as hex to stdout")
|
||||
p.add_argument("--b64", action="store_true", help="output as Base64 to stdout")
|
||||
|
||||
|
||||
def _add_secret_args(p, prefix, name, required=False):
|
||||
dest_base = prefix.replace("-", "_")
|
||||
p.add_argument(f"--{prefix}", dest=f"{dest_base}_file", metavar="FILE",
|
||||
help=f"{name} (file)", required=False)
|
||||
p.add_argument(f"--{prefix}-hex", dest=f"{dest_base}_hex", metavar="HEX",
|
||||
help=f"{name} (hex)")
|
||||
# Add an explicit --xxx-file alias for scenarios such as signing (skipped when prefix already contains file)
|
||||
if dest_base not in ("sig_file",):
|
||||
pass
|
||||
|
||||
|
||||
def build_parser():
|
||||
parser = argparse.ArgumentParser(
|
||||
prog="purepycrypto",
|
||||
description="purepycrypto non-interactive CLI (any argument enters CLI mode)",
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter,
|
||||
epilog=__doc__.split("Examples")[-1] if "Examples" in __doc__ else None,
|
||||
)
|
||||
parser.add_argument("-V", "--version", action="version",
|
||||
version=f"purepycrypto {__version__}")
|
||||
sub = parser.add_subparsers(dest="command", metavar="<command>")
|
||||
|
||||
# hash
|
||||
p = sub.add_parser("hash", help="compute a hash")
|
||||
p.add_argument("--algo", default="sha256",
|
||||
choices=["sha256", "sha512", "blake2b"])
|
||||
p.add_argument("--digest-size", type=int, default=64,
|
||||
help="BLAKE2b digest length (1-64, default 64)")
|
||||
_add_io_args(p)
|
||||
p.set_defaults(func=_cmd_hash)
|
||||
|
||||
# hmac
|
||||
p = sub.add_parser("hmac", help="compute an HMAC")
|
||||
p.add_argument("--algo", default="sha256", choices=["sha256", "sha512"])
|
||||
_add_io_args(p)
|
||||
_add_secret_args(p, "key", "HMAC key")
|
||||
p.set_defaults(func=_cmd_hmac)
|
||||
|
||||
# kdf
|
||||
p = sub.add_parser("kdf", help="key derivation")
|
||||
p.add_argument("--algo", default="pbkdf2",
|
||||
choices=["pbkdf2", "hkdf", "scrypt", "argon2id"])
|
||||
p.add_argument("--length", type=int, default=32, help="output length (bytes)")
|
||||
p.add_argument("--hash-name", default="sha256", choices=["sha256", "sha512"])
|
||||
p.add_argument("--iterations", type=int, default=100000, help="PBKDF2 iteration count")
|
||||
p.add_argument("--n", type=int, default=16384, help="scrypt N (power of two)")
|
||||
p.add_argument("--r", type=int, default=8, help="scrypt r")
|
||||
p.add_argument("--p", type=int, default=1, help="parallelism p / Argon2 lanes")
|
||||
p.add_argument("--t", type=int, default=3, help="Argon2 time cost")
|
||||
p.add_argument("--m", type=int, default=65536, help="Argon2 memory cost (KiB)")
|
||||
p.add_argument("--info", help="HKDF info (text)")
|
||||
p.add_argument("--info-hex", help="HKDF info (hex)")
|
||||
_add_io_args(p, with_out=True, hex_in=False)
|
||||
_add_secret_args(p, "password", "password / input key material")
|
||||
_add_secret_args(p, "salt", "salt")
|
||||
p.set_defaults(func=_cmd_kdf)
|
||||
|
||||
# aes
|
||||
p = sub.add_parser("aes", help="AES encrypt/decrypt")
|
||||
p.add_argument("--mode", default="gcm",
|
||||
choices=["ecb", "cbc", "ctr", "cfb", "ofb", "gcm"])
|
||||
p.add_argument("--op", default="enc", choices=["enc", "dec"])
|
||||
p.add_argument("--aad", help="GCM additional authenticated data (text)")
|
||||
p.add_argument("--aad-hex", help="GCM AAD (hex)")
|
||||
p.add_argument("--tag-out", metavar="FILE", help="GCM encrypt: output the tag separately")
|
||||
p.add_argument("--tag-file", metavar="FILE", help="GCM decrypt: read the tag from a file")
|
||||
_add_io_args(p)
|
||||
_add_secret_args(p, "key", "AES key (16/24/32 bytes)")
|
||||
_add_secret_args(p, "iv", "IV (16 bytes)")
|
||||
_add_secret_args(p, "nonce", "nonce (GCM 12 bytes / CTR 8 bytes)")
|
||||
p.set_defaults(func=_cmd_aes)
|
||||
|
||||
# chacha
|
||||
p = sub.add_parser("chacha", help="ChaCha20-Poly1305 encrypt/decrypt")
|
||||
p.add_argument("--op", default="enc", choices=["enc", "dec"])
|
||||
p.add_argument("--xchacha", action="store_true",
|
||||
help="use XChaCha20-Poly1305 (24-byte nonce)")
|
||||
p.add_argument("--aad", help="additional authenticated data (text)")
|
||||
p.add_argument("--aad-hex", help="additional authenticated data (hex)")
|
||||
_add_io_args(p)
|
||||
_add_secret_args(p, "key", "key (32 bytes)")
|
||||
_add_secret_args(p, "nonce", "nonce (12 or 24 bytes)")
|
||||
p.set_defaults(func=_cmd_chacha)
|
||||
|
||||
# x25519
|
||||
p = sub.add_parser("x25519", help="X25519 key generation / shared secret")
|
||||
p.add_argument("--op", default="keygen", choices=["keygen", "base", "shared"])
|
||||
_add_io_args(p, with_out=True, hex_in=False)
|
||||
_add_secret_args(p, "priv", "private key (32 bytes)")
|
||||
_add_secret_args(p, "peer-pub", "peer public key (32 bytes)")
|
||||
p.set_defaults(func=_cmd_x25519)
|
||||
|
||||
# rsa
|
||||
p = sub.add_parser("rsa", help="RSA key generation / OAEP / PSS / PEM")
|
||||
p.add_argument("--op", default="keygen",
|
||||
choices=["keygen", "oaep-enc", "oaep-dec", "sign",
|
||||
"verify", "pem-to-der"])
|
||||
p.add_argument("--bits", type=int, default=2048, help="key size in bits (>=521, 2048 recommended)")
|
||||
p.add_argument("--no-parallel", action="store_true", help="disable multiprocess prime generation")
|
||||
p.add_argument("--priv-pem", metavar="FILE", help="private key PEM file")
|
||||
p.add_argument("--pub-pem", metavar="FILE", help="public key PEM file")
|
||||
p.add_argument("--priv-out", metavar="FILE", help="keygen: private key output path")
|
||||
p.add_argument("--pub-out", metavar="FILE", help="keygen: public key output path")
|
||||
p.add_argument("--label", help="OAEP label (text)")
|
||||
p.add_argument("--label-hex", help="OAEP label (hex)")
|
||||
_add_io_args(p)
|
||||
_add_secret_args(p, "sig", "PSS signature")
|
||||
p.add_argument("--sig-file", dest="sig_file", metavar="FILE",
|
||||
help="PSS signature file (same as --sig)")
|
||||
p.set_defaults(func=_cmd_rsa)
|
||||
|
||||
# rand
|
||||
p = sub.add_parser("rand", help="generate random bytes")
|
||||
p.add_argument("length", type=int, nargs="?", default=32)
|
||||
p.add_argument("--alnum", action="store_true", help="generate a random alphanumeric string")
|
||||
p.add_argument("--out", metavar="FILE", help="output file")
|
||||
p.add_argument("--hex", action="store_true", help="output as hex")
|
||||
p.add_argument("--b64", action="store_true", help="output as Base64")
|
||||
p.set_defaults(func=_cmd_rand)
|
||||
|
||||
# encode (v3.2.0)
|
||||
p = sub.add_parser("encode", help="encode/decode (base64/base32/hex/base58)")
|
||||
p.add_argument("--format", default="base64",
|
||||
choices=["base64", "base64url", "base32", "hex", "base58"])
|
||||
p.add_argument("--op", default="enc", choices=["enc", "dec"])
|
||||
_add_io_args(p)
|
||||
p.set_defaults(func=_cmd_encode)
|
||||
|
||||
# rand2 (v3.2.0, secure random)
|
||||
p = sub.add_parser("random", help="secure random (bytes/token/password/uuid)")
|
||||
p.add_argument("--kind", default="token",
|
||||
choices=["bytes", "token", "urlsafe", "password", "uuid"])
|
||||
p.add_argument("--length", type=int, default=32, help="length (bytes or number of characters)")
|
||||
p.add_argument("--special", action="store_true", help="password: include special characters")
|
||||
p.add_argument("--out", metavar="FILE", help="output file (bytes type)")
|
||||
p.add_argument("--hex", action="store_true", help="output as hex")
|
||||
p.set_defaults(func=_cmd_rand2)
|
||||
|
||||
# selftest / version
|
||||
p = sub.add_parser("selftest", help="run the built-in self-test")
|
||||
p.set_defaults(func=_cmd_selftest)
|
||||
|
||||
p = sub.add_parser("version", help="show the version")
|
||||
p.set_defaults(func=_cmd_version)
|
||||
|
||||
return parser
|
||||
|
||||
|
||||
def _cli_main(argv=None):
|
||||
"""Non-interactive CLI main entry point (used when merging into a single file)."""
|
||||
parser = build_parser()
|
||||
args = parser.parse_args(argv)
|
||||
if not getattr(args, "command", None):
|
||||
parser.print_help()
|
||||
return 0
|
||||
try:
|
||||
args.func(args)
|
||||
except PPYC_ERR as e:
|
||||
# Unified fatal error: print code/message/suggestion then return a non-zero exit code
|
||||
print(f"[✗] {e.code}: {e.message}", file=sys.stderr)
|
||||
if e.suggestion:
|
||||
print(f" Suggestion: {e.suggestion}", file=sys.stderr)
|
||||
return 2
|
||||
except FileNotFoundError as e:
|
||||
print(f"[✗] {PPYC_ERR_FILE_NOT_FOUND}: {e}", file=sys.stderr)
|
||||
print(" Suggestion: check that the path is correct", file=sys.stderr)
|
||||
return 3
|
||||
except (ValueError, TypeError) as e:
|
||||
print(f"[✗] {PPYC_ERR_INVALID_ARG}: {e}", file=sys.stderr)
|
||||
return 4
|
||||
return 0
|
||||
|
||||
|
||||
# Compatibility alias (called directly within the package / used by __init__)
|
||||
main = _cli_main
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(_cli_main())
|
||||
@@ -0,0 +1,210 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""purepycrypto.common
|
||||
========================================
|
||||
purepycrypto - Pure-Python cryptography library (zero dependencies)
|
||||
Basic utilities: bit-mask constants, constant-time compare/select, secure random, byte XOR, padding.
|
||||
|
||||
Error system
|
||||
--------
|
||||
This module follows the library-wide error contract (see :mod:`._ppyc_error`):
|
||||
|
||||
* **Non-fatal errors** (invalid argument / invalid padding, etc.) -> return a 3-tuple
|
||||
``(error_code, error_message, suggestion)``;
|
||||
On success the business value itself is returned; pure validation functions return :data:`OK_TUPLE`.
|
||||
* **Fatal errors** (broken internal invariant) -> raise :class:`PPYC_ERR`.
|
||||
|
||||
Backward compatibility
|
||||
--------
|
||||
``CryptoError`` / ``DecryptionError`` are no longer defined in this module, but re-exported from
|
||||
:mod:`._ppyc_error` (they are both aliases of :class:`PPYC_ERR`),
|
||||
to keep legacy forms such as ``from purepycrypto.common import CryptoError`` working.
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
from ._ppyc_error import (
|
||||
PPYC_ERR,
|
||||
err,
|
||||
CryptoError,
|
||||
DecryptionError,
|
||||
PPYC_ERR_INVALID_ARG,
|
||||
PPYC_ERR_INVALID_TYPE,
|
||||
PPYC_ERR_INVALID_PADDING,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"MASK32", "MASK64", "MASK128", "POLY1305_P", "GHASH_R", "R_CONST",
|
||||
"CryptoError", "DecryptionError",
|
||||
"_consttime_eq", "_consttime_int_eq", "_consttime_select",
|
||||
"rand_int", "rand_bytes",
|
||||
"_xor_bytes", "_xor_bytes_fast",
|
||||
"_pad16", "_pad_pkcs7", "_unpad_pkcs7",
|
||||
]
|
||||
|
||||
|
||||
MASK32 = 0xFFFFFFFF
|
||||
MASK64 = 0xFFFFFFFFFFFFFFFF
|
||||
MASK128 = (1 << 128) - 1
|
||||
POLY1305_P = (1 << 130) - 5
|
||||
GHASH_R = 0xE1000000000000000000000000000000
|
||||
R_CONST = GHASH_R
|
||||
|
||||
|
||||
def _consttime_eq(a: bytes, b: bytes) -> bool:
|
||||
"""Compare two byte strings for equality in constant time.
|
||||
|
||||
Different lengths also take the constant-time path (per-byte masked XOR) to avoid leaking length via timing.
|
||||
|
||||
Returns
|
||||
----
|
||||
bool
|
||||
True if the contents are identical, otherwise False.
|
||||
This is an internal hot path that cannot fail, so no error tuple is returned.
|
||||
"""
|
||||
if len(a) != len(b):
|
||||
la, lb = len(a), len(b)
|
||||
diff = la ^ lb
|
||||
for i in range(max(la, lb)):
|
||||
x = a[i] if i < la else 0
|
||||
y = b[i] if i < lb else 0
|
||||
diff |= x ^ y
|
||||
return diff == 0
|
||||
r = 0
|
||||
for x, y in zip(a, b):
|
||||
r |= x ^ y
|
||||
return r == 0
|
||||
|
||||
|
||||
def _consttime_int_eq(a: int, b: int, bits: int) -> bool:
|
||||
"""Compare two integers of at most "bits" bits for equality in constant time.
|
||||
|
||||
Returns
|
||||
----
|
||||
bool
|
||||
True if equal, otherwise False. Internal hot path, no error tuple returned.
|
||||
"""
|
||||
diff = a ^ b
|
||||
result = 0
|
||||
for i in range(0, bits, 64):
|
||||
result |= (diff >> i) & MASK64
|
||||
return result == 0
|
||||
|
||||
|
||||
def _consttime_select(cond: int, a: int, b: int, bits: int) -> int:
|
||||
"""Constant-time select: return a when cond is non-zero, otherwise b.
|
||||
|
||||
Returns
|
||||
----
|
||||
int
|
||||
The selected bits-bit integer. Internal hot path, no error tuple returned.
|
||||
"""
|
||||
mask = (-cond) & ((1 << bits) - 1)
|
||||
return (a & mask) | (b & ~mask & ((1 << bits) - 1))
|
||||
|
||||
|
||||
def rand_int(a: int, b: int):
|
||||
"""Return a uniformly random integer in the closed interval [a, b] (no modulo bias).
|
||||
|
||||
Returns
|
||||
----
|
||||
int
|
||||
A random integer in [a, b].
|
||||
tuple
|
||||
When a > b (invalid interval), returns (PPYC_ERR_INVALID_ARG, reason, suggestion).
|
||||
"""
|
||||
if a > b:
|
||||
return err(PPYC_ERR_INVALID_ARG,
|
||||
f"invalid random range: lower bound a={a} is greater than upper bound b={b}",
|
||||
"make sure rand_int(a, b) is called with a <= b")
|
||||
size = b - a + 1
|
||||
nb = (size.bit_length() + 7) // 8
|
||||
while True:
|
||||
raw = int.from_bytes(os.urandom(nb), "big")
|
||||
if raw < size:
|
||||
return a + raw
|
||||
|
||||
|
||||
def rand_bytes(n: int):
|
||||
"""Return n cryptographically secure random bytes.
|
||||
|
||||
Returns
|
||||
----
|
||||
bytes
|
||||
n random bytes.
|
||||
tuple
|
||||
n not an integer -> (PPYC_ERR_INVALID_TYPE, ...);
|
||||
n < 0 -> (PPYC_ERR_INVALID_ARG, ...).
|
||||
"""
|
||||
if isinstance(n, bool) or not isinstance(n, int):
|
||||
return err(PPYC_ERR_INVALID_TYPE,
|
||||
f"random byte count must be an integer, got {type(n).__name__}",
|
||||
"pass a non-negative integer n")
|
||||
if n < 0:
|
||||
return err(PPYC_ERR_INVALID_ARG,
|
||||
f"random byte count cannot be negative: n={n}",
|
||||
"pass a non-negative integer n")
|
||||
return os.urandom(n)
|
||||
|
||||
|
||||
def _xor_bytes(a: bytes, b: bytes) -> bytes:
|
||||
"""Byte-wise XOR (uses the shorter of the two lengths). Internal hot path, no error return."""
|
||||
return bytes(x ^ y for x, y in zip(a, b))
|
||||
|
||||
|
||||
def _xor_bytes_fast(a: bytes, b: bytes) -> bytes:
|
||||
"""Big-integer XOR (requires len(a) == len(b)). Internal hot path, no error return."""
|
||||
return (int.from_bytes(a, "little") ^ int.from_bytes(b, "little")).to_bytes(len(a), "little")
|
||||
|
||||
|
||||
def _pad16(data: bytes) -> bytes:
|
||||
"""Zero-pad to a 16-byte boundary (returned unchanged if already aligned). Internal hot path, no error return."""
|
||||
if len(data) % 16 == 0:
|
||||
return data
|
||||
return data + b"\x00" * (16 - len(data) % 16)
|
||||
|
||||
|
||||
def _pad_pkcs7(data: bytes, bs: int = 16):
|
||||
"""Apply PKCS#7 padding (always appends 1..bs padding bytes).
|
||||
|
||||
Returns
|
||||
----
|
||||
bytes
|
||||
The padded data.
|
||||
tuple
|
||||
When bs is invalid (not an integer, or outside 1..255) returns
|
||||
(PPYC_ERR_INVALID_ARG, reason, suggestion).
|
||||
"""
|
||||
if isinstance(bs, bool) or not isinstance(bs, int) or bs < 1 or bs > 255:
|
||||
return err(PPYC_ERR_INVALID_ARG,
|
||||
f"invalid PKCS#7 block size: bs={bs!r}",
|
||||
"block size must be an integer in 1..255 (AES typically uses 16)")
|
||||
p = bs - (len(data) % bs)
|
||||
return data + bytes([p]) * p
|
||||
|
||||
|
||||
def _unpad_pkcs7(data: bytes):
|
||||
"""Remove PKCS#7 padding (block size fixed at 16).
|
||||
|
||||
Returns
|
||||
----
|
||||
bytes
|
||||
The original data with padding removed.
|
||||
tuple
|
||||
On invalid padding returns (PPYC_ERR_INVALID_PADDING, reason, suggestion).
|
||||
Triggered when: the data is empty / the last byte is not in 1..16 / the last byte is greater than the data length /
|
||||
the padding bytes are inconsistent.
|
||||
"""
|
||||
if not data:
|
||||
return err(PPYC_ERR_INVALID_PADDING,
|
||||
"data is empty, cannot remove PKCS#7 padding",
|
||||
"make sure the ciphertext is at least one block (16 bytes) long")
|
||||
p = data[-1]
|
||||
if p < 1 or p > 16 or p > len(data):
|
||||
return err(PPYC_ERR_INVALID_PADDING,
|
||||
f"invalid PKCS#7 padding byte: {p}",
|
||||
"check that the key / IV / mode are correct, or whether the data was tampered with")
|
||||
if data[-p:] != bytes([p]) * p:
|
||||
return err(PPYC_ERR_INVALID_PADDING,
|
||||
"PKCS#7 padding bytes are inconsistent",
|
||||
"check that the key / IV / mode are correct, or whether the data was tampered with")
|
||||
return data[:-p]
|
||||
@@ -0,0 +1,150 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""purepycrypto.der
|
||||
========================================
|
||||
purepycrypto - Pure-Python cryptography library (zero dependencies)
|
||||
ASN.1 DER encoding/decoding and PEM wrapping/parsing (RSA PKCS#1 / PKCS#8 / SPKI).
|
||||
"""
|
||||
|
||||
import base64
|
||||
|
||||
from .rsa import RSAPrivateKey, RSAPublicKey
|
||||
from ._ppyc_error import (
|
||||
PPYC_ERR, err, PPYC_ERR_INVALID_ENCODING, PPYC_ERR_PARSE_FAILED,
|
||||
)
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 13. ASN.1 DER / PEM
|
||||
# ============================================================
|
||||
|
||||
OID_RSA = "1.2.840.113549.1.1.1"
|
||||
|
||||
|
||||
def _der_len(n: int) -> bytes:
|
||||
if n < 0x80:
|
||||
return bytes([n])
|
||||
raw = n.to_bytes((n.bit_length() + 7) // 8, "big")
|
||||
return bytes([0x80 | len(raw)]) + raw
|
||||
|
||||
|
||||
def _der_int(n: int) -> bytes:
|
||||
if n == 0:
|
||||
return b"\x02\x01\x00"
|
||||
raw = n.to_bytes((n.bit_length() + 7) // 8, "big")
|
||||
if raw[0] & 0x80:
|
||||
raw = b"\x00" + raw
|
||||
return b"\x02" + _der_len(len(raw)) + raw
|
||||
|
||||
|
||||
def _der_seq(*items: bytes) -> bytes:
|
||||
body = b"".join(items)
|
||||
return b"\x30" + _der_len(len(body)) + body
|
||||
|
||||
|
||||
def _der_octet(data: bytes) -> bytes:
|
||||
return b"\x04" + _der_len(len(data)) + data
|
||||
|
||||
|
||||
def _der_bit(data: bytes) -> bytes:
|
||||
return b"\x03" + _der_len(len(data) + 1) + b"\x00" + data
|
||||
|
||||
|
||||
def _der_null() -> bytes:
|
||||
return b"\x05\x00"
|
||||
|
||||
|
||||
def _der_oid(oid: str) -> bytes:
|
||||
parts = [int(x) for x in oid.split(".")]
|
||||
encoded = [40 * parts[0] + parts[1]]
|
||||
for p in parts[2:]:
|
||||
stack = [p & 0x7F]
|
||||
p >>= 7
|
||||
while p:
|
||||
stack.append((p & 0x7F) | 0x80)
|
||||
p >>= 7
|
||||
encoded.extend(reversed(stack))
|
||||
return b"\x06" + _der_len(len(encoded)) + bytes(encoded)
|
||||
|
||||
|
||||
def private_key_to_pkcs1_der(priv: RSAPrivateKey) -> bytes:
|
||||
return _der_seq(_der_int(0), _der_int(priv.n), _der_int(priv.e), _der_int(priv.d),
|
||||
_der_int(priv.p), _der_int(priv.q), _der_int(priv.dp),
|
||||
_der_int(priv.dq), _der_int(priv.q_inv))
|
||||
|
||||
|
||||
def public_key_to_pkcs1_der(pub: RSAPublicKey) -> bytes:
|
||||
return _der_seq(_der_int(pub.n), _der_int(pub.e))
|
||||
|
||||
|
||||
def private_key_to_pkcs8_der(priv: RSAPrivateKey) -> bytes:
|
||||
alg = _der_seq(_der_oid(OID_RSA), _der_null())
|
||||
return _der_seq(_der_int(0), alg, _der_octet(private_key_to_pkcs1_der(priv)))
|
||||
|
||||
|
||||
def public_key_to_spki_der(pub: RSAPublicKey) -> bytes:
|
||||
alg = _der_seq(_der_oid(OID_RSA), _der_null())
|
||||
return _der_seq(alg, _der_bit(public_key_to_pkcs1_der(pub)))
|
||||
|
||||
|
||||
def _pem(der: bytes, label: str) -> str:
|
||||
b64 = base64.b64encode(der).decode("ascii")
|
||||
lines = [b64[i:i + 64] for i in range(0, len(b64), 64)]
|
||||
return f"-----BEGIN {label}-----\n" + "\n".join(lines) + f"\n-----END {label}-----\n"
|
||||
|
||||
|
||||
def private_key_to_pem(priv: RSAPrivateKey) -> str:
|
||||
return _pem(private_key_to_pkcs8_der(priv), "PRIVATE KEY")
|
||||
|
||||
|
||||
def public_key_to_pem(pub: RSAPublicKey) -> str:
|
||||
return _pem(public_key_to_spki_der(pub), "PUBLIC KEY")
|
||||
|
||||
|
||||
def _b64_pem_to_der(pem: str) -> bytes:
|
||||
lines = [ln.strip() for ln in pem.strip().splitlines()]
|
||||
b64_lines = [ln for ln in lines if not ln.startswith("-----")]
|
||||
return base64.b64decode("".join(b64_lines))
|
||||
|
||||
|
||||
def _der_read(data: bytes, pos: int):
|
||||
tag = data[pos]; pos += 1
|
||||
length_byte = data[pos]; pos += 1
|
||||
if length_byte < 0x80:
|
||||
length = length_byte
|
||||
else:
|
||||
nb = length_byte & 0x7F
|
||||
length = int.from_bytes(data[pos:pos + nb], "big")
|
||||
pos += nb
|
||||
return data[pos:pos + length], pos + length
|
||||
|
||||
|
||||
def _der_read_int(data: bytes, pos: int):
|
||||
tag = data[pos]
|
||||
if tag != 0x02:
|
||||
raise PPYC_ERR(PPYC_ERR_INVALID_ENCODING,
|
||||
f"expected ASN.1 INTEGER (0x02), got 0x{tag:02x}",
|
||||
"make sure the input is valid DER encoding")
|
||||
content, pos = _der_read(data, pos)
|
||||
val = int.from_bytes(content, "big", signed=True)
|
||||
if val < 0:
|
||||
raise PPYC_ERR(PPYC_ERR_INVALID_ENCODING, "ASN.1 INTEGER is negative",
|
||||
"RSA key material must not be negative, please check the input")
|
||||
return val, pos
|
||||
|
||||
|
||||
def parse_private_pem(pem: str) -> RSAPrivateKey:
|
||||
der = _b64_pem_to_der(pem)
|
||||
outer, _ = _der_read(der, 0)
|
||||
pos = 0
|
||||
_, pos = _der_read_int(outer, pos)
|
||||
_, pos = _der_read(outer, pos)
|
||||
octet, pos = _der_read(outer, pos)
|
||||
pkcs1, _ = _der_read(octet, 0)
|
||||
pos2 = 0
|
||||
_, pos2 = _der_read_int(pkcs1, pos2)
|
||||
n, pos2 = _der_read_int(pkcs1, pos2)
|
||||
e, pos2 = _der_read_int(pkcs1, pos2)
|
||||
d, pos2 = _der_read_int(pkcs1, pos2)
|
||||
p, pos2 = _der_read_int(pkcs1, pos2)
|
||||
q, pos2 = _der_read_int(pkcs1, pos2)
|
||||
return RSAPrivateKey(n, e, d, p, q, verify=True)
|
||||
@@ -0,0 +1,634 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""purepycrypto.ed25519
|
||||
========================================
|
||||
purepycrypto - Pure-Python cryptography library (zero dependencies)
|
||||
Ed25519 digital signatures (RFC 8032, the pure Ed25519 variant, not Ed25519ph).
|
||||
|
||||
Implementation highlights
|
||||
--------
|
||||
* Curve edwards25519: -x^2 + y^2 = 1 + d*x^2*y^2, p = 2^255 - 19,
|
||||
L = 2^252 + 27742317777372353535851937790883648493.
|
||||
* Point representation: extended homogeneous coordinates (X : Y : Z : T), with x = X/Z and y = Y/Z.
|
||||
General addition uses add-2008-hwcd-3 (a = -1) as a unified formula; doubling uses dbl-2008-hwcd;
|
||||
for **affine** table entries (Z = 1) the 7-multiplication mixed addition _pt_add_mixed is used (2 multiplications fewer than general addition).
|
||||
* Fixed-base scalar multiplication e*B: an **affine Comb table** rows[i][d] = (d*2^(w*i))*B; the whole table is made
|
||||
affine with a single Montgomery batch inversion; it is built lazily once at module level and cached, and each row needs only 1 point addition and 0 doublings.
|
||||
- Secret scalars (a and r in signing) go through a **constant-time masked scan** (_ct_select_packed: a fixed 2^w rounds of
|
||||
r |= e & m, with no secret-dependent branch / early exit / early return).
|
||||
- Public scalars (S in verification) use plain indexing (not constant time, but only public data is involved).
|
||||
* Variable-base scalar multiplication k*A: **wNAF-5** (density about 1/6, roughly 80% fewer point additions than a fixed window); public scalars only.
|
||||
* Verification: tests whether S*B - k*A - R is the identity element (equivalent to
|
||||
encode(S*B) == encode(R + k*A) in RFC 8032 section 5.1.7), saving 2 point encodings / modular inversions.
|
||||
* Encoding / decoding: RFC 8032 section 5.1.2; decoding performs square-root recovery (p = 5 mod 8) with strict rejection of invalid encodings.
|
||||
* Hashing: SHA-512 (purepycrypto.hash.sha512, zero third-party dependencies).
|
||||
|
||||
Tunable keyword arguments (defaults are already optimal; positional arguments are fully compatible with the original version)
|
||||
--------------------------------------------------------
|
||||
window Comb table window bit width, default 4. 4 is optimal for constant-time base multiplication (masked scan rounds = 2^w);
|
||||
increasing it reduces point additions on the public path, but the table lookup rounds on the constant-time path grow accordingly.
|
||||
precompute True (default) uses the precomputed Comb table; False falls back to generic double-and-add scalar multiplication
|
||||
(smaller memory footprint, slower).
|
||||
multiprocess whether to build the Comb table in parallel with multiprocessing; default False (affects only the one-off table build;
|
||||
the Windows spawn overhead usually outweighs the benefit, hence disabled by default).
|
||||
|
||||
Security notes
|
||||
--------
|
||||
Pure-Python big-integer arithmetic cannot provide true constant time. This implementation is written to "eliminate
|
||||
secret-dependent branches and control flow" -- secret scalars go only through the constant-time masked scan, introducing no secret-dependent branch / early exit; suitable for teaching,
|
||||
protocol prototyping and compatibility scenarios. For side-channel-sensitive key operations use native implementations such as libsodium / OpenSSL.
|
||||
|
||||
Unified error system
|
||||
------------
|
||||
This module follows the unified purepycrypto error contract (see ``purepycrypto._ppyc_error``):
|
||||
* **Non-fatal errors** (invalid seed length, window out of range, etc.) -> return a 3-tuple
|
||||
``(error_code, error_message, suggestion)``;
|
||||
* **Fatal errors** (internal point decoding / broken invariant) -> raise ``PPYC_ERR``;
|
||||
* ``ed25519_verify`` preserves boolean semantics and **returns False** for every invalid input (length / public key /
|
||||
signature / point encoding), with the internal ``PPYC_ERR`` caught in place.
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
from typing import Dict, List, Optional, Tuple
|
||||
|
||||
try: # Standard usage: relative import within the package
|
||||
from .hash import sha512
|
||||
from .common import _consttime_eq
|
||||
from ._ppyc_error import (
|
||||
PPYC_ERR,
|
||||
Ed25519Error,
|
||||
err, is_err, OK_TUPLE,
|
||||
PPYC_ERR_INVALID_LENGTH,
|
||||
PPYC_ERR_INVALID_POINT,
|
||||
PPYC_ERR_INVALID_ARG,
|
||||
)
|
||||
except ImportError: # fallback: allows loading this file directly as a script (no package context)
|
||||
_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
if _root not in sys.path:
|
||||
sys.path.insert(0, _root)
|
||||
from purepycrypto.hash import sha512
|
||||
from purepycrypto.common import _consttime_eq
|
||||
from purepycrypto._ppyc_error import (
|
||||
PPYC_ERR,
|
||||
Ed25519Error,
|
||||
err, is_err, OK_TUPLE,
|
||||
PPYC_ERR_INVALID_LENGTH,
|
||||
PPYC_ERR_INVALID_POINT,
|
||||
PPYC_ERR_INVALID_ARG,
|
||||
)
|
||||
|
||||
|
||||
P = 2 ** 255 - 19
|
||||
L = 2 ** 252 + 27742317777372353535851937790883648493
|
||||
_COFACTOR = 8
|
||||
|
||||
D = (-121665 * pow(121666, P - 2, P)) % P # d = -121665/121666 mod p
|
||||
D2 = (2 * D) % P
|
||||
SQRT_M1 = pow(2, (P - 1) // 4, P) # sqrt(-1) mod p
|
||||
|
||||
BX = 15112221349535400772501151409588531511454012693041857206046113283949847762202
|
||||
BY = 46316835694926478169428394003475163141307993866256225615783033603165251855960
|
||||
Point = Tuple[int, int, int, int]
|
||||
_BASE: Point = (BX, BY, 1, (BX * BY) % P)
|
||||
IDENTITY: Point = (0, 1, 1, 0) # identity element (Z = 1, usable as an affine table entry)
|
||||
|
||||
|
||||
# Ed25519Error is defined uniformly in purepycrypto._ppyc_error (a PPYC_ERR subclass) and reused here directly.
|
||||
|
||||
|
||||
def _pt_add(p1: Point, p2: Point) -> Point:
|
||||
"""Unified addition (add-2008-hwcd-3 with a = -1, no exceptional branch, handles any point pair)."""
|
||||
x1, y1, z1, t1 = p1
|
||||
x2, y2, z2, t2 = p2
|
||||
a = (y1 - x1) * (y2 - x2) % P
|
||||
b = (y1 + x1) * (y2 + x2) % P
|
||||
c = t1 * D2 % P * t2 % P
|
||||
dd = z1 * 2 * z2 % P
|
||||
e = b - a
|
||||
f = dd - c
|
||||
g = dd + c
|
||||
h = b + a
|
||||
return (e * f % P, g * h % P, f * g % P, e * h % P)
|
||||
|
||||
|
||||
def _pt_add_mixed(p1: Point, x2: int, y2: int, t2d: int) -> Point:
|
||||
"""Mixed addition: extended-coordinate point p1 plus an **affine** point (x2, y2) (Z2 = 1, t2d = x2*y2*D2 mod p).
|
||||
|
||||
9 multiplications are reduced to 7 (the affine specialization of add-2008-hwcd-3); it also holds when p1 is the identity element.
|
||||
"""
|
||||
x1, y1, z1, t1 = p1
|
||||
a = (y1 - x1) * (y2 - x2) % P
|
||||
b = (y1 + x1) * (y2 + x2) % P
|
||||
c = t1 * t2d % P
|
||||
dd = z1 + z1
|
||||
e = b - a
|
||||
f = dd - c
|
||||
g = dd + c
|
||||
h = b + a
|
||||
return (e * f % P, g * h % P, f * g % P, e * h % P)
|
||||
|
||||
|
||||
def _pt_dbl(p1: Point) -> Point:
|
||||
"""Point doubling (dbl-2008-hwcd from RFC 8032 section 5.1.4, a = -1)."""
|
||||
x1, y1, z1, _t1 = p1
|
||||
a = x1 * x1 % P
|
||||
b = y1 * y1 % P
|
||||
c = 2 * z1 * z1 % P
|
||||
dd = (-a) % P
|
||||
e = ((x1 + y1) * (x1 + y1) - a - b) % P
|
||||
g = (dd + b) % P
|
||||
f = (g - c) % P
|
||||
h = (dd - b) % P
|
||||
return (e * f % P, g * h % P, f * g % P, e * h % P)
|
||||
|
||||
|
||||
def _pt_neg(p1: Point) -> Point:
|
||||
"""Negation of a point: -(X:Y:Z:T) = (-X:Y:Z:-T)."""
|
||||
x, y, z, t = p1
|
||||
return ((-x) % P, y, z, (-t) % P)
|
||||
|
||||
|
||||
def _ct_eq_mask(a: int, b: int) -> int:
|
||||
"""Returns an all-ones mask (-1) when a == b, otherwise 0; no secret-dependent branch."""
|
||||
return ((a ^ b) - 1) >> 63
|
||||
|
||||
|
||||
def _ct_select_point(table: List[Point], idx: int) -> Point:
|
||||
"""Constant-time extraction of table[idx] (masked linear scan, no early exit)."""
|
||||
rx = ry = rz = rt = 0
|
||||
for j, (px, py, pz, pt) in enumerate(table):
|
||||
m = ((j ^ idx) - 1) >> 63
|
||||
nm = ~m
|
||||
rx = (rx & nm) | (px & m)
|
||||
ry = (ry & nm) | (py & m)
|
||||
rz = (rz & nm) | (pz & m)
|
||||
rt = (rt & nm) | (pt & m)
|
||||
return (rx, ry, rz, rt)
|
||||
|
||||
|
||||
# ------------------------------------------------------------
|
||||
# 12.3 Fixed-base Comb table (affine + constant-time masked lookup)
|
||||
# ------------------------------------------------------------
|
||||
# Each of the 2^w candidate points per row is packed into a single big integer (3 slots of 256 bits: x | y<<256 | t2d<<512),
|
||||
# where (x, y) are **affine** coordinates (Z = 1) and t2d = x*y*D2 mod p. The whole table is generated only from the public
|
||||
# base point B, so it is a public constant; making it affine reduces each row point addition to the 7-multiplication mixed addition _pt_add_mixed.
|
||||
#
|
||||
# Secret scalar lookups use a fixed 2^w round masked scan (_ct_select_packed), with no secret-dependent branch /
|
||||
# early exit; public scalars use plain indexing (_scalarmult_base_pub), which is faster and involves no secrets.
|
||||
|
||||
_W_CT = 4 # constant-time path window (2^w masked scan rounds; 4 is optimal)
|
||||
_SLOT_MASK = (1 << 256) - 1 # single coordinate slot mask
|
||||
_COMB_CACHE = {} # window -> List[Tuple[packed, ...]]
|
||||
_COMB_BUILD_LOCK = threading.Lock()
|
||||
|
||||
|
||||
def _wc(w: int) -> int:
|
||||
"""ceil(256 / w) -- the number of rows needed to cover a 256-bit scalar."""
|
||||
return (256 + w - 1) // w
|
||||
|
||||
|
||||
def _build_comb_block(args):
|
||||
"""Build one row: the projective point list of [(d*2^(w*i))*B | d = 0..2^w-1]."""
|
||||
w, i = args
|
||||
base = _BASE
|
||||
for _ in range(w * i):
|
||||
base = _pt_dbl(base)
|
||||
mult = [IDENTITY, base]
|
||||
for d in range(2, 1 << w):
|
||||
mult.append(_pt_add(mult[d - 1], base) if (d & 1) else _pt_dbl(mult[d >> 1]))
|
||||
return mult
|
||||
|
||||
|
||||
def _affinize(flat):
|
||||
"""Make the whole table affine with a single Montgomery batch inversion, packed as x | y<<256 | t2d<<512."""
|
||||
n = len(flat)
|
||||
pre = [0] * n
|
||||
acc = 1
|
||||
for k in range(n):
|
||||
pre[k] = acc
|
||||
acc = acc * flat[k][2] % P
|
||||
inv = pow(acc, P - 2, P)
|
||||
out = [0] * n
|
||||
for k in range(n - 1, -1, -1):
|
||||
z = flat[k][2]
|
||||
zi = inv * pre[k] % P
|
||||
inv = inv * z % P
|
||||
x = flat[k][0] * zi % P
|
||||
y = flat[k][1] * zi % P
|
||||
out[k] = x | (y << 256) | (x * y % P * D2 % P << 512)
|
||||
return out
|
||||
|
||||
|
||||
def _build_comb(w: int, multiprocess: bool = False):
|
||||
"""Build the affine Comb table for window w; with multiprocess=True the rows are built in parallel."""
|
||||
n = _wc(w)
|
||||
rows = None
|
||||
if multiprocess and n > 1:
|
||||
try:
|
||||
from concurrent.futures import ProcessPoolExecutor
|
||||
workers = min(n, os.cpu_count() or 2)
|
||||
with ProcessPoolExecutor(max_workers=workers) as ex:
|
||||
rows = list(ex.map(_build_comb_block, [(w, i) for i in range(n)]))
|
||||
except Exception:
|
||||
rows = None # any exception falls back to serial construction
|
||||
if rows is None:
|
||||
rows = [_build_comb_block((w, i)) for i in range(n)]
|
||||
packed = _affinize([p for r in rows for p in r])
|
||||
step = 1 << w
|
||||
return [tuple(packed[i * step:(i + 1) * step]) for i in range(n)]
|
||||
|
||||
|
||||
def _comb_table(window, multiprocess: bool = False):
|
||||
"""Return (and cache) the affine Comb table for window `window`; built once on the first call."""
|
||||
w = _W_CT if window is None else int(window)
|
||||
if w < 1 or w > 8:
|
||||
raise PPYC_ERR(PPYC_ERR_INVALID_ARG,
|
||||
f"window must be between 1 and 8, got {w}",
|
||||
"pass a window width in 1..8 (default 4)")
|
||||
tab = _COMB_CACHE.get(w)
|
||||
if tab is None:
|
||||
with _COMB_BUILD_LOCK:
|
||||
tab = _COMB_CACHE.get(w)
|
||||
if tab is None:
|
||||
tab = _build_comb(w, multiprocess)
|
||||
_COMB_CACHE[w] = tab
|
||||
return tab
|
||||
|
||||
|
||||
def ed25519_precompute(window=None, multiprocess: bool = False):
|
||||
"""Explicitly (pre)build and cache the Comb table so the first later call has no build latency.
|
||||
|
||||
Returns
|
||||
----
|
||||
(None, None, None)
|
||||
Success (``OK_TUPLE``).
|
||||
(str, str, str)
|
||||
A non-fatal error tuple; ``PPYC_ERR_INVALID_ARG`` (window out of range).
|
||||
"""
|
||||
w = _W_CT if window is None else int(window)
|
||||
if w < 1 or w > 8:
|
||||
return err(PPYC_ERR_INVALID_ARG,
|
||||
f"window must be between 1 and 8, got {w}",
|
||||
"pass a window width in 1..8 (default 4)")
|
||||
_comb_table(w, multiprocess)
|
||||
return OK_TUPLE
|
||||
|
||||
|
||||
def _ct_select_packed(row, idx: int):
|
||||
"""Constant-time extraction of the idx-th affine table entry from the packed row `row`, returning (x, y, t2d).
|
||||
|
||||
A fixed len(row)-round masked scan (r |= e & m), with no secret-dependent branch / early exit.
|
||||
"""
|
||||
r = 0
|
||||
j = 0
|
||||
for e in row:
|
||||
r |= e & (((j ^ idx) - 1) >> 63)
|
||||
j += 1
|
||||
return (r & _SLOT_MASK, (r >> 256) & _SLOT_MASK, (r >> 512) & _SLOT_MASK)
|
||||
|
||||
|
||||
def _split(p):
|
||||
"""Unpack a packed affine table entry (x | y<<256 | t2d<<512)."""
|
||||
return (p & _SLOT_MASK, (p >> 256) & _SLOT_MASK, (p >> 512) & _SLOT_MASK)
|
||||
|
||||
|
||||
def _scalarmult_base_ct(scalar: int, window=None, multiprocess: bool = False) -> Point:
|
||||
"""Secret-scalar fixed-base multiplication scalar*B: affine Comb table + constant-time masked lookup + mixed addition.
|
||||
|
||||
The control flow is independent of the scalar: the main loop always runs ceil(256/w) rounds, each with a fixed 2^w masked comparisons + 1 point addition.
|
||||
"""
|
||||
w = _W_CT if window is None else int(window)
|
||||
rows = _comb_table(w, multiprocess)
|
||||
s = scalar & ((1 << 256) - 1)
|
||||
mask = (1 << w) - 1
|
||||
acc = IDENTITY
|
||||
i = 0
|
||||
for row in rows:
|
||||
acc = _pt_add_mixed(acc, *_ct_select_packed(row, (s >> (w * i)) & mask))
|
||||
i += 1
|
||||
return acc
|
||||
|
||||
|
||||
def _scalarmult_base_pub(scalar: int, window=None, multiprocess: bool = False) -> Point:
|
||||
"""Public-scalar fixed-base multiplication scalar*B: affine Comb table + plain indexing + mixed addition (faster than the masked scan)."""
|
||||
w = _W_CT if window is None else int(window)
|
||||
rows = _comb_table(w, multiprocess)
|
||||
s = scalar & ((1 << 256) - 1)
|
||||
mask = (1 << w) - 1
|
||||
acc = IDENTITY
|
||||
i = 0
|
||||
for row in rows:
|
||||
acc = _pt_add_mixed(acc, *_split(row[(s >> (w * i)) & mask]))
|
||||
i += 1
|
||||
return acc
|
||||
|
||||
|
||||
def _wnaf(k: int, w: int):
|
||||
"""wNAF recoding (public scalars only; the positions of non-zero digits depend on the scalar, so it is not constant time)."""
|
||||
digits = []
|
||||
m = (1 << w) - 1
|
||||
half = 1 << (w - 1)
|
||||
while k > 0:
|
||||
if k & 1:
|
||||
d = k & m
|
||||
if d >= half:
|
||||
d -= (1 << w)
|
||||
k -= d
|
||||
else:
|
||||
d = 0
|
||||
digits.append(d)
|
||||
k >>= 1
|
||||
return digits
|
||||
|
||||
|
||||
def _odd_multiples(pt: Point, w: int) -> List[Point]:
|
||||
"""Return [1P, 3P, 5P, ..., (2^(w-1)-1)P] (the wNAF table)."""
|
||||
tab = [pt]
|
||||
p2 = _pt_dbl(pt)
|
||||
for _ in range((1 << (w - 2)) - 1):
|
||||
tab.append(_pt_add(tab[-1], p2))
|
||||
return tab
|
||||
|
||||
|
||||
def _scalarmult_pub(pt: Point, scalar: int, w: int = 5) -> Point:
|
||||
"""**Public-scalar** variable-base scalar multiplication scalar*pt (wNAF-5, density about 1/6).
|
||||
|
||||
Usable only for public scalars (such as k in verification). The positions of non-zero wNAF digits depend on the scalar, making it a non-constant-time
|
||||
algorithm; it must **not** be used for secret-dependent operations such as private keys / randomness.
|
||||
"""
|
||||
tab = _odd_multiples(pt, w)
|
||||
acc = IDENTITY
|
||||
for d in reversed(_wnaf(int(scalar), w)):
|
||||
acc = _pt_dbl(acc)
|
||||
if d:
|
||||
q = tab[(d - 1) >> 1] if d > 0 else _pt_neg(tab[(-1 - d) >> 1])
|
||||
acc = _pt_add(acc, q)
|
||||
return acc
|
||||
|
||||
|
||||
def _scalarmult_joint(k1: int, tab1, k2: int, tab2, w: int = 5) -> Point:
|
||||
"""Straus / Shamir double scalar multiplication k1*P1 + k2*P2 (sharing doublings).
|
||||
|
||||
tab1 / tab2 are the odd-multiple tables of the respective points (can be generated with _odd_multiples). Public scalars only.
|
||||
"""
|
||||
d1 = _wnaf(int(k1), w)
|
||||
d2 = _wnaf(int(k2), w)
|
||||
n1 = len(d1)
|
||||
n2 = len(d2)
|
||||
acc = IDENTITY
|
||||
for i in range(max(n1, n2) - 1, -1, -1):
|
||||
acc = _pt_dbl(acc)
|
||||
if i < n1:
|
||||
d = d1[i]
|
||||
if d:
|
||||
q = tab1[(d - 1) >> 1] if d > 0 else _pt_neg(tab1[(-1 - d) >> 1])
|
||||
acc = _pt_add(acc, q)
|
||||
if i < n2:
|
||||
d = d2[i]
|
||||
if d:
|
||||
q = tab2[(d - 1) >> 1] if d > 0 else _pt_neg(tab2[(-1 - d) >> 1])
|
||||
acc = _pt_add(acc, q)
|
||||
return acc
|
||||
|
||||
|
||||
def _scalarmult(pt: Point, scalar: int) -> Point:
|
||||
"""Generic 4-bit window scalar multiplication (non-constant-time optimal, no precomputation), with constant-time table lookup.
|
||||
|
||||
Only used as the fallback path when precompute=False; the main loop always runs 64 rounds.
|
||||
"""
|
||||
s = scalar & ((1 << 256) - 1)
|
||||
table = [IDENTITY]
|
||||
cur = IDENTITY
|
||||
for _ in range(15):
|
||||
cur = _pt_add(cur, pt)
|
||||
table.append(cur)
|
||||
acc = IDENTITY
|
||||
for i in range(63, -1, -1):
|
||||
acc = _pt_dbl(acc)
|
||||
acc = _pt_dbl(acc)
|
||||
acc = _pt_dbl(acc)
|
||||
acc = _pt_dbl(acc)
|
||||
acc = _pt_add(acc, _ct_select_point(table, (s >> (4 * i)) & 0xF))
|
||||
return acc
|
||||
|
||||
|
||||
# ------------------------------------------------------------
|
||||
# 12.4 Point encoding / decoding (RFC 8032 section 5.1.2)
|
||||
# ------------------------------------------------------------
|
||||
|
||||
def _pt_encode(pt: Point) -> bytes:
|
||||
"""Compressed encoding: little-endian(y) | (x & 1) << 255."""
|
||||
x, y, z, _t = pt
|
||||
zi = pow(z, P - 2, P)
|
||||
xa = x * zi % P
|
||||
ya = y * zi % P
|
||||
return (ya | ((xa & 1) << 255)).to_bytes(32, "little")
|
||||
|
||||
|
||||
def _pt_encode_pair(p1: Point, p2: Point) -> Tuple[bytes, bytes]:
|
||||
"""Encode two points at once using a single Montgomery batch inversion (equivalent to two _pt_encode calls).
|
||||
|
||||
z = (z1*z2)^-1 => z1^-1 = z*z2, z2^-1 = z*z1; only 1 modular exponentiation instead of 2.
|
||||
"""
|
||||
z1 = p1[2]
|
||||
z2 = p2[2]
|
||||
zi = pow(z1 * z2 % P, P - 2, P)
|
||||
i1 = zi * z2 % P
|
||||
i2 = zi * z1 % P
|
||||
x1 = p1[0] * i1 % P
|
||||
y1 = p1[1] * i1 % P
|
||||
x2 = p2[0] * i2 % P
|
||||
y2 = p2[1] * i2 % P
|
||||
return ((y1 | ((x1 & 1) << 255)).to_bytes(32, "little"),
|
||||
(y2 | ((x2 & 1) << 255)).to_bytes(32, "little"))
|
||||
|
||||
|
||||
def _sqrt_ratio(u: int, v: int) -> int:
|
||||
"""Compute sqrt(u/v) mod p; raises PPYC_ERR(PPYC_ERR_INVALID_POINT) when it is not a square (p = 5 mod 8)."""
|
||||
v3 = v * v % P * v % P
|
||||
v7 = v3 * v3 % P * v % P
|
||||
r = u * v3 % P * pow(u * v7 % P, (P - 5) // 8, P) % P
|
||||
vxx = v * r % P * r % P
|
||||
if vxx == u % P:
|
||||
return r
|
||||
if vxx == (-u) % P:
|
||||
return r * SQRT_M1 % P
|
||||
raise PPYC_ERR(PPYC_ERR_INVALID_POINT,
|
||||
"invalid Ed25519 point encoding (x has no square root)",
|
||||
"check that the input is a valid 32-byte compressed point")
|
||||
|
||||
|
||||
def _pt_decode(b32: bytes) -> Point:
|
||||
"""Decode a 32-byte compressed point.
|
||||
|
||||
Raises ``PPYC_ERR`` on invalid encodings (fatal, error code ``PPYC_ERR_INVALID_LENGTH`` /
|
||||
``PPYC_ERR_INVALID_POINT``); callers needing boolean semantics (such as verification) should catch ``PPYC_ERR``.
|
||||
"""
|
||||
if len(b32) != 32:
|
||||
raise PPYC_ERR(PPYC_ERR_INVALID_LENGTH,
|
||||
f"an Ed25519 point encoding must be 32 bytes, got {len(b32)}",
|
||||
"pass a 32-byte compressed point")
|
||||
v = int.from_bytes(b32, "little")
|
||||
sign = (v >> 255) & 1
|
||||
y = v & ((1 << 255) - 1)
|
||||
if y >= P:
|
||||
raise PPYC_ERR(PPYC_ERR_INVALID_POINT,
|
||||
"invalid Ed25519 point encoding (y >= p)",
|
||||
"check that the input is a valid compressed point")
|
||||
yy = y * y % P
|
||||
x = _sqrt_ratio((yy - 1) % P, (D * yy + 1) % P)
|
||||
if x == 0 and sign == 1:
|
||||
raise PPYC_ERR(PPYC_ERR_INVALID_POINT,
|
||||
"invalid Ed25519 point encoding (x = 0 but the sign bit is 1)",
|
||||
"check that the input is a valid compressed point")
|
||||
if (x & 1) != sign:
|
||||
x = (P - x) % P
|
||||
return (x, y, 1, (x * y) % P)
|
||||
|
||||
|
||||
# ------------------------------------------------------------
|
||||
# 12.5 Scalar handling
|
||||
# ------------------------------------------------------------
|
||||
|
||||
def _clamp(h32: bytes) -> bytes:
|
||||
"""RFC 8032 section 5.1.5 private key scalar clamping: h[0] &= 248; h[31] &= 127; h[31] |= 64."""
|
||||
b = bytearray(h32)
|
||||
b[0] &= 248
|
||||
b[31] &= 127
|
||||
b[31] |= 64
|
||||
return bytes(b)
|
||||
|
||||
|
||||
def _secrets(seed32: bytes) -> Tuple[int, bytes, int]:
|
||||
"""Derive (scalar a, prefix prefix, a mod L) from the seed."""
|
||||
if len(seed32) != 32:
|
||||
raise PPYC_ERR(PPYC_ERR_INVALID_LENGTH,
|
||||
f"an Ed25519 seed must be 32 bytes, got {len(seed32)}",
|
||||
"pass a 32-byte seed")
|
||||
h = sha512(seed32)
|
||||
a_bytes = _clamp(h[0:32])
|
||||
prefix = h[32:64]
|
||||
a = int.from_bytes(a_bytes, "little")
|
||||
return a, prefix, a % L
|
||||
|
||||
|
||||
# ------------------------------------------------------------
|
||||
# 12.6 Public API (RFC 8032: keygen / publickey / sign / verify)
|
||||
# ------------------------------------------------------------
|
||||
# Tunable keyword arguments (defaults are optimal; positional arguments are fully compatible with the original version):
|
||||
# window Comb table window bit width, default None (uses the module constant _W_CT).
|
||||
# precompute True (default) uses the module-level precomputed Comb table; False falls back to generic double-and-add (slower).
|
||||
# multiprocess bool, affects only the one-off Comb table build.
|
||||
#
|
||||
# Secret scalars (a and r in signing) always go through _scalarmult_base_ct (constant-time masked scan);
|
||||
# public scalars (S and k in verification) go through _scalarmult_base_pub / _scalarmult_pub (wNAF).
|
||||
|
||||
|
||||
def ed25519_publickey(seed32, window=None, precompute=True,
|
||||
multiprocess=False):
|
||||
"""Derive the 32-byte public key A = a*B from a 32-byte seed (RFC 8032 section 5.1.5).
|
||||
|
||||
Returns
|
||||
----
|
||||
bytes
|
||||
32-byte public key.
|
||||
(str, str, str)
|
||||
A non-fatal error tuple; ``PPYC_ERR_INVALID_LENGTH`` (the seed is not 32 bytes).
|
||||
"""
|
||||
if len(seed32) != 32:
|
||||
return err(PPYC_ERR_INVALID_LENGTH,
|
||||
f"an Ed25519 seed must be 32 bytes, got {len(seed32)}",
|
||||
"pass a 32-byte seed")
|
||||
a = _secrets(seed32)[0]
|
||||
if precompute:
|
||||
pt = _scalarmult_base_ct(a, window, multiprocess)
|
||||
else:
|
||||
pt = _scalarmult(_BASE, a)
|
||||
return _pt_encode(pt)
|
||||
|
||||
|
||||
def ed25519_keygen(window=None, precompute=True, multiprocess=False):
|
||||
"""Generate a key pair.
|
||||
|
||||
Returns
|
||||
----
|
||||
(bytes, bytes)
|
||||
(seed32 seed, pub32 public key).
|
||||
"""
|
||||
seed = os.urandom(32)
|
||||
return seed, ed25519_publickey(seed, window, precompute, multiprocess)
|
||||
|
||||
|
||||
def ed25519_sign(message, seed32, window=None, precompute=True,
|
||||
multiprocess=False):
|
||||
"""RFC 8032 section 5.1.6 Ed25519 signing, returning 64 bytes (R || S).
|
||||
|
||||
r = SHA512(prefix || M) mod L; R = r·B; k = SHA512(R || A || M) mod L;
|
||||
S = (r + k*a) mod L. The encodings of A and R share one modular inversion (_pt_encode_pair).
|
||||
|
||||
Returns
|
||||
----
|
||||
bytes
|
||||
64-byte signature (R || S).
|
||||
(str, str, str)
|
||||
A non-fatal error tuple; ``PPYC_ERR_INVALID_LENGTH`` (the seed is not 32 bytes).
|
||||
"""
|
||||
if len(seed32) != 32:
|
||||
return err(PPYC_ERR_INVALID_LENGTH,
|
||||
f"an Ed25519 seed must be 32 bytes, got {len(seed32)}",
|
||||
"pass a 32-byte seed")
|
||||
a, prefix, a_mod = _secrets(seed32)
|
||||
if precompute:
|
||||
A = _scalarmult_base_ct(a, window, multiprocess)
|
||||
r = int.from_bytes(sha512(prefix + message), "little") % L
|
||||
R = _scalarmult_base_ct(r, window, multiprocess)
|
||||
else:
|
||||
A = _scalarmult(_BASE, a)
|
||||
r = int.from_bytes(sha512(prefix + message), "little") % L
|
||||
R = _scalarmult(_BASE, r)
|
||||
Aenc, Renc = _pt_encode_pair(A, R)
|
||||
k = int.from_bytes(sha512(Renc + Aenc + message), "little") % L
|
||||
S = (r + k * a_mod) % L
|
||||
return Renc + S.to_bytes(32, "little")
|
||||
|
||||
|
||||
def ed25519_verify(signature, message, public, window=None, precompute=True,
|
||||
multiprocess=False):
|
||||
"""RFC 8032 section 5.1.7 verification.
|
||||
|
||||
Tests [S]B == R + [k]A, equivalent to S*B - k*A - R == identity; the identity is tested by coordinates
|
||||
(X == 0 and Y == Z), avoiding point encoding / modular inversion. S*B uses the Comb table (public scalar) and
|
||||
k*A uses wNAF-5; so 1 fixed-base scalar multiplication + 1 variable-base wNAF in total.
|
||||
|
||||
Returns
|
||||
----
|
||||
bool
|
||||
True if the signature is valid; an invalid signature length / public key length, S >= L, or a failed
|
||||
point decoding all return False (boolean semantics preserved; the internal ``PPYC_ERR`` is caught in place).
|
||||
"""
|
||||
if len(signature) != 64 or len(public) != 32:
|
||||
return False
|
||||
S = int.from_bytes(signature[32:], "little")
|
||||
if S >= L: # RFC 8032 requires S < L
|
||||
return False
|
||||
try:
|
||||
A = _pt_decode(public)
|
||||
R = _pt_decode(signature[:32])
|
||||
except PPYC_ERR:
|
||||
return False
|
||||
k = int.from_bytes(sha512(signature[:32] + public + message), "little") % L
|
||||
sb = _scalarmult_base_pub(S, window, multiprocess)
|
||||
ka = _scalarmult_pub(A, k)
|
||||
x, y, z, _t = _pt_add(_pt_add(sb, _pt_neg(ka)), _pt_neg(R))
|
||||
return (x % P) == 0 and (y - z) % P == 0
|
||||
|
||||
|
||||
__all__ = [
|
||||
"Ed25519Error",
|
||||
"ed25519_keygen",
|
||||
"ed25519_publickey",
|
||||
"ed25519_sign",
|
||||
"ed25519_verify",
|
||||
"ed25519_precompute",
|
||||
]
|
||||
@@ -0,0 +1,922 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
purepycrypto.encoding
|
||||
=====================
|
||||
purepycrypto - Pure-Python cryptography library (zero dependencies)
|
||||
Pure-Python encodings: Base64 / Base32 / Base16 (Hex) / Base58 / big-integer base64url.
|
||||
|
||||
Design conventions
|
||||
--------
|
||||
* **Zero dependencies**: implemented in pure Python only, with no third-party library;
|
||||
* **Byte-for-byte identical to the standard library**:
|
||||
the output of ``b64encode`` / ``b32encode`` / ``hex_encode`` matches
|
||||
``base64.b64encode`` / ``base64.b32encode`` / ``bytes.hex()`` **exactly**
|
||||
(this module returns ASCII ``str``; its ``.encode("ascii")``
|
||||
is the ``bytes`` returned by the standard library, byte-for-byte);
|
||||
* **Unified error system** (see ``purepycrypto._ppyc_error``):
|
||||
- fatal errors -> ``raise PPYC_ERR(...)`` (not triggered by normal use of this module);
|
||||
- invalid input / failed validation -> ``return err(PPYC_ERR_xxx, msg, suggestion)`` 3-tuple;
|
||||
- success -> return ``str`` (encoding) or ``bytes`` (decoding).
|
||||
|
||||
Error codes
|
||||
------
|
||||
PPYC_ERR_INVALID_ARG invalid argument type / value
|
||||
PPYC_ERR_INVALID_ENCODING the encoded text contains invalid characters
|
||||
PPYC_ERR_INVALID_LENGTH invalid length / padding
|
||||
PPYC_ERR_INVALID_HEX invalid hex text
|
||||
|
||||
Usage
|
||||
----
|
||||
from purepycrypto.encoding import b64encode, b64decode
|
||||
|
||||
s = b64encode(b"hello") # "aGVsbG8="
|
||||
data = b64decode(s) # b"hello"
|
||||
code, msg, hint = b64decode("!!!") # invalid input -- returns an error 3-tuple
|
||||
"""
|
||||
|
||||
from ._ppyc_error import (
|
||||
err,
|
||||
PPYC_ERR_INVALID_ARG,
|
||||
PPYC_ERR_INVALID_ENCODING,
|
||||
PPYC_ERR_INVALID_LENGTH,
|
||||
PPYC_ERR_INVALID_HEX,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
# Base64
|
||||
"b64encode", "b64decode",
|
||||
"b64encode_urlsafe", "b64decode_urlsafe",
|
||||
"b64encode_nopad", "b64decode_nopad",
|
||||
# Base32
|
||||
"b32encode", "b32decode",
|
||||
"b32encode_hex", "b32decode_hex",
|
||||
# Base16 / Hex
|
||||
"hex_encode", "hex_decode",
|
||||
"hex_encode_sep", "hex_decode_sep",
|
||||
# Other
|
||||
"b64_encode_bigint", "b64_decode_bigint",
|
||||
"b58encode", "b58decode",
|
||||
]
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# 0. Internal helpers: type coercion and validation
|
||||
# ======================================================================
|
||||
|
||||
_BYTES_LIKE = (bytes, bytearray, memoryview)
|
||||
|
||||
|
||||
def _coerce_bytes(data, name="data"):
|
||||
"""Coerce ``data`` to ``bytes``.
|
||||
|
||||
Returns
|
||||
----
|
||||
(bytes, None) OK
|
||||
(None, (code, msg, hint)) invalid argument type (PPYC_ERR_INVALID_ARG)
|
||||
"""
|
||||
if isinstance(data, _BYTES_LIKE):
|
||||
return bytes(data), None
|
||||
return None, err(
|
||||
PPYC_ERR_INVALID_ARG,
|
||||
f"{name} must be bytes / bytearray, got {type(data).__name__}",
|
||||
"pass bytes-like data (the encoding input is binary)",
|
||||
)
|
||||
|
||||
|
||||
def _coerce_ascii(s, name="s"):
|
||||
"""Coerce the encoded text ``s`` (``str`` or ``bytes``) to ASCII ``bytes``.
|
||||
|
||||
Returns
|
||||
----
|
||||
(bytes, None) OK
|
||||
(None, (code, msg, hint)) invalid type (PPYC_ERR_INVALID_ARG) or non-ASCII characters present
|
||||
(PPYC_ERR_INVALID_ENCODING)
|
||||
"""
|
||||
if isinstance(s, str):
|
||||
try:
|
||||
return s.encode("ascii"), None
|
||||
except UnicodeEncodeError:
|
||||
return None, err(
|
||||
PPYC_ERR_INVALID_ENCODING,
|
||||
f"{name} contains non-ASCII characters and cannot be parsed as Base64/Base32/Base58",
|
||||
"make sure the input is ASCII text (or UTF-8 encode it first)",
|
||||
)
|
||||
if isinstance(s, _BYTES_LIKE):
|
||||
return bytes(s), None
|
||||
return None, err(
|
||||
PPYC_ERR_INVALID_ARG,
|
||||
f"{name} must be str or bytes, got {type(s).__name__}",
|
||||
"pass encoded text of type str / bytes",
|
||||
)
|
||||
|
||||
|
||||
def _coerce_altchars(altchars):
|
||||
"""Coerce ``altchars`` to a 2-byte ``bytes``.
|
||||
|
||||
Returns
|
||||
----
|
||||
(bytes(2), None) OK
|
||||
(None, (code, msg, hint)) invalid (PPYC_ERR_INVALID_ARG)
|
||||
"""
|
||||
if isinstance(altchars, str):
|
||||
try:
|
||||
altchars = altchars.encode("ascii")
|
||||
except UnicodeEncodeError:
|
||||
return None, err(
|
||||
PPYC_ERR_INVALID_ARG,
|
||||
"altchars must be 2 ASCII characters",
|
||||
"e.g. altchars='-_'",
|
||||
)
|
||||
if isinstance(altchars, _BYTES_LIKE):
|
||||
altchars = bytes(altchars)
|
||||
if len(altchars) != 2:
|
||||
return None, err(
|
||||
PPYC_ERR_INVALID_ARG,
|
||||
f"altchars length must be 2, got {len(altchars)}",
|
||||
"e.g. altchars=b'-_' (URL-safe)",
|
||||
)
|
||||
return altchars, None
|
||||
return None, err(
|
||||
PPYC_ERR_INVALID_ARG,
|
||||
f"altchars must be 2 bytes or 2 characters, got {type(altchars).__name__}",
|
||||
"e.g. altchars=b'-_'"
|
||||
)
|
||||
|
||||
|
||||
def _split_err(result):
|
||||
"""Determine whether a result is an error 3-tuple; if so return ``(True, err_tuple)``, otherwise ``(False, result)``."""
|
||||
if isinstance(result, tuple) and len(result) == 3 and isinstance(result[0], str) \
|
||||
and result[0].startswith("PPYC_ERR_"):
|
||||
return True, result
|
||||
return False, result
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# 1. Base64 (RFC 4648 section 4)
|
||||
# ======================================================================
|
||||
|
||||
_B64_ALPHABET = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
|
||||
_PAD = 0x3D # '='
|
||||
|
||||
|
||||
def _b64_encode_core(data):
|
||||
"""Pure implementation: ``bytes`` -> standard-alphabet Base64 ``bytes`` with padding."""
|
||||
alpha = _B64_ALPHABET
|
||||
n = len(data)
|
||||
out = bytearray()
|
||||
for i in range(0, n, 3):
|
||||
chunk = data[i:i + 3]
|
||||
b = len(chunk)
|
||||
v = 0
|
||||
for j in range(b):
|
||||
v |= chunk[j] << (16 - 8 * j)
|
||||
out.append(alpha[(v >> 18) & 0x3F])
|
||||
out.append(alpha[(v >> 12) & 0x3F])
|
||||
if b == 1:
|
||||
out.append(_PAD)
|
||||
out.append(_PAD)
|
||||
else:
|
||||
out.append(alpha[(v >> 6) & 0x3F])
|
||||
if b == 2:
|
||||
out.append(_PAD)
|
||||
else:
|
||||
out.append(alpha[v & 0x3F])
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def _b64_table(altchars=None):
|
||||
"""Build the Base64 decoding lookup table: values 0..63 / -1 invalid / -2 padding."""
|
||||
table = [-1] * 256
|
||||
for i, ch in enumerate(_B64_ALPHABET):
|
||||
table[ch] = i
|
||||
table[_PAD] = -2
|
||||
if altchars is not None:
|
||||
table[altchars[0]] = 62
|
||||
table[altchars[1]] = 63
|
||||
return table
|
||||
|
||||
|
||||
_B64_TABLE_STD = _b64_table()
|
||||
|
||||
|
||||
def _b64_decode_core(data, table, validate):
|
||||
"""Pure-implementation Base64 decoding core.
|
||||
|
||||
Returns
|
||||
----
|
||||
(bytes, None) OK
|
||||
(None, (code, msg, hint)) invalid encoding / length (PPYC_ERR_INVALID_ENCODING /
|
||||
PPYC_ERR_INVALID_LENGTH)
|
||||
"""
|
||||
vals = []
|
||||
pad = 0
|
||||
seen_pad = False
|
||||
for c in data:
|
||||
v = table[c]
|
||||
if v == -2: # '='
|
||||
seen_pad = True
|
||||
pad += 1
|
||||
continue
|
||||
if v == -1: # character outside the alphabet
|
||||
if validate:
|
||||
return None, err(
|
||||
PPYC_ERR_INVALID_ENCODING,
|
||||
f"Base64 input contains an invalid character 0x{c:02x} ({chr(c)!r})",
|
||||
"strict mode allows only A-Za-z0-9+/ and the padding '='",
|
||||
)
|
||||
continue
|
||||
if seen_pad: # data after padding
|
||||
if validate:
|
||||
return None, err(
|
||||
PPYC_ERR_INVALID_ENCODING,
|
||||
"extra data after the Base64 padding '='",
|
||||
"check whether the text was truncated or has appended content",
|
||||
)
|
||||
break
|
||||
vals.append(v)
|
||||
|
||||
if validate and not vals and pad > 0:
|
||||
return None, err(
|
||||
PPYC_ERR_INVALID_ENCODING,
|
||||
"Base64 text starts with the padding '='",
|
||||
"the padding '=' may only appear at the end",
|
||||
)
|
||||
|
||||
rem = len(vals) % 4
|
||||
expected = (4 - rem) % 4
|
||||
if rem == 1:
|
||||
return None, err(
|
||||
PPYC_ERR_INVALID_LENGTH,
|
||||
"the Base64 data character count is invalid (=1 mod 4)",
|
||||
"check for missing or extra characters",
|
||||
)
|
||||
if pad != expected:
|
||||
return None, err(
|
||||
PPYC_ERR_INVALID_LENGTH,
|
||||
f"incorrect Base64 padding count (expected {expected} '=' but got {pad})",
|
||||
"add the missing '=' or remove the extra '='",
|
||||
)
|
||||
|
||||
out = bytearray()
|
||||
n = len(vals)
|
||||
i = 0
|
||||
while i + 4 <= n:
|
||||
v = (vals[i] << 18) | (vals[i + 1] << 12) | (vals[i + 2] << 6) | vals[i + 3]
|
||||
out += v.to_bytes(3, "big")
|
||||
i += 4
|
||||
r = n - i
|
||||
if r == 2:
|
||||
v = (vals[i] << 18) | (vals[i + 1] << 12)
|
||||
out += v.to_bytes(3, "big")[:1]
|
||||
elif r == 3:
|
||||
v = (vals[i] << 18) | (vals[i + 1] << 12) | (vals[i + 2] << 6)
|
||||
out += v.to_bytes(3, "big")[:2]
|
||||
return bytes(out), None
|
||||
|
||||
|
||||
def b64encode(data, altchars=None):
|
||||
"""Base64 encoding (RFC 4648 section 4), byte-for-byte identical to ``base64.b64encode``.
|
||||
|
||||
Parameters
|
||||
----
|
||||
data : bytes | bytearray | memoryview
|
||||
Binary data to encode.
|
||||
altchars : bytes | str | None
|
||||
Optional 2-character replacement table, used to replace ``+`` and ``/`` in the standard alphabet
|
||||
(e.g. ``b"-_"`` gives URL-safe output); ``None`` means the standard alphabet.
|
||||
|
||||
Returns
|
||||
----
|
||||
str OK: ASCII Base64 text (``.encode("ascii")`` gives the standard-library bytes)
|
||||
(code, msg, hint) failure:
|
||||
- ``PPYC_ERR_INVALID_ARG`` invalid type or length of ``data`` / ``altchars``
|
||||
"""
|
||||
b, e = _coerce_bytes(data)
|
||||
if e is not None:
|
||||
return e
|
||||
core = _b64_encode_core(b)
|
||||
if altchars is not None:
|
||||
alt, e = _coerce_altchars(altchars)
|
||||
if e is not None:
|
||||
return e
|
||||
core = core.translate(bytes.maketrans(b"+/", alt))
|
||||
return core.decode("ascii")
|
||||
|
||||
|
||||
def b64decode(s, altchars=None, validate=False):
|
||||
"""Base64 decoding (RFC 4648 section 4), aligned with ``base64.b64decode``.
|
||||
|
||||
Parameters
|
||||
----
|
||||
s : str | bytes
|
||||
Base64 text to decode.
|
||||
altchars : bytes | str | None
|
||||
The same replacement table as :func:`b64encode` (decoding accepts both altchars and ``+/``).
|
||||
validate : bool
|
||||
When ``True``, strict validation is enabled: any non-alphabet character, misplaced padding or extra
|
||||
data after padding returns an error; when ``False``, non-alphabet characters are ignored (matching the lenient standard-library mode).
|
||||
|
||||
Returns
|
||||
----
|
||||
bytes OK: the decoded original data
|
||||
(code, msg, hint) failure:
|
||||
- ``PPYC_ERR_INVALID_ARG`` invalid argument type
|
||||
- ``PPYC_ERR_INVALID_ENCODING`` invalid character / misplaced padding (strict mode)
|
||||
- ``PPYC_ERR_INVALID_LENGTH`` incorrect length or padding count
|
||||
"""
|
||||
data, e = _coerce_ascii(s)
|
||||
if e is not None:
|
||||
return e
|
||||
if altchars is None:
|
||||
table = _B64_TABLE_STD
|
||||
else:
|
||||
alt, e = _coerce_altchars(altchars)
|
||||
if e is not None:
|
||||
return e
|
||||
table = _b64_table(alt)
|
||||
result, e = _b64_decode_core(data, table, bool(validate))
|
||||
if e is not None:
|
||||
return e
|
||||
return result
|
||||
|
||||
|
||||
def _b64_urlsafe_decode(data):
|
||||
"""URL-safe decoding core (tolerates missing padding, for JWK/JWT use).
|
||||
|
||||
Returns
|
||||
----
|
||||
(bytes, None) / (None, err_tuple)
|
||||
"""
|
||||
core = data.rstrip(b"=")
|
||||
if b"=" in core:
|
||||
return None, err(
|
||||
PPYC_ERR_INVALID_ENCODING,
|
||||
"Base64URL text has data before the padding '='",
|
||||
"check whether '=' or invalid characters were mixed in",
|
||||
)
|
||||
if len(core) % 4 == 1:
|
||||
return None, err(
|
||||
PPYC_ERR_INVALID_LENGTH,
|
||||
"the Base64URL data character count is invalid (=1 mod 4)",
|
||||
"check for missing or extra characters",
|
||||
)
|
||||
padded = core + b"=" * ((-len(core)) % 4)
|
||||
return _b64_decode_core(padded, _B64_TABLE_URLSAFE, True)
|
||||
|
||||
|
||||
_B64_TABLE_URLSAFE = _b64_table(b"-_")
|
||||
|
||||
|
||||
def b64encode_urlsafe(data):
|
||||
"""URL-safe Base64 encoding (``+``/``/`` -> ``-``/``_``), keeping the ``=`` padding.
|
||||
|
||||
Returns
|
||||
----
|
||||
str OK: ASCII URL-safe Base64 text
|
||||
(code, msg, hint) failure: ``PPYC_ERR_INVALID_ARG`` (``data`` is not bytes-like)
|
||||
"""
|
||||
return b64encode(data, altchars=b"-_")
|
||||
|
||||
|
||||
def b64decode_urlsafe(s):
|
||||
"""URL-safe Base64 decoding, **tolerating missing ``=`` padding** (convenient for parsing JWK/JWT).
|
||||
|
||||
Returns
|
||||
----
|
||||
bytes OK: the decoded original data
|
||||
(code, msg, hint) failure:
|
||||
- ``PPYC_ERR_INVALID_ARG`` invalid argument type
|
||||
- ``PPYC_ERR_INVALID_ENCODING`` invalid character
|
||||
- ``PPYC_ERR_INVALID_LENGTH`` invalid length
|
||||
"""
|
||||
data, e = _coerce_ascii(s)
|
||||
if e is not None:
|
||||
return e
|
||||
result, e = _b64_urlsafe_decode(data)
|
||||
if e is not None:
|
||||
return e
|
||||
return result
|
||||
|
||||
|
||||
def b64encode_nopad(data):
|
||||
"""Base64 encoding (standard alphabet), with the ``=`` padding **removed**.
|
||||
|
||||
Returns
|
||||
----
|
||||
str OK: unpadded ASCII Base64 text
|
||||
(code, msg, hint) failure: ``PPYC_ERR_INVALID_ARG`` (``data`` is not bytes-like)
|
||||
"""
|
||||
b, e = _coerce_bytes(data)
|
||||
if e is not None:
|
||||
return e
|
||||
return _b64_encode_core(b).rstrip(b"=").decode("ascii")
|
||||
|
||||
|
||||
def b64decode_nopad(s):
|
||||
"""Base64 decoding (standard alphabet), **accepting unpadded input** (padding is added automatically).
|
||||
|
||||
Returns
|
||||
----
|
||||
bytes OK: the decoded original data
|
||||
(code, msg, hint) failure:
|
||||
- ``PPYC_ERR_INVALID_ARG`` invalid argument type
|
||||
- ``PPYC_ERR_INVALID_ENCODING`` invalid character / '=' in the middle
|
||||
- ``PPYC_ERR_INVALID_LENGTH`` invalid length
|
||||
"""
|
||||
data, e = _coerce_ascii(s)
|
||||
if e is not None:
|
||||
return e
|
||||
core = data.rstrip(b"=")
|
||||
if b"=" in core:
|
||||
return err(
|
||||
PPYC_ERR_INVALID_ENCODING,
|
||||
"Base64 text has data before the padding '='",
|
||||
"check whether '=' or invalid characters were mixed in",
|
||||
)
|
||||
if len(core) % 4 == 1:
|
||||
return err(
|
||||
PPYC_ERR_INVALID_LENGTH,
|
||||
"the Base64 data character count is invalid (=1 mod 4)",
|
||||
"check for missing or extra characters",
|
||||
)
|
||||
padded = core + b"=" * ((-len(core)) % 4)
|
||||
result, e = _b64_decode_core(padded, _B64_TABLE_STD, True)
|
||||
if e is not None:
|
||||
return e
|
||||
return result
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# 2. Base32 (RFC 4648 sections 6 / 7)
|
||||
# ======================================================================
|
||||
|
||||
_B32_ALPHABET = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"
|
||||
_B32HEX_ALPHABET = b"0123456789ABCDEFGHIJKLMNOPQRSTUV"
|
||||
|
||||
|
||||
def _b32_encode_core(data, alphabet):
|
||||
"""Pure implementation: ``bytes`` -> padded Base32 ``bytes`` (5 bytes -> 8 characters)."""
|
||||
n = len(data)
|
||||
out = bytearray()
|
||||
for i in range(0, n, 5):
|
||||
chunk = data[i:i + 5]
|
||||
b = len(chunk)
|
||||
buf = chunk + b"\x00" * (5 - b)
|
||||
v = int.from_bytes(buf, "big") # 40 bit
|
||||
sig = (b * 8 + 4) // 5 # number of significant characters
|
||||
for j in range(8):
|
||||
if j < sig:
|
||||
out.append(alphabet[(v >> (35 - 5 * j)) & 0x1F])
|
||||
else:
|
||||
out.append(_PAD)
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def _b32_table(alphabet, casefold=False):
|
||||
"""Build the Base32 decoding lookup table (values 0..31 / -1 invalid / -2 padding)."""
|
||||
table = [-1] * 256
|
||||
for i, ch in enumerate(alphabet):
|
||||
table[ch] = i
|
||||
table[_PAD] = -2
|
||||
if casefold:
|
||||
for c in range(0x61, 0x7B): # a..z
|
||||
up = c - 32
|
||||
if table[up] != -1:
|
||||
table[c] = table[up]
|
||||
return table
|
||||
|
||||
|
||||
_B32_TABLE_STD = _b32_table(_B32_ALPHABET, False)
|
||||
_B32_TABLE_STD_CF = _b32_table(_B32_ALPHABET, True)
|
||||
_B32_TABLE_HEX = _b32_table(_B32HEX_ALPHABET, False)
|
||||
_B32_TABLE_HEX_CF = _b32_table(_B32HEX_ALPHABET, True)
|
||||
|
||||
|
||||
def _b32_decode_core(data, table):
|
||||
"""Pure-implementation Base32 decoding core.
|
||||
|
||||
Returns
|
||||
----
|
||||
(bytes, None) OK
|
||||
(None, (code, msg, hint)) invalid character (PPYC_ERR_INVALID_ENCODING)
|
||||
or length / padding error (PPYC_ERR_INVALID_LENGTH)
|
||||
"""
|
||||
vals = []
|
||||
pad = 0
|
||||
seen_pad = False
|
||||
for c in data:
|
||||
v = table[c]
|
||||
if v == -2: # '='
|
||||
seen_pad = True
|
||||
pad += 1
|
||||
continue
|
||||
if v == -1:
|
||||
return None, err(
|
||||
PPYC_ERR_INVALID_ENCODING,
|
||||
f"Base32 input contains an invalid character 0x{c:02x} ({chr(c)!r})",
|
||||
"Base32 allows only alphabet characters and the padding '='",
|
||||
)
|
||||
if seen_pad:
|
||||
return None, err(
|
||||
PPYC_ERR_INVALID_ENCODING,
|
||||
"extra data after the Base32 padding '='",
|
||||
"check whether the text was truncated or has appended content",
|
||||
)
|
||||
vals.append(v)
|
||||
|
||||
total = len(vals) + pad
|
||||
if total % 8 != 0:
|
||||
return None, err(
|
||||
PPYC_ERR_INVALID_LENGTH,
|
||||
f"the Base32 text length must be a multiple of 8, got {total}",
|
||||
"add the missing characters or '=' padding, or remove extra characters",
|
||||
)
|
||||
rem = len(vals) % 8
|
||||
expected = (8 - rem) % 8
|
||||
if rem not in (0, 2, 4, 5, 7):
|
||||
return None, err(
|
||||
PPYC_ERR_INVALID_LENGTH,
|
||||
f"invalid number of trailing Base32 data characters ({rem} left)",
|
||||
"the valid counts of trailing data characters are 0 / 2 / 4 / 5 / 7",
|
||||
)
|
||||
if pad != expected:
|
||||
return None, err(
|
||||
PPYC_ERR_INVALID_LENGTH,
|
||||
f"incorrect Base32 padding count (expected {expected} '=' but got {pad})",
|
||||
"add the missing '=' or remove the extra '='",
|
||||
)
|
||||
|
||||
out = bytearray()
|
||||
full = len(vals) - rem
|
||||
for i in range(0, full, 8):
|
||||
v = 0
|
||||
for j in range(8):
|
||||
v = (v << 5) | vals[i + j]
|
||||
out += v.to_bytes(5, "big")
|
||||
if rem:
|
||||
acc = 0
|
||||
for x in vals[full:]:
|
||||
acc = (acc << 5) | x
|
||||
nbytes = {2: 1, 4: 2, 5: 3, 7: 4}[rem]
|
||||
shift = rem * 5 - nbytes * 8
|
||||
out += (acc >> shift).to_bytes(nbytes, "big")
|
||||
return bytes(out), None
|
||||
|
||||
|
||||
def b32encode(data):
|
||||
"""Base32 encoding (RFC 4648 section 6, standard alphabet A-Z2-7), consistent with ``base64.b32encode``.
|
||||
|
||||
Returns
|
||||
----
|
||||
str OK: ASCII Base32 text
|
||||
(code, msg, hint) failure: ``PPYC_ERR_INVALID_ARG`` (``data`` is not bytes-like)
|
||||
"""
|
||||
b, e = _coerce_bytes(data)
|
||||
if e is not None:
|
||||
return e
|
||||
return _b32_encode_core(b, _B32_ALPHABET).decode("ascii")
|
||||
|
||||
|
||||
def b32decode(s, casefold=False):
|
||||
"""Base32 decoding (RFC 4648 section 6, standard alphabet A-Z2-7), consistent with ``base64.b32decode``.
|
||||
|
||||
Parameters
|
||||
----
|
||||
s : str | bytes
|
||||
Base32 text.
|
||||
casefold : bool
|
||||
When ``True``, lower-case letters are accepted (a-z is treated the same as A-Z).
|
||||
|
||||
Returns
|
||||
----
|
||||
bytes OK: the decoded original data
|
||||
(code, msg, hint) failure:
|
||||
- ``PPYC_ERR_INVALID_ARG`` invalid argument type
|
||||
- ``PPYC_ERR_INVALID_ENCODING`` invalid character / extra data after padding
|
||||
- ``PPYC_ERR_INVALID_LENGTH`` incorrect length or padding count
|
||||
"""
|
||||
data, e = _coerce_ascii(s)
|
||||
if e is not None:
|
||||
return e
|
||||
table = _B32_TABLE_STD_CF if casefold else _B32_TABLE_STD
|
||||
result, e = _b32_decode_core(data, table)
|
||||
if e is not None:
|
||||
return e
|
||||
return result
|
||||
|
||||
|
||||
def b32encode_hex(data):
|
||||
"""Base32 encoding (RFC 4648 section 7 Extended Hex alphabet 0-9A-V), consistent with ``base64.b32hexencode``.
|
||||
|
||||
Returns
|
||||
----
|
||||
str OK: ASCII Base32-Hex text
|
||||
(code, msg, hint) failure: ``PPYC_ERR_INVALID_ARG`` (``data`` is not bytes-like)
|
||||
"""
|
||||
b, e = _coerce_bytes(data)
|
||||
if e is not None:
|
||||
return e
|
||||
return _b32_encode_core(b, _B32HEX_ALPHABET).decode("ascii")
|
||||
|
||||
|
||||
def b32decode_hex(s, casefold=False):
|
||||
"""Base32 decoding (RFC 4648 section 7 Extended Hex alphabet 0-9A-V), consistent with ``base64.b32hexdecode``.
|
||||
|
||||
Parameters
|
||||
----
|
||||
s : str | bytes
|
||||
Base32-Hex text.
|
||||
casefold : bool
|
||||
When ``True``, lower-case letters are accepted.
|
||||
|
||||
Returns
|
||||
----
|
||||
bytes OK: the decoded original data
|
||||
(code, msg, hint) failure:
|
||||
- ``PPYC_ERR_INVALID_ARG`` invalid argument type
|
||||
- ``PPYC_ERR_INVALID_ENCODING`` invalid character / extra data after padding
|
||||
- ``PPYC_ERR_INVALID_LENGTH`` incorrect length or padding count
|
||||
"""
|
||||
data, e = _coerce_ascii(s)
|
||||
if e is not None:
|
||||
return e
|
||||
table = _B32_TABLE_HEX_CF if casefold else _B32_TABLE_HEX
|
||||
result, e = _b32_decode_core(data, table)
|
||||
if e is not None:
|
||||
return e
|
||||
return result
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# 3. Base16 / Hex (RFC 4648 section 8)
|
||||
# ======================================================================
|
||||
|
||||
def _as_hex_str(s):
|
||||
"""Normalize the hex text ``s`` to ``str``.
|
||||
|
||||
Returns
|
||||
----
|
||||
(str, None) / (None, err_tuple)
|
||||
"""
|
||||
if isinstance(s, str):
|
||||
return s, None
|
||||
if isinstance(s, _BYTES_LIKE):
|
||||
try:
|
||||
return bytes(s).decode("ascii"), None
|
||||
except UnicodeDecodeError:
|
||||
return None, err(
|
||||
PPYC_ERR_INVALID_HEX,
|
||||
"the hex input contains a non-ASCII byte",
|
||||
"hex text should consist only of 0-9A-Fa-f",
|
||||
)
|
||||
return None, err(
|
||||
PPYC_ERR_INVALID_ARG,
|
||||
f"the hex input must be str or bytes, got {type(s).__name__}",
|
||||
"pass a hexadecimal string",
|
||||
)
|
||||
|
||||
|
||||
def hex_encode(data, upper=False):
|
||||
"""Base16 / Hex encoding, byte-for-byte identical to ``bytes.hex()``.
|
||||
|
||||
Parameters
|
||||
----
|
||||
data : bytes | bytearray | memoryview
|
||||
Data to encode.
|
||||
upper : bool
|
||||
When ``True``, output upper-case hex (``bytes.hex().upper()``).
|
||||
|
||||
Returns
|
||||
----
|
||||
str OK: hexadecimal text
|
||||
(code, msg, hint) failure: ``PPYC_ERR_INVALID_ARG`` (``data`` is not bytes-like)
|
||||
"""
|
||||
b, e = _coerce_bytes(data)
|
||||
if e is not None:
|
||||
return e
|
||||
h = b.hex()
|
||||
return h.upper() if upper else h
|
||||
|
||||
|
||||
def hex_decode(s):
|
||||
"""Base16 / Hex decoding, behaving like ``bytes.fromhex()`` (allows spaces between bytes).
|
||||
|
||||
Returns
|
||||
----
|
||||
bytes OK: the decoded original data
|
||||
(code, msg, hint) failure:
|
||||
- ``PPYC_ERR_INVALID_ARG`` invalid argument type
|
||||
- ``PPYC_ERR_INVALID_HEX`` invalid hex text (invalid character or odd length)
|
||||
"""
|
||||
t, e = _as_hex_str(s)
|
||||
if e is not None:
|
||||
return e
|
||||
try:
|
||||
return bytes.fromhex(t)
|
||||
except ValueError as ex:
|
||||
return err(
|
||||
PPYC_ERR_INVALID_HEX,
|
||||
f"invalid hexadecimal text: {ex}",
|
||||
"hex text should contain only 0-9A-Fa-f (spaces between bytes are allowed) with an even length",
|
||||
)
|
||||
|
||||
|
||||
def hex_encode_sep(data, sep=":", upper=False):
|
||||
"""Base16 / Hex encoding with a separator (convenient for displaying fingerprints / keys).
|
||||
|
||||
Parameters
|
||||
----
|
||||
data : bytes | bytearray | memoryview
|
||||
Data to encode.
|
||||
sep : str
|
||||
Separator placed between bytes, default ``":"``; an empty string is equivalent to :func:`hex_encode`.
|
||||
upper : bool
|
||||
When ``True``, output upper-case.
|
||||
|
||||
Returns
|
||||
----
|
||||
str OK: text of the form ``"de:ad:be:ef"``
|
||||
(code, msg, hint) failure:
|
||||
- ``PPYC_ERR_INVALID_ARG`` ``data`` is not bytes-like
|
||||
- ``PPYC_ERR_INVALID_ARG`` ``sep`` is not str
|
||||
"""
|
||||
if not isinstance(sep, str):
|
||||
return err(
|
||||
PPYC_ERR_INVALID_ARG,
|
||||
f"sep must be str, got {type(sep).__name__}",
|
||||
"e.g. sep=':' or sep='-'"
|
||||
)
|
||||
h = hex_encode(data, upper=upper)
|
||||
is_e, _ = _split_err(h)
|
||||
if is_e:
|
||||
return h
|
||||
if not sep:
|
||||
return h
|
||||
return sep.join(h[i:i + 2] for i in range(0, len(h), 2))
|
||||
|
||||
|
||||
def hex_decode_sep(s, sep=":"):
|
||||
"""Base16 / Hex decoding with a separator (the counterpart of :func:`hex_encode_sep`).
|
||||
|
||||
Parameters
|
||||
----
|
||||
s : str | bytes
|
||||
Text of the form ``"de:ad:be:ef"``.
|
||||
sep : str
|
||||
Separator; an empty string means no separator is used.
|
||||
|
||||
Returns
|
||||
----
|
||||
bytes OK: the decoded original data
|
||||
(code, msg, hint) failure:
|
||||
- ``PPYC_ERR_INVALID_ARG`` invalid argument type
|
||||
- ``PPYC_ERR_INVALID_HEX`` invalid hex text
|
||||
"""
|
||||
if not isinstance(sep, str):
|
||||
return err(
|
||||
PPYC_ERR_INVALID_ARG,
|
||||
f"sep must be str, got {type(sep).__name__}",
|
||||
"e.g. sep=':' or sep='-'"
|
||||
)
|
||||
t, e = _as_hex_str(s)
|
||||
if e is not None:
|
||||
return e
|
||||
if sep:
|
||||
parts = t.split(sep)
|
||||
cleaned = "".join(p.strip() for p in parts)
|
||||
else:
|
||||
cleaned = t.replace(" ", "")
|
||||
try:
|
||||
return bytes.fromhex(cleaned)
|
||||
except ValueError as ex:
|
||||
return err(
|
||||
PPYC_ERR_INVALID_HEX,
|
||||
f"invalid hexadecimal text: {ex}",
|
||||
"hex text should contain only 0-9A-Fa-f with an even length",
|
||||
)
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# 4. Big integer <-> Base64URL (JWK style)
|
||||
# ======================================================================
|
||||
|
||||
def b64_encode_bigint(n):
|
||||
"""Big integer -> Base64URL (unpadded), for JWK fields such as ``n``/``e``.
|
||||
|
||||
Uses the shortest big-endian representation: ``0`` -> ``""``.
|
||||
|
||||
Returns
|
||||
----
|
||||
str OK: URL-safe, unpadded Base64 text
|
||||
(code, msg, hint) failure: ``PPYC_ERR_INVALID_ARG``
|
||||
(``n`` is not an int or is negative)
|
||||
"""
|
||||
if isinstance(n, bool) or not isinstance(n, int):
|
||||
return err(
|
||||
PPYC_ERR_INVALID_ARG,
|
||||
f"n must be int, got {type(n).__name__}",
|
||||
"pass a non-negative integer",
|
||||
)
|
||||
if n < 0:
|
||||
return err(
|
||||
PPYC_ERR_INVALID_ARG,
|
||||
f"n must be a non-negative integer, got {n}",
|
||||
"big-integer encoding requires n >= 0",
|
||||
)
|
||||
nbytes = (n.bit_length() + 7) // 8
|
||||
raw = n.to_bytes(nbytes, "big")
|
||||
return _b64_encode_core(raw).translate(bytes.maketrans(b"+/", b"-_")).rstrip(b"=").decode("ascii")
|
||||
|
||||
|
||||
def b64_decode_bigint(s):
|
||||
"""Base64URL (unpadded) -> big integer, the inverse of :func:`b64_encode_bigint`.
|
||||
|
||||
Returns
|
||||
----
|
||||
int OK: the decoded big integer
|
||||
(code, msg, hint) failure:
|
||||
- ``PPYC_ERR_INVALID_ARG`` invalid argument type
|
||||
- ``PPYC_ERR_INVALID_ENCODING`` invalid character
|
||||
- ``PPYC_ERR_INVALID_LENGTH`` invalid length
|
||||
"""
|
||||
data, e = _coerce_ascii(s)
|
||||
if e is not None:
|
||||
return e
|
||||
result, e = _b64_urlsafe_decode(data)
|
||||
if e is not None:
|
||||
return e
|
||||
return int.from_bytes(result, "big")
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# 5. Base58 (Bitcoin alphabet)
|
||||
# ======================================================================
|
||||
|
||||
_B58_ALPHABET = b"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
|
||||
_B58_TABLE = [-1] * 256
|
||||
for _i, _ch in enumerate(_B58_ALPHABET):
|
||||
_B58_TABLE[_ch] = _i
|
||||
del _i, _ch
|
||||
|
||||
|
||||
def b58encode(data):
|
||||
"""Base58 encoding (Bitcoin alphabet, excluding the easily confused ``0 O I l``).
|
||||
|
||||
A leading zero byte is encoded as a leading ``'1'``.
|
||||
|
||||
Returns
|
||||
----
|
||||
str OK: Base58 text
|
||||
(code, msg, hint) failure: ``PPYC_ERR_INVALID_ARG`` (``data`` is not bytes-like)
|
||||
"""
|
||||
b, e = _coerce_bytes(data)
|
||||
if e is not None:
|
||||
return e
|
||||
n = int.from_bytes(b, "big")
|
||||
out = bytearray()
|
||||
while n > 0:
|
||||
n, r = divmod(n, 58)
|
||||
out.append(_B58_ALPHABET[r])
|
||||
pad = 0
|
||||
for byte in b:
|
||||
if byte == 0:
|
||||
pad += 1
|
||||
else:
|
||||
break
|
||||
if pad:
|
||||
out.extend(_B58_ALPHABET[0:1] * pad)
|
||||
out.reverse()
|
||||
return out.decode("ascii")
|
||||
|
||||
|
||||
def b58decode(s):
|
||||
"""Base58 decoding (Bitcoin alphabet), the inverse of :func:`b58encode`.
|
||||
|
||||
Returns
|
||||
----
|
||||
bytes OK: the decoded original data
|
||||
(code, msg, hint) failure:
|
||||
- ``PPYC_ERR_INVALID_ARG`` invalid argument type
|
||||
- ``PPYC_ERR_INVALID_ENCODING`` contains a non-Base58 character
|
||||
"""
|
||||
data, e = _coerce_ascii(s)
|
||||
if e is not None:
|
||||
return e
|
||||
pad = 0
|
||||
for c in data:
|
||||
if c == _B58_ALPHABET[0]:
|
||||
pad += 1
|
||||
else:
|
||||
break
|
||||
n = 0
|
||||
for c in data:
|
||||
v = _B58_TABLE[c]
|
||||
if v == -1:
|
||||
return err(
|
||||
PPYC_ERR_INVALID_ENCODING,
|
||||
f"Base58 input contains an invalid character 0x{c:02x} ({chr(c)!r})",
|
||||
"the Base58 (Bitcoin) alphabet excludes 0 / O / I / l and symbols",
|
||||
)
|
||||
n = n * 58 + v
|
||||
nbytes = (n.bit_length() + 7) // 8
|
||||
return b"\x00" * pad + n.to_bytes(nbytes, "big")
|
||||
@@ -0,0 +1,84 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Example: encrypt / decrypt a file using the pure-Python implementation
|
||||
================================================
|
||||
Demonstrates:
|
||||
- Argon2id / scrypt key derivation from a passphrase
|
||||
- AES-256-GCM authenticated encryption
|
||||
- file format: MAGIC | salt | nonce | ciphertext | tag
|
||||
|
||||
Usage:
|
||||
python encrypt_file.py enc <input file> <output file> <passphrase>
|
||||
python encrypt_file.py dec <input file> <output file> <passphrase>
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
|
||||
from purepycrypto import AES, argon2id, DecryptionError
|
||||
|
||||
MAGIC = b"PPYC1"
|
||||
SALT_LEN = 16
|
||||
NONCE_LEN = 12
|
||||
KEY_LEN = 32
|
||||
|
||||
|
||||
def derive_key(password: str, salt: bytes) -> bytes:
|
||||
"""Derive a 32-byte key from the passphrase using Argon2id."""
|
||||
return argon2id(password.encode("utf-8"), salt,
|
||||
t=3, m=65536, p=4, tag_length=KEY_LEN)
|
||||
|
||||
|
||||
def encrypt(in_path: str, out_path: str, password: str) -> None:
|
||||
with open(in_path, "rb") as f:
|
||||
plaintext = f.read()
|
||||
|
||||
salt = os.urandom(SALT_LEN)
|
||||
nonce = os.urandom(NONCE_LEN)
|
||||
key = derive_key(password, salt)
|
||||
|
||||
aes = AES(key)
|
||||
ciphertext, tag = aes.gcm_encrypt(nonce, plaintext)
|
||||
|
||||
with open(out_path, "wb") as f:
|
||||
f.write(MAGIC + salt + nonce + ciphertext + tag)
|
||||
print(f"[✓] Encrypted {in_path} -> {out_path} ({len(plaintext)} bytes)")
|
||||
|
||||
|
||||
def decrypt(in_path: str, out_path: str, password: str) -> None:
|
||||
with open(in_path, "rb") as f:
|
||||
blob = f.read()
|
||||
|
||||
if not blob.startswith(MAGIC):
|
||||
raise SystemExit("[✗] Bad file format (MAGIC mismatch)")
|
||||
body = blob[len(MAGIC):]
|
||||
salt = body[:SALT_LEN]
|
||||
nonce = body[SALT_LEN:SALT_LEN + NONCE_LEN]
|
||||
ciphertext = body[SALT_LEN + NONCE_LEN:-16]
|
||||
tag = body[-16:]
|
||||
|
||||
key = derive_key(password, salt)
|
||||
aes = AES(key)
|
||||
try:
|
||||
plaintext = aes.gcm_decrypt(nonce, ciphertext, tag)
|
||||
except DecryptionError:
|
||||
raise SystemExit("[✗] Decryption failed: wrong passphrase or the file was tampered with")
|
||||
|
||||
with open(out_path, "wb") as f:
|
||||
f.write(plaintext)
|
||||
print(f"[✓] Decrypted {in_path} -> {out_path} ({len(plaintext)} bytes)")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
if len(sys.argv) != 5 or sys.argv[1] not in ("enc", "dec"):
|
||||
print(__doc__)
|
||||
raise SystemExit(1)
|
||||
mode, in_path, out_path, password = sys.argv[1:5]
|
||||
if mode == "enc":
|
||||
encrypt(in_path, out_path, password)
|
||||
else:
|
||||
decrypt(in_path, out_path, password)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,62 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Example: X25519 key exchange + HKDF + AES-GCM hybrid encryption
|
||||
================================================
|
||||
Demonstrates the classic ECDH + KDF + AEAD hybrid encryption flow:
|
||||
|
||||
Alice Bob
|
||||
------ -----
|
||||
(a, A=g^a) (b, B=g^b)
|
||||
A --------->
|
||||
<--------- B
|
||||
s = B^a s = A^b
|
||||
key = HKDF(s, ...) ----------------- key = HKDF(s, ...)
|
||||
AES-GCM(key, msg) --------->
|
||||
"""
|
||||
from purepycrypto import (
|
||||
x25519_generate_keypair, x25519_shared,
|
||||
hkdf, AES,
|
||||
)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
print("== 1. Both sides generate their own X25519 key pair ==")
|
||||
alice_priv, alice_pub = x25519_generate_keypair()
|
||||
bob_priv, bob_pub = x25519_generate_keypair()
|
||||
print(f" Alice public key: {alice_pub.hex()[:32]}...")
|
||||
print(f" Bob public key: {bob_pub.hex()[:32]}...")
|
||||
|
||||
print("\n== 2. Each side computes the shared secret (ECDH) ==")
|
||||
alice_shared, a_zero = x25519_shared(alice_priv, bob_pub)
|
||||
bob_shared, b_zero = x25519_shared(bob_priv, alice_pub)
|
||||
assert alice_shared == bob_shared, "shared secrets differ!"
|
||||
assert not a_zero and not b_zero, "low-order point detected, shared secret is unsafe!"
|
||||
print(f" Shared secret matches ✓ ({alice_shared.hex()[:32]}...)")
|
||||
|
||||
print("\n== 3. Derive the session key from the shared secret using HKDF ==")
|
||||
salt = b"purepycrypto-demo-salt"
|
||||
info = b"session-key-v1"
|
||||
alice_key = hkdf(alice_shared, salt, info, 32)
|
||||
bob_key = hkdf(bob_shared, salt, info, 32)
|
||||
assert alice_key == bob_key
|
||||
print(f" Session key matches ✓ ({alice_key.hex()[:32]}...)")
|
||||
|
||||
print("\n== 4. Alice encrypts a message with the session key ==")
|
||||
import os
|
||||
message = b"Meet me at the usual place at noon."
|
||||
nonce = os.urandom(12)
|
||||
# Note: in a real setting the nonce should be sent first; here it travels with the ciphertext
|
||||
ciphertext, tag = AES(alice_key).gcm_encrypt(nonce, message)
|
||||
print(f" plaintext: {message!r}")
|
||||
print(f" ciphertext: {ciphertext.hex()}")
|
||||
|
||||
print("\n== 5. Bob decrypts ==")
|
||||
plaintext = AES(bob_key).gcm_decrypt(nonce, ciphertext, tag)
|
||||
print(f" decrypted: {plaintext!r}")
|
||||
assert plaintext == message
|
||||
print("\n[✓] Hybrid encryption flow completed successfully")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,61 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Example: correct usage of multiprocess parallel acceleration (Windows must-read)
|
||||
================================================
|
||||
Demonstrates `sha3_batch` batch parallelism and automatic multiprocessing for large AES-GCM-SIV inputs.
|
||||
|
||||
⚠️ Key point: the script must be wrapped in `if __name__ == "__main__":`!
|
||||
Windows uses spawn to start child processes, which re-import the main module;
|
||||
calling a multiprocessing API at module top level will raise:
|
||||
RuntimeError: An attempt has been made to start a new process
|
||||
before the current process has finished its bootstrapping phase.
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
|
||||
# Windows Chinese console (GBK) compatibility: avoid UnicodeEncodeError when printing non-GBK characters
|
||||
for _s in ("stdout", "stderr"):
|
||||
_stream = getattr(sys, _s, None)
|
||||
if _stream is not None:
|
||||
try:
|
||||
_stream.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
from purepycrypto import sha3_batch, aes256_gcm_siv_encrypt
|
||||
|
||||
|
||||
def main():
|
||||
# ---- 1) Batch hashing (multiprocess parallel) ----
|
||||
messages = [os.urandom(4096) for _ in range(400)] # 400 messages of 4KB (enough to yield a parallel speedup)
|
||||
|
||||
t0 = time.perf_counter()
|
||||
d1 = sha3_batch(messages, "sha3_256", n_workers=1) # serial
|
||||
t1 = time.perf_counter() - t0
|
||||
|
||||
t0 = time.perf_counter()
|
||||
d2 = sha3_batch(messages, "sha3_256", n_workers=4) # 4 processes
|
||||
t2 = time.perf_counter() - t0
|
||||
|
||||
assert d1 == d2, "parallel results must match the serial ones"
|
||||
print(f"[sha3_batch] 400 x 4KB: serial {t1*1000:.1f} ms / 4 procs {t2*1000:.1f} ms"
|
||||
f" speedup {t1/t2:.2f}x")
|
||||
|
||||
# ---- 2) Large AES-GCM-SIV input (automatic multiprocessing) ----
|
||||
key = os.urandom(32)
|
||||
nonce = os.urandom(12)
|
||||
data = os.urandom(512 * 1024) # 512 KB
|
||||
|
||||
ct, tag = aes256_gcm_siv_encrypt(key, nonce, data) # automatic multiprocessing
|
||||
print(f"[AES-GCM-SIV] 512KB encrypted, ciphertext {len(ct)} bytes, tag {tag.hex()[:16]}...")
|
||||
|
||||
# force a serial comparison
|
||||
ct2, tag2 = aes256_gcm_siv_encrypt(key, nonce, data, n_workers=1)
|
||||
assert (ct, tag) == (ct2, tag2), "parallel/serial results must match"
|
||||
print("[AES-GCM-SIV] multiprocess and serial results match OK")
|
||||
|
||||
|
||||
if __name__ == "__main__": # <- REQUIRED on Windows
|
||||
main()
|
||||
@@ -0,0 +1,57 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Example: RSA-PSS sign and verify + PEM key persistence
|
||||
================================================
|
||||
Demonstrates:
|
||||
- generating an RSA key pair
|
||||
- exporting PEM (PKCS#8 / SPKI)
|
||||
- PSS signing and verification of a message
|
||||
- tamper detection
|
||||
"""
|
||||
import os
|
||||
import tempfile
|
||||
|
||||
from purepycrypto import (
|
||||
rsa_keygen, rsa_pss_sign, rsa_pss_verify,
|
||||
private_key_to_pem, public_key_to_pem, parse_private_pem,
|
||||
)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
print("== 1. Generate an RSA-2048 key pair ==")
|
||||
pub, priv = rsa_keygen(bits=2048)
|
||||
print(f" n = {priv.n.bit_length()} bit, e = {priv.e}")
|
||||
|
||||
print("\n== 2. Export PEM ==")
|
||||
priv_pem = private_key_to_pem(priv)
|
||||
pub_pem = public_key_to_pem(pub)
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
priv_path = os.path.join(d, "private.pem")
|
||||
pub_path = os.path.join(d, "public.pem")
|
||||
with open(priv_path, "w", encoding="ascii") as f:
|
||||
f.write(priv_pem)
|
||||
with open(pub_path, "w", encoding="ascii") as f:
|
||||
f.write(pub_pem)
|
||||
print(f" private key written to {priv_path}")
|
||||
print(f" public key written to {pub_path}")
|
||||
|
||||
print("\n== 3. Reload the private key from PEM ==")
|
||||
with open(priv_path, encoding="ascii") as f:
|
||||
priv2 = parse_private_pem(f.read())
|
||||
assert priv2.n == priv.n
|
||||
print(" Loaded successfully, modulus matches ✓")
|
||||
|
||||
print("\n== 4. PSS sign / verify ==")
|
||||
message = b"https://example.com/important-document"
|
||||
signature = rsa_pss_sign(message, priv)
|
||||
print(f" signature length: {len(signature)} bytes")
|
||||
print(f" verify result: {rsa_pss_verify(message, signature, pub)}")
|
||||
|
||||
print("\n== 5. Tamper detection ==")
|
||||
tampered = message + b"!"
|
||||
print(f" verify after tampering: {rsa_pss_verify(tampered, signature, pub)} (should be False)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,253 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""purepycrypto.hash
|
||||
========================================
|
||||
purepycrypto - Pure-Python cryptography library (zero dependencies)
|
||||
Pure-Python hash implementations: SHA-256, SHA-512, BLAKE2b.
|
||||
"""
|
||||
|
||||
import struct
|
||||
|
||||
from .common import MASK32, MASK64
|
||||
from ._ppyc_error import err, PPYC_ERR_INVALID_ARG
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 2. SHA-256
|
||||
# ============================================================
|
||||
|
||||
SHA256_H0 = (0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
|
||||
0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19)
|
||||
|
||||
SHA256_K = (
|
||||
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
|
||||
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
|
||||
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
|
||||
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
|
||||
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
|
||||
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
|
||||
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
|
||||
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
|
||||
)
|
||||
|
||||
|
||||
def sha256(message: bytes) -> bytes:
|
||||
L = len(message) * 8
|
||||
padded = message + b"\x80"
|
||||
while len(padded) % 64 != 56:
|
||||
padded += b"\x00"
|
||||
padded += struct.pack(">Q", L & MASK64)
|
||||
|
||||
state = list(SHA256_H0)
|
||||
K = SHA256_K
|
||||
M = MASK32
|
||||
for i in range(0, len(padded), 64):
|
||||
W = list(struct.unpack(">16I", padded[i:i + 64]))
|
||||
for t in range(16, 64):
|
||||
x = W[t - 15]
|
||||
y = W[t - 2]
|
||||
s0 = ((x >> 7) | (x << 25)) ^ ((x >> 18) | (x << 14)) ^ (x >> 3)
|
||||
s1 = ((y >> 17) | (y << 15)) ^ ((y >> 19) | (y << 13)) ^ (y >> 10)
|
||||
W.append((W[t - 16] + s0 + W[t - 7] + s1) & M)
|
||||
|
||||
a, b, c, d, e, f, g, h = state
|
||||
for t in range(64):
|
||||
S1 = ((e >> 6) | (e << 26)) ^ ((e >> 11) | (e << 21)) ^ ((e >> 25) | (e << 7))
|
||||
ch = (e & f) ^ ((~e) & g)
|
||||
T1 = (h + S1 + ch + K[t] + W[t]) & M
|
||||
S0 = ((a >> 2) | (a << 30)) ^ ((a >> 13) | (a << 19)) ^ ((a >> 22) | (a << 10))
|
||||
maj = (a & b) ^ (a & c) ^ (b & c)
|
||||
T2 = (S0 + maj) & M
|
||||
h, g, f, e, d, c, b, a = (
|
||||
g, f, e, (d + T1) & M, c, b, a, (T1 + T2) & M
|
||||
)
|
||||
state[0] = (state[0] + a) & M
|
||||
state[1] = (state[1] + b) & M
|
||||
state[2] = (state[2] + c) & M
|
||||
state[3] = (state[3] + d) & M
|
||||
state[4] = (state[4] + e) & M
|
||||
state[5] = (state[5] + f) & M
|
||||
state[6] = (state[6] + g) & M
|
||||
state[7] = (state[7] + h) & M
|
||||
|
||||
return struct.pack(">8I", *state)
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 3. SHA-512
|
||||
# ============================================================
|
||||
|
||||
SHA512_H0 = (
|
||||
0x6a09e667f3bcc908, 0xbb67ae8584caa73b, 0x3c6ef372fe94f82b, 0xa54ff53a5f1d36f1,
|
||||
0x510e527fade682d1, 0x9b05688c2b3e6c1f, 0x1f83d9abfb41bd6b, 0x5be0cd19137e2179,
|
||||
)
|
||||
|
||||
SHA512_K = (
|
||||
0x428a2f98d728ae22, 0x7137449123ef65cd, 0xb5c0fbcfec4d3b2f, 0xe9b5dba58189dbbc,
|
||||
0x3956c25bf348b538, 0x59f111f1b605d019, 0x923f82a4af194f9b, 0xab1c5ed5da6d8118,
|
||||
0xd807aa98a3030242, 0x12835b0145706fbe, 0x243185be4ee4b28c, 0x550c7dc3d5ffb4e2,
|
||||
0x72be5d74f27b896f, 0x80deb1fe3b1696b1, 0x9bdc06a725c71235, 0xc19bf174cf692694,
|
||||
0xe49b69c19ef14ad2, 0xefbe4786384f25e3, 0x0fc19dc68b8cd5b5, 0x240ca1cc77ac9c65,
|
||||
0x2de92c6f592b0275, 0x4a7484aa6ea6e483, 0x5cb0a9dcbd41fbd4, 0x76f988da831153b5,
|
||||
0x983e5152ee66dfab, 0xa831c66d2db43210, 0xb00327c898fb213f, 0xbf597fc7beef0ee4,
|
||||
0xc6e00bf33da88fc2, 0xd5a79147930aa725, 0x06ca6351e003826f, 0x142929670a0e6e70,
|
||||
0x27b70a8546d22ffc, 0x2e1b21385c26c926, 0x4d2c6dfc5ac42aed, 0x53380d139d95b3df,
|
||||
0x650a73548baf63de, 0x766a0abb3c77b2a8, 0x81c2c92e47edaee6, 0x92722c851482353b,
|
||||
0xa2bfe8a14cf10364, 0xa81a664bbc423001, 0xc24b8b70d0f89791, 0xc76c51a30654be30,
|
||||
0xd192e819d6ef5218, 0xd69906245565a910, 0xf40e35855771202a, 0x106aa07032bbd1b8,
|
||||
0x19a4c116b8d2d0c8, 0x1e376c085141ab53, 0x2748774cdf8eeb99, 0x34b0bcb5e19b48a8,
|
||||
0x391c0cb3c5c95a63, 0x4ed8aa4ae3418acb, 0x5b9cca4f7763e373, 0x682e6ff3d6b2b8a3,
|
||||
0x748f82ee5defb2fc, 0x78a5636f43172f60, 0x84c87814a1f0ab72, 0x8cc702081a6439ec,
|
||||
0x90befffa23631e28, 0xa4506cebde82bde9, 0xbef9a3f7b2c67915, 0xc67178f2e372532b,
|
||||
0xca273eceea26619c, 0xd186b8c721c0c207, 0xeada7dd6cde0eb1e, 0xf57d4f7fee6ed178,
|
||||
0x06f067aa72176fba, 0x0a637dc5a2c898a6, 0x113f9804bef90dae, 0x1b710b35131c471b,
|
||||
0x28db77f523047d84, 0x32caab7b40c72493, 0x3c9ebe0a15c9bebc, 0x431d67c49c100d4c,
|
||||
0x4cc5d4becb3e42b6, 0x597f299cfc657e2a, 0x5fcb6fab3ad6faec, 0x6c44198c4a475817,
|
||||
)
|
||||
|
||||
|
||||
def sha512(message: bytes) -> bytes:
|
||||
L = len(message) * 8
|
||||
padded = message + b"\x80"
|
||||
while len(padded) % 128 != 112:
|
||||
padded += b"\x00"
|
||||
padded += struct.pack(">QQ", (L >> 64) & MASK64, L & MASK64)
|
||||
|
||||
state = list(SHA512_H0)
|
||||
K = SHA512_K
|
||||
M = MASK64
|
||||
for i in range(0, len(padded), 128):
|
||||
W = list(struct.unpack(">16Q", padded[i:i + 128]))
|
||||
for t in range(16, 80):
|
||||
x = W[t - 15]
|
||||
y = W[t - 2]
|
||||
s0 = ((x >> 1) | (x << 63)) ^ ((x >> 8) | (x << 56)) ^ (x >> 7)
|
||||
s1 = ((y >> 19) | (y << 45)) ^ ((y >> 61) | (y << 3)) ^ (y >> 6)
|
||||
W.append((W[t - 16] + s0 + W[t - 7] + s1) & M)
|
||||
|
||||
a, b, c, d, e, f, g, h = state
|
||||
for t in range(80):
|
||||
S1 = ((e >> 14) | (e << 50)) ^ ((e >> 18) | (e << 46)) ^ ((e >> 41) | (e << 23))
|
||||
ch = (e & f) ^ ((~e) & g)
|
||||
T1 = (h + S1 + ch + K[t] + W[t]) & M
|
||||
S0 = ((a >> 28) | (a << 36)) ^ ((a >> 34) | (a << 30)) ^ ((a >> 39) | (a << 25))
|
||||
maj = (a & b) ^ (a & c) ^ (b & c)
|
||||
T2 = (S0 + maj) & M
|
||||
h, g, f, e, d, c, b, a = (
|
||||
g, f, e, (d + T1) & M, c, b, a, (T1 + T2) & M
|
||||
)
|
||||
state[0] = (state[0] + a) & M
|
||||
state[1] = (state[1] + b) & M
|
||||
state[2] = (state[2] + c) & M
|
||||
state[3] = (state[3] + d) & M
|
||||
state[4] = (state[4] + e) & M
|
||||
state[5] = (state[5] + f) & M
|
||||
state[6] = (state[6] + g) & M
|
||||
state[7] = (state[7] + h) & M
|
||||
|
||||
return struct.pack(">8Q", *state)
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 4. BLAKE2b
|
||||
# ============================================================
|
||||
|
||||
BLAKE2B_IV = (
|
||||
0x6a09e667f3bcc908, 0xbb67ae8584caa73b,
|
||||
0x3c6ef372fe94f82b, 0xa54ff53a5f1d36f1,
|
||||
0x510e527fade682d1, 0x9b05688c2b3e6c1f,
|
||||
0x1f83d9abfb41bd6b, 0x5be0cd19137e2179,
|
||||
)
|
||||
|
||||
SIGMA = (
|
||||
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15),
|
||||
(14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3),
|
||||
(11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4),
|
||||
(7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8),
|
||||
(9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13),
|
||||
(2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9),
|
||||
(12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11),
|
||||
(13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10),
|
||||
(6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5),
|
||||
(10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0),
|
||||
)
|
||||
|
||||
|
||||
def _blake2b_compress(h, block, t0, t1, f):
|
||||
M = MASK64
|
||||
v = list(h) + list(BLAKE2B_IV)
|
||||
v[12] ^= t0
|
||||
v[13] ^= t1
|
||||
v[14] ^= f
|
||||
m = list(struct.unpack("<16Q", block))
|
||||
|
||||
def G(a, b, c, d, x, y):
|
||||
v[a] = (v[a] + v[b] + x) & M
|
||||
v[d] = ((v[d] ^ v[a]) >> 32) | (((v[d] ^ v[a]) << 32) & M)
|
||||
v[c] = (v[c] + v[d]) & M
|
||||
v[b] = ((v[b] ^ v[c]) >> 24) | (((v[b] ^ v[c]) << 40) & M)
|
||||
v[a] = (v[a] + v[b] + y) & M
|
||||
v[d] = ((v[d] ^ v[a]) >> 16) | (((v[d] ^ v[a]) << 48) & M)
|
||||
v[c] = (v[c] + v[d]) & M
|
||||
v[b] = ((v[b] ^ v[c]) >> 63) | (((v[b] ^ v[c]) << 1) & M)
|
||||
|
||||
for r in range(12):
|
||||
s = SIGMA[r % 10]
|
||||
G(0, 4, 8, 12, m[s[0]], m[s[1]])
|
||||
G(1, 5, 9, 13, m[s[2]], m[s[3]])
|
||||
G(2, 6, 10, 14, m[s[4]], m[s[5]])
|
||||
G(3, 7, 11, 15, m[s[6]], m[s[7]])
|
||||
G(0, 5, 10, 15, m[s[8]], m[s[9]])
|
||||
G(1, 6, 11, 12, m[s[10]], m[s[11]])
|
||||
G(2, 7, 8, 13, m[s[12]], m[s[13]])
|
||||
G(3, 4, 9, 14, m[s[14]], m[s[15]])
|
||||
|
||||
for i in range(8):
|
||||
h[i] = (h[i] ^ v[i] ^ v[i + 8]) & M
|
||||
return h
|
||||
|
||||
|
||||
def blake2b(data: bytes, digest_size: int = 64):
|
||||
"""BLAKE2b hash (RFC 7693).
|
||||
|
||||
Parameters
|
||||
----
|
||||
data : bytes
|
||||
Data to hash.
|
||||
digest_size : int
|
||||
Output digest length, 1..64 (default 64).
|
||||
|
||||
Returns
|
||||
----
|
||||
bytes
|
||||
A digest of length ``digest_size``.
|
||||
tuple
|
||||
When ``digest_size`` is invalid (not an integer, or outside 1..64) returns
|
||||
``(PPYC_ERR_INVALID_ARG, reason, suggestion)``.
|
||||
"""
|
||||
if isinstance(digest_size, bool) or not isinstance(digest_size, int) \
|
||||
or not (1 <= digest_size <= 64):
|
||||
return err(PPYC_ERR_INVALID_ARG,
|
||||
f"BLAKE2b digest_size must be between 1 and 64, got {digest_size!r}",
|
||||
"pass an integer in 1..64 (default 64)")
|
||||
h = list(BLAKE2B_IV)
|
||||
h[0] ^= digest_size | (1 << 16) | (1 << 24)
|
||||
t0, t1 = 0, 0
|
||||
pos = 0
|
||||
# Key point: only compress as an intermediate block (f=0) when the remaining data EXCEEDS one block,
|
||||
# otherwise the final block (including the case of exactly 128 bytes) must be finalized with f=MASK64.
|
||||
# Empty input also requires compressing one all-zero block (RFC 7693).
|
||||
while len(data) - pos > 128:
|
||||
t0 += 128
|
||||
if t0 > MASK64:
|
||||
t1 += 1
|
||||
t0 &= MASK64
|
||||
h = _blake2b_compress(h, data[pos:pos + 128], t0, t1, 0)
|
||||
pos += 128
|
||||
last = data[pos:]
|
||||
t0 += len(last)
|
||||
if t0 > MASK64:
|
||||
t1 += 1
|
||||
t0 &= MASK64
|
||||
last_padded = last + b"\x00" * (128 - len(last))
|
||||
h = _blake2b_compress(h, last_padded, t0, t1, MASK64)
|
||||
return struct.pack("<8Q", *h)[:digest_size]
|
||||
@@ -0,0 +1,553 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""purepycrypto.kdf
|
||||
========================================
|
||||
purepycrypto - Pure-Python cryptography library (zero dependencies)
|
||||
Key derivation: HMAC-SHA256/512, PBKDF2, HKDF, scrypt (RFC 7914), Argon2id (RFC 9106).
|
||||
"""
|
||||
|
||||
import struct
|
||||
|
||||
from .common import MASK32, MASK64
|
||||
from .hash import sha256, sha512, blake2b
|
||||
from ._ppyc_error import (
|
||||
PPYC_ERR, err, is_err,
|
||||
PPYC_ERR_INVALID_ARG,
|
||||
PPYC_ERR_INVALID_ALGO,
|
||||
PPYC_ERR_INVALID_KDF_PARAM,
|
||||
PPYC_ERR_INTERNAL,
|
||||
)
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 5. Argon2id (RFC 9106)
|
||||
# ============================================================
|
||||
|
||||
def _h_prime(data: bytes, outlen: int):
|
||||
"""Argon2 variable-length hash H' (RFC 9106 section 3.3).
|
||||
|
||||
Returns
|
||||
----
|
||||
bytes
|
||||
A digest of length ``outlen``.
|
||||
tuple
|
||||
Only propagates the error tuple of the internal ``blake2b`` check when it fails
|
||||
``(PPYC_ERR_INVALID_ARG, ...)`` (cannot happen with normal parameters).
|
||||
"""
|
||||
if outlen <= 64:
|
||||
return blake2b(struct.pack("<I", outlen) + data, digest_size=outlen)
|
||||
r = (outlen + 31) // 32 - 2
|
||||
V = blake2b(struct.pack("<I", outlen) + data, digest_size=64)
|
||||
if is_err(V):
|
||||
return V
|
||||
out = V[:32]
|
||||
for _ in range(r - 1):
|
||||
V = blake2b(V, digest_size=64)
|
||||
if is_err(V):
|
||||
return V
|
||||
out += V[:32]
|
||||
V = blake2b(V, digest_size=outlen - 32 * r)
|
||||
if is_err(V):
|
||||
return V
|
||||
out += V
|
||||
return out[:outlen]
|
||||
|
||||
|
||||
def _gb(v, a, b, c, d):
|
||||
M = MASK64
|
||||
v[a] = (v[a] + v[b] + 2 * (v[a] & MASK32) * (v[b] & MASK32)) & M
|
||||
v[d] = ((v[d] ^ v[a]) >> 32) | (((v[d] ^ v[a]) << 32) & M)
|
||||
v[c] = (v[c] + v[d] + 2 * (v[c] & MASK32) * (v[d] & MASK32)) & M
|
||||
v[b] = ((v[b] ^ v[c]) >> 24) | (((v[b] ^ v[c]) << 40) & M)
|
||||
v[a] = (v[a] + v[b] + 2 * (v[a] & MASK32) * (v[b] & MASK32)) & M
|
||||
v[d] = ((v[d] ^ v[a]) >> 16) | (((v[d] ^ v[a]) << 48) & M)
|
||||
v[c] = (v[c] + v[d] + 2 * (v[c] & MASK32) * (v[d] & MASK32)) & M
|
||||
v[b] = ((v[b] ^ v[c]) >> 63) | (((v[b] ^ v[c]) << 1) & M)
|
||||
|
||||
|
||||
def _permute_p(S: bytes) -> bytes:
|
||||
regs = []
|
||||
for i in range(8):
|
||||
row = []
|
||||
for j in range(8):
|
||||
off = (i * 8 + j) * 16
|
||||
lo, hi = struct.unpack("<2Q", S[off:off + 16])
|
||||
row.append([lo, hi])
|
||||
regs.append(row)
|
||||
|
||||
def perm(rl):
|
||||
v = []
|
||||
for lo, hi in rl:
|
||||
v.append(lo); v.append(hi)
|
||||
_gb(v, 0, 4, 8, 12); _gb(v, 1, 5, 9, 13)
|
||||
_gb(v, 2, 6, 10, 14); _gb(v, 3, 7, 11, 15)
|
||||
_gb(v, 0, 5, 10, 15); _gb(v, 1, 6, 11, 12)
|
||||
_gb(v, 2, 7, 8, 13); _gb(v, 3, 4, 9, 14)
|
||||
return [[v[2 * i], v[2 * i + 1]] for i in range(8)]
|
||||
|
||||
for i in range(8):
|
||||
regs[i] = perm(regs[i])
|
||||
for j in range(8):
|
||||
col = [regs[i][j] for i in range(8)]
|
||||
col_p = perm(col)
|
||||
for i in range(8):
|
||||
regs[i][j] = col_p[i]
|
||||
|
||||
out = bytearray(1024)
|
||||
for i in range(8):
|
||||
for j in range(8):
|
||||
off = (i * 8 + j) * 16
|
||||
out[off:off + 16] = struct.pack("<2Q", regs[i][j][0], regs[i][j][1])
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def _compress_g(X: bytes, Y: bytes) -> bytes:
|
||||
R = bytes(a ^ b for a, b in zip(X, Y))
|
||||
Z = _permute_p(R)
|
||||
return bytes(a ^ b for a, b in zip(Z, R))
|
||||
|
||||
|
||||
def argon2id(password: bytes, salt: bytes, t: int = 1, m: int = 256, p: int = 1,
|
||||
tag_length: int = 32, secret: bytes = b"", ad: bytes = b"",
|
||||
version: int = 0x13):
|
||||
"""Argon2id key derivation (RFC 9106).
|
||||
|
||||
Parameters
|
||||
----
|
||||
t : int number of iterations (passes), must be >= 1
|
||||
m : int number of memory blocks (KiB), must be >= 8*p
|
||||
p : int parallelism (number of lanes), must be >= 1
|
||||
tag_length : int output length (bytes), must be >= 4
|
||||
|
||||
Returns
|
||||
----
|
||||
bytes
|
||||
A derived key of length ``tag_length``.
|
||||
tuple
|
||||
Invalid parameters return a 3-tuple, always with error code ``PPYC_ERR_INVALID_KDF_PARAM``:
|
||||
triggered by ``t < 1`` / ``p < 1`` / ``m < 8*p`` / ``tag_length < 4``.
|
||||
"""
|
||||
if t < 1:
|
||||
return err(PPYC_ERR_INVALID_KDF_PARAM,
|
||||
f"Argon2id iteration count t must be >= 1, got {t}",
|
||||
"RFC 9106 recommends a value such as t=3")
|
||||
if p < 1:
|
||||
return err(PPYC_ERR_INVALID_KDF_PARAM,
|
||||
f"Argon2id parallelism p must be >= 1, got {p}",
|
||||
"p is usually set to the number of CPU cores")
|
||||
if m < 8 * p:
|
||||
return err(PPYC_ERR_INVALID_KDF_PARAM,
|
||||
f"Argon2id memory parameter m must be >= 8*p (m={m}, p={p})",
|
||||
"increase m or decrease p")
|
||||
if tag_length < 4:
|
||||
return err(PPYC_ERR_INVALID_KDF_PARAM,
|
||||
f"Argon2id output length tag_length must be >= 4, got {tag_length}",
|
||||
"pass a tag_length >= 4 (16/32/64 are common)")
|
||||
|
||||
h0_input = (struct.pack("<I", p) + struct.pack("<I", tag_length) +
|
||||
struct.pack("<I", m) + struct.pack("<I", t) +
|
||||
struct.pack("<I", version) + struct.pack("<I", 2) +
|
||||
struct.pack("<I", len(password)) + password +
|
||||
struct.pack("<I", len(salt)) + salt +
|
||||
struct.pack("<I", len(secret)) + secret +
|
||||
struct.pack("<I", len(ad)) + ad)
|
||||
H0 = blake2b(h0_input, digest_size=64)
|
||||
if is_err(H0):
|
||||
return H0
|
||||
|
||||
m_prime = 4 * p * (m // (4 * p))
|
||||
q = m_prime // p
|
||||
SL = 4
|
||||
seg = q // SL
|
||||
|
||||
B = [[bytearray(1024) for _ in range(q)] for _ in range(p)]
|
||||
|
||||
for i in range(p):
|
||||
blk0 = _h_prime(H0 + struct.pack("<I", 0) + struct.pack("<I", i), 1024)
|
||||
if is_err(blk0):
|
||||
return blk0
|
||||
blk1 = _h_prime(H0 + struct.pack("<I", 1) + struct.pack("<I", i), 1024)
|
||||
if is_err(blk1):
|
||||
return blk1
|
||||
B[i][0][:] = blk0
|
||||
B[i][1][:] = blk1
|
||||
|
||||
for r in range(t):
|
||||
for sl in range(SL):
|
||||
for i in range(p):
|
||||
if r == 0 and sl < 2:
|
||||
Z = (struct.pack("<Q", r) + struct.pack("<Q", i) +
|
||||
struct.pack("<Q", sl) + struct.pack("<Q", m_prime) +
|
||||
struct.pack("<Q", t) + struct.pack("<Q", 2))
|
||||
addr_blocks = (seg * 8 + 1023) // 1024 + 1
|
||||
addr_all = []
|
||||
for idx in range(1, addr_blocks + 1):
|
||||
inp = Z + struct.pack("<Q", idx) + b"\x00" * 968
|
||||
zero = bytes(1024)
|
||||
tmp = _compress_g(zero, inp)
|
||||
addr_block = _compress_g(zero, tmp)
|
||||
addr_all.append(addr_block)
|
||||
addr_bytes = b"".join(addr_all)
|
||||
|
||||
start = 2 if (r == 0 and sl == 0) else 0
|
||||
|
||||
for j in range(start, seg):
|
||||
curr = sl * seg + j
|
||||
prev = bytes(B[i][(curr - 1) % q])
|
||||
|
||||
if r == 0 and sl < 2:
|
||||
off = j * 8
|
||||
J1 = struct.unpack_from("<I", addr_bytes, off)[0]
|
||||
J2 = struct.unpack_from("<I", addr_bytes, off + 4)[0]
|
||||
else:
|
||||
J1 = struct.unpack_from("<I", prev, 0)[0]
|
||||
J2 = struct.unpack_from("<I", prev, 4)[0]
|
||||
|
||||
if r == 0 and sl == 0:
|
||||
ref_lane = i
|
||||
else:
|
||||
ref_lane = J2 % p
|
||||
|
||||
same_lane = (ref_lane == i)
|
||||
if r == 0:
|
||||
if sl == 0: W = j - 1
|
||||
elif same_lane: W = sl * seg + j - 1
|
||||
elif j == 0: W = sl * seg - 1
|
||||
else: W = sl * seg
|
||||
else:
|
||||
if same_lane: W = q - seg + j - 1
|
||||
elif j == 0: W = q - seg - 1
|
||||
else: W = q - seg
|
||||
W = max(W, 1)
|
||||
|
||||
x = ((J1 * J1) >> 32) & MASK64
|
||||
yv = ((W * x) >> 32) & MASK64
|
||||
zz = W - 1 - yv
|
||||
|
||||
if r == 0:
|
||||
start_pos = 0
|
||||
else:
|
||||
start_pos = ((sl + 1) * seg) % q
|
||||
|
||||
ref_col = (start_pos + zz) % q
|
||||
ref_block = bytes(B[ref_lane][ref_col])
|
||||
new_block = _compress_g(prev, ref_block)
|
||||
|
||||
if r > 0 or curr >= 2:
|
||||
new_block = bytes(a ^ b for a, b in zip(new_block, B[i][curr]))
|
||||
B[i][curr][:] = new_block
|
||||
|
||||
final = bytearray(B[0][q - 1])
|
||||
for i in range(1, p):
|
||||
for k in range(1024):
|
||||
final[k] ^= B[i][q - 1][k]
|
||||
|
||||
tag = _h_prime(bytes(final), tag_length)
|
||||
if is_err(tag):
|
||||
return tag
|
||||
return tag
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 6. HMAC / PBKDF2 / scrypt / HKDF
|
||||
# ============================================================
|
||||
|
||||
def hmac_sha256(key: bytes, message: bytes) -> bytes:
|
||||
bs = 64
|
||||
if len(key) > bs:
|
||||
key = sha256(key)
|
||||
key = key + b"\x00" * (bs - len(key))
|
||||
ipad = bytes(b ^ 0x36 for b in key)
|
||||
opad = bytes(b ^ 0x5c for b in key)
|
||||
return sha256(opad + sha256(ipad + message))
|
||||
|
||||
|
||||
def hmac_sha512(key: bytes, message: bytes) -> bytes:
|
||||
bs = 128
|
||||
if len(key) > bs:
|
||||
key = sha512(key)
|
||||
key = key + b"\x00" * (bs - len(key))
|
||||
ipad = bytes(b ^ 0x36 for b in key)
|
||||
opad = bytes(b ^ 0x5c for b in key)
|
||||
return sha512(opad + sha512(ipad + message))
|
||||
|
||||
|
||||
def pbkdf2_hmac(password: bytes, salt: bytes, iterations: int,
|
||||
dklen: int, hash_name: str = "sha256"):
|
||||
"""PBKDF2-HMAC key derivation (RFC 8018).
|
||||
|
||||
Returns
|
||||
----
|
||||
bytes
|
||||
A derived key of length ``dklen``.
|
||||
tuple
|
||||
On error returns a 3-tuple:
|
||||
|
||||
* ``PPYC_ERR_INVALID_ALGO`` -- ``hash_name`` is not sha256/sha512
|
||||
* ``PPYC_ERR_INVALID_KDF_PARAM`` -- ``iterations < 1`` or ``dklen < 1``
|
||||
"""
|
||||
if hash_name == "sha256":
|
||||
hmac_func = hmac_sha256
|
||||
h_len = 32
|
||||
elif hash_name == "sha512":
|
||||
hmac_func = hmac_sha512
|
||||
h_len = 64
|
||||
else:
|
||||
return err(PPYC_ERR_INVALID_ALGO,
|
||||
f"PBKDF2 does not support hash algorithm {hash_name!r}",
|
||||
"use 'sha256' or 'sha512'")
|
||||
|
||||
if iterations < 1:
|
||||
return err(PPYC_ERR_INVALID_KDF_PARAM,
|
||||
f"PBKDF2 iteration count iterations must be >= 1, got {iterations}",
|
||||
"a value >= 100000 is recommended to resist brute force")
|
||||
if dklen < 1:
|
||||
return err(PPYC_ERR_INVALID_KDF_PARAM,
|
||||
f"PBKDF2 output length dklen must be >= 1, got {dklen}",
|
||||
"pass a desired key length >= 1")
|
||||
|
||||
l = (dklen + h_len - 1) // h_len
|
||||
dk = bytearray()
|
||||
for i in range(1, l + 1):
|
||||
u = hmac_func(password, salt + struct.pack(">I", i))
|
||||
t = bytearray(u)
|
||||
for _ in range(iterations - 1):
|
||||
u = hmac_func(password, u)
|
||||
for j in range(h_len):
|
||||
t[j] ^= u[j]
|
||||
dk.extend(t)
|
||||
return bytes(dk[:dklen])
|
||||
|
||||
|
||||
# ---- scrypt is defined later in this file (single implementation, the correct RFC 7914 version) ----
|
||||
|
||||
|
||||
def hkdf_extract(salt: bytes, ikm: bytes, hash_name: str = "sha256"):
|
||||
"""HKDF-Extract (RFC 5869 section 2.2): ``PRK = HMAC(salt, ikm)``.
|
||||
|
||||
Returns
|
||||
----
|
||||
bytes
|
||||
The pseudorandom key PRK (length equal to the selected hash output length).
|
||||
tuple
|
||||
Returns ``(PPYC_ERR_INVALID_ALGO, reason, suggestion)`` when ``hash_name`` is invalid.
|
||||
"""
|
||||
if hash_name == "sha256":
|
||||
hmac_func = hmac_sha256
|
||||
h_len = 32
|
||||
elif hash_name == "sha512":
|
||||
hmac_func = hmac_sha512
|
||||
h_len = 64
|
||||
else:
|
||||
return err(PPYC_ERR_INVALID_ALGO,
|
||||
f"HKDF does not support hash algorithm {hash_name!r}",
|
||||
"use 'sha256' or 'sha512'")
|
||||
if not salt:
|
||||
salt = b"\x00" * h_len
|
||||
return hmac_func(salt, ikm)
|
||||
|
||||
|
||||
def hkdf_expand(prk: bytes, info: bytes, length: int, hash_name: str = "sha256"):
|
||||
"""HKDF-Expand (RFC 5869 section 2.3): derive an OKM of length ``length`` from the PRK.
|
||||
|
||||
Returns
|
||||
----
|
||||
bytes
|
||||
The output keying material OKM of length ``length``.
|
||||
tuple
|
||||
On error returns a 3-tuple:
|
||||
|
||||
* ``PPYC_ERR_INVALID_ALGO`` -- ``hash_name`` is invalid
|
||||
* ``PPYC_ERR_INVALID_ARG`` -- ``prk`` is empty
|
||||
* ``PPYC_ERR_INVALID_KDF_PARAM`` -- ``length < 1`` or ``length > 255*h_len``
|
||||
"""
|
||||
if hash_name == "sha256":
|
||||
hmac_func = hmac_sha256
|
||||
h_len = 32
|
||||
elif hash_name == "sha512":
|
||||
hmac_func = hmac_sha512
|
||||
h_len = 64
|
||||
else:
|
||||
return err(PPYC_ERR_INVALID_ALGO,
|
||||
f"HKDF does not support hash algorithm {hash_name!r}",
|
||||
"use 'sha256' or 'sha512'")
|
||||
if not prk:
|
||||
return err(PPYC_ERR_INVALID_ARG,
|
||||
"the HKDF-Expand PRK must not be empty",
|
||||
"obtain a non-empty PRK via hkdf_extract first")
|
||||
if length < 1:
|
||||
return err(PPYC_ERR_INVALID_KDF_PARAM,
|
||||
f"HKDF output length length must be >= 1, got {length}",
|
||||
"pass a desired length >= 1")
|
||||
if length > 255 * h_len:
|
||||
return err(PPYC_ERR_INVALID_KDF_PARAM,
|
||||
f"HKDF output length too large: length={length} > 255*{h_len}",
|
||||
f"the HKDF single-call output limit is {255 * h_len} bytes")
|
||||
|
||||
n = (length + h_len - 1) // h_len
|
||||
okm = b""
|
||||
t = b""
|
||||
for i in range(1, n + 1):
|
||||
t = hmac_func(prk, t + info + bytes([i]))
|
||||
okm += t
|
||||
return okm[:length]
|
||||
|
||||
|
||||
def hkdf(ikm: bytes, salt: bytes = b"", info: bytes = b"",
|
||||
length: int = 32, hash_name: str = "sha256"):
|
||||
"""HKDF (RFC 5869) = Extract followed by Expand.
|
||||
|
||||
Returns
|
||||
----
|
||||
bytes
|
||||
Output keying material of length ``length``.
|
||||
tuple
|
||||
Propagates the error tuple of :func:`hkdf_extract` / :func:`hkdf_expand`
|
||||
(``PPYC_ERR_INVALID_ALGO`` / ``PPYC_ERR_INVALID_ARG`` /
|
||||
``PPYC_ERR_INVALID_KDF_PARAM``).
|
||||
"""
|
||||
prk = hkdf_extract(salt, ikm, hash_name)
|
||||
if is_err(prk):
|
||||
return prk
|
||||
okm = hkdf_expand(prk, info, length, hash_name)
|
||||
if is_err(okm):
|
||||
return okm
|
||||
return okm
|
||||
|
||||
|
||||
# ============ Fixed scrypt + GHASH ============
|
||||
|
||||
def _salsa20_8_core(block_in):
|
||||
"""Salsa20/8 core permutation (internal hot path).
|
||||
|
||||
The ``block_in`` argument must be exactly 64 bytes; this is an internal invariant.
|
||||
|
||||
Returns
|
||||
----
|
||||
bytes
|
||||
64-byte permutation result.
|
||||
"""
|
||||
if len(block_in) != 64:
|
||||
# Broken internal invariant (a bug in this library) -> fatal error
|
||||
raise PPYC_ERR(PPYC_ERR_INTERNAL,
|
||||
f"_salsa20_8_core requires a 64-byte input, got {len(block_in)}",
|
||||
"this is an internal library error, please file an issue")
|
||||
M = MASK32
|
||||
x = list(struct.unpack("<16I", block_in))
|
||||
x0, x1, x2, x3 = x[0], x[1], x[2], x[3]
|
||||
x4, x5, x6, x7 = x[4], x[5], x[6], x[7]
|
||||
x8, x9, x10, x11 = x[8], x[9], x[10], x[11]
|
||||
x12, x13, x14, x15 = x[12], x[13], x[14], x[15]
|
||||
o0, o1, o2, o3 = x0, x1, x2, x3
|
||||
o4, o5, o6, o7 = x4, x5, x6, x7
|
||||
o8, o9, o10, o11 = x8, x9, x10, x11
|
||||
o12, o13, o14, o15 = x12, x13, x14, x15
|
||||
|
||||
for _ in range(4):
|
||||
t = (x0 + x12) & M; x4 = (x4 ^ (((t << 7) | (t >> 25)) & M)) & M
|
||||
t = (x4 + x0) & M; x8 = (x8 ^ (((t << 9) | (t >> 23)) & M)) & M
|
||||
t = (x8 + x4) & M; x12 = (x12 ^ (((t << 13) | (t >> 19)) & M)) & M
|
||||
t = (x12 + x8) & M; x0 = (x0 ^ (((t << 18) | (t >> 14)) & M)) & M
|
||||
t = (x5 + x1) & M; x9 = (x9 ^ (((t << 7) | (t >> 25)) & M)) & M
|
||||
t = (x9 + x5) & M; x13 = (x13 ^ (((t << 9) | (t >> 23)) & M)) & M
|
||||
t = (x13 + x9) & M; x1 = (x1 ^ (((t << 13) | (t >> 19)) & M)) & M
|
||||
t = (x1 + x13) & M; x5 = (x5 ^ (((t << 18) | (t >> 14)) & M)) & M
|
||||
t = (x10 + x6) & M; x14 = (x14 ^ (((t << 7) | (t >> 25)) & M)) & M
|
||||
t = (x14 + x10) & M; x2 = (x2 ^ (((t << 9) | (t >> 23)) & M)) & M
|
||||
t = (x2 + x14) & M; x6 = (x6 ^ (((t << 13) | (t >> 19)) & M)) & M
|
||||
t = (x6 + x2) & M; x10 = (x10 ^ (((t << 18) | (t >> 14)) & M)) & M
|
||||
t = (x15 + x11) & M; x3 = (x3 ^ (((t << 7) | (t >> 25)) & M)) & M
|
||||
t = (x3 + x15) & M; x7 = (x7 ^ (((t << 9) | (t >> 23)) & M)) & M
|
||||
t = (x7 + x3) & M; x11 = (x11 ^ (((t << 13) | (t >> 19)) & M)) & M
|
||||
t = (x11 + x7) & M; x15 = (x15 ^ (((t << 18) | (t >> 14)) & M)) & M
|
||||
|
||||
t = (x0 + x3) & M; x1 = (x1 ^ (((t << 7) | (t >> 25)) & M)) & M
|
||||
t = (x1 + x0) & M; x2 = (x2 ^ (((t << 9) | (t >> 23)) & M)) & M
|
||||
t = (x2 + x1) & M; x3 = (x3 ^ (((t << 13) | (t >> 19)) & M)) & M
|
||||
t = (x3 + x2) & M; x0 = (x0 ^ (((t << 18) | (t >> 14)) & M)) & M
|
||||
t = (x5 + x4) & M; x6 = (x6 ^ (((t << 7) | (t >> 25)) & M)) & M
|
||||
t = (x6 + x5) & M; x7 = (x7 ^ (((t << 9) | (t >> 23)) & M)) & M
|
||||
t = (x7 + x6) & M; x4 = (x4 ^ (((t << 13) | (t >> 19)) & M)) & M
|
||||
t = (x4 + x7) & M; x5 = (x5 ^ (((t << 18) | (t >> 14)) & M)) & M
|
||||
t = (x10 + x9) & M; x11 = (x11 ^ (((t << 7) | (t >> 25)) & M)) & M
|
||||
t = (x11 + x10) & M; x8 = (x8 ^ (((t << 9) | (t >> 23)) & M)) & M
|
||||
t = (x8 + x11) & M; x9 = (x9 ^ (((t << 13) | (t >> 19)) & M)) & M
|
||||
t = (x9 + x8) & M; x10 = (x10 ^ (((t << 18) | (t >> 14)) & M)) & M
|
||||
t = (x15 + x14) & M; x12 = (x12 ^ (((t << 7) | (t >> 25)) & M)) & M
|
||||
t = (x12 + x15) & M; x13 = (x13 ^ (((t << 9) | (t >> 23)) & M)) & M
|
||||
t = (x13 + x12) & M; x14 = (x14 ^ (((t << 13) | (t >> 19)) & M)) & M
|
||||
t = (x14 + x13) & M; x15 = (x15 ^ (((t << 18) | (t >> 14)) & M)) & M
|
||||
|
||||
return struct.pack("<16I",
|
||||
(x0 + o0) & M, (x1 + o1) & M, (x2 + o2) & M, (x3 + o3) & M,
|
||||
(x4 + o4) & M, (x5 + o5) & M, (x6 + o6) & M, (x7 + o7) & M,
|
||||
(x8 + o8) & M, (x9 + o9) & M, (x10 + o10) & M, (x11 + o11) & M,
|
||||
(x12 + o12) & M, (x13 + o13) & M, (x14 + o14) & M, (x15 + o15) & M)
|
||||
|
||||
|
||||
def _blockmix_salsa8(B, r):
|
||||
# RFC 7914 BlockMix:
|
||||
# X = B[2r-1]
|
||||
# for i = 0 .. 2r-1: X = Salsa20/8(X xor B[i]); Y[i] = X
|
||||
# BlockMix = (Y[0], Y[2], ..., Y[2r-2], Y[1], Y[3], ..., Y[2r-1])
|
||||
# Key point: the chained XOR must advance in the order i=0,1,...,2r-1, and only then is the even/odd permutation applied to the output.
|
||||
X = bytes(B[(2 * r - 1) * 64: 2 * r * 64])
|
||||
Y = [None] * (2 * r)
|
||||
for i in range(2 * r):
|
||||
X = _salsa20_8_core(bytes(a ^ b for a, b in zip(X, B[i*64:(i+1)*64])))
|
||||
Y[i] = X
|
||||
return b"".join(Y[0::2] + Y[1::2])
|
||||
|
||||
|
||||
def _integerify(B, r):
|
||||
# RFC 7914: Integerify(B) = interpret B[2r-1] as a little-endian integer.
|
||||
# mod N (N <= 2^32) depends only on the lowest 64 bits of that block = its first 8 bytes.
|
||||
return struct.unpack("<Q", B[(2*r-1)*64:(2*r-1)*64 + 8])[0]
|
||||
|
||||
|
||||
def _romix(B, N, r):
|
||||
bs = 128 * r
|
||||
V = bytearray(N * bs)
|
||||
X = bytes(B)
|
||||
for i in range(N):
|
||||
V[i*bs:(i+1)*bs] = X
|
||||
X = _blockmix_salsa8(X, r)
|
||||
for i in range(N):
|
||||
j = _integerify(X, r) % N
|
||||
X = _blockmix_salsa8(bytes(a ^ b for a, b in zip(X, V[j*bs:(j+1)*bs])), r)
|
||||
return X
|
||||
|
||||
|
||||
def scrypt(password, salt, N=2**12, r=8, p=1, dklen=32):
|
||||
"""scrypt key derivation (RFC 7914).
|
||||
|
||||
Returns
|
||||
----
|
||||
bytes
|
||||
A derived key of length ``dklen``.
|
||||
tuple
|
||||
Invalid parameters return ``(PPYC_ERR_INVALID_KDF_PARAM, reason, suggestion)``.
|
||||
Triggered by: ``N`` not a power of two or <= 1 / ``r < 1`` / ``p < 1`` / ``dklen < 1``.
|
||||
"""
|
||||
if N <= 1 or (N & (N - 1)) != 0:
|
||||
return err(PPYC_ERR_INVALID_KDF_PARAM,
|
||||
f"scrypt parameter N must be a power of two greater than 1, got {N}",
|
||||
"N=16384 (2^14) is common")
|
||||
if r < 1 or p < 1:
|
||||
return err(PPYC_ERR_INVALID_KDF_PARAM,
|
||||
f"scrypt parameters r and p must be >= 1 (r={r}, p={p})",
|
||||
"r=8, p=1 are common")
|
||||
if dklen < 1:
|
||||
return err(PPYC_ERR_INVALID_KDF_PARAM,
|
||||
f"scrypt output length dklen must be >= 1, got {dklen}",
|
||||
"dklen=32 or 64 are common")
|
||||
bs = 128 * r
|
||||
B = pbkdf2_hmac(password, salt, 1, p * bs, "sha256")
|
||||
if is_err(B):
|
||||
return B
|
||||
B_out = bytearray(p * bs)
|
||||
for i in range(p):
|
||||
B_out[i*bs:(i+1)*bs] = _romix(B[i*bs:(i+1)*bs], N, r)
|
||||
res = pbkdf2_hmac(password, bytes(B_out), 1, dklen, "sha256")
|
||||
if is_err(res):
|
||||
return res
|
||||
return res
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,169 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""purepycrypto.parallel
|
||||
========================================
|
||||
purepycrypto - Pure-Python cryptography library (zero dependencies)
|
||||
Multiprocessing pool reuse and SharedMemory zero-copy I/O (automatically falls back to serial when unavailable).
|
||||
|
||||
Error system
|
||||
--------
|
||||
* **Multiprocessing unavailable** (``_HAS_MP`` is ``False``) is an **expected normal condition**:
|
||||
:func:`_get_pool` returns ``None`` and the caller falls back to a serial implementation. The corresponding
|
||||
unified error code is :data:`PPYC_ERR_NO_MULTIPROCESS` (semantic marker only, no exception raised).
|
||||
* Fatal environment problems such as **pool creation failure** -> raise :class:`PPYC_ERR`
|
||||
(error code ``PPYC_ERR_NO_MULTIPROCESS``).
|
||||
* :func:`_alloc_shm` allocation failure -> returns a 3-tuple
|
||||
``(PPYC_ERR_NO_MULTIPROCESS, reason, suggestion)``.
|
||||
* :func:`_free_shm` / :func:`_cleanup_pool` are release-type operations that tolerate failure and
|
||||
return :data:`OK_TUPLE`.
|
||||
"""
|
||||
|
||||
import atexit
|
||||
|
||||
from ._ppyc_error import (
|
||||
PPYC_ERR, err, is_err, OK_TUPLE,
|
||||
PPYC_ERR_NO_MULTIPROCESS,
|
||||
)
|
||||
|
||||
try:
|
||||
import multiprocessing as mp
|
||||
from multiprocessing import Pool, cpu_count
|
||||
from multiprocessing import shared_memory
|
||||
_HAS_MP = True
|
||||
except (ImportError, ModuleNotFoundError):
|
||||
mp = None
|
||||
Pool = None
|
||||
cpu_count = lambda: 1
|
||||
shared_memory = None
|
||||
_HAS_MP = False
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 1. Multiprocessing pool reuse
|
||||
# ============================================================
|
||||
|
||||
_pool = None
|
||||
_pool_size = 0
|
||||
_pool_key = None
|
||||
|
||||
|
||||
def _get_pool(n: int):
|
||||
"""Get (recreating if necessary) a reusable process pool of size ``n``.
|
||||
|
||||
Contract
|
||||
----
|
||||
* Returns ``Pool`` : parallelism works, the caller can use it directly.
|
||||
* Returns ``None`` : **multiprocessing unavailable** (``_HAS_MP`` is ``False``), semantically equivalent to
|
||||
the error code :data:`PPYC_ERR_NO_MULTIPROCESS`; the caller should fall back to a serial implementation
|
||||
(this is a designed normal path, not a crash).
|
||||
* Raises :class:`PPYC_ERR` : pool creation failed (environment problem, error code
|
||||
``PPYC_ERR_NO_MULTIPROCESS``).
|
||||
|
||||
Parameters
|
||||
----
|
||||
n : int
|
||||
Desired number of worker processes.
|
||||
|
||||
Returns
|
||||
----
|
||||
multiprocessing.pool.Pool | None
|
||||
See the contract above.
|
||||
"""
|
||||
global _pool, _pool_size, _pool_key
|
||||
if not _HAS_MP:
|
||||
return None
|
||||
key = (n,)
|
||||
if _pool is None or _pool_size != n or _pool_key != key:
|
||||
if _pool is not None:
|
||||
try:
|
||||
_pool.terminate()
|
||||
_pool.join()
|
||||
except Exception:
|
||||
pass
|
||||
_pool = None
|
||||
try:
|
||||
_pool = Pool(n)
|
||||
except (OSError, RuntimeError, ValueError) as exc:
|
||||
_pool = None
|
||||
_pool_size = 0
|
||||
_pool_key = None
|
||||
# The environment cannot create a pool -> fatal error (PPYC_ERR)
|
||||
raise PPYC_ERR(
|
||||
PPYC_ERR_NO_MULTIPROCESS,
|
||||
f"cannot create a process pool of size {n}: {exc}",
|
||||
"check the system process/memory limits, or explicitly disable multiprocessing parallelism",
|
||||
) from exc
|
||||
_pool_size = n
|
||||
_pool_key = key
|
||||
return _pool
|
||||
|
||||
|
||||
def _cleanup_pool():
|
||||
"""Release the global process pool (registered with ``atexit``).
|
||||
|
||||
Returns
|
||||
----
|
||||
tuple
|
||||
Always returns the success tuple :data:`OK_TUPLE` (release failures are silently ignored).
|
||||
"""
|
||||
global _pool
|
||||
if _pool is not None:
|
||||
try:
|
||||
_pool.terminate()
|
||||
_pool.join()
|
||||
except Exception:
|
||||
pass
|
||||
_pool = None
|
||||
return OK_TUPLE
|
||||
|
||||
|
||||
atexit.register(_cleanup_pool)
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 2. SharedMemory zero-copy I/O
|
||||
# ============================================================
|
||||
|
||||
def _alloc_shm(data: bytes):
|
||||
"""Allocate space in shared memory and write ``data`` into it.
|
||||
|
||||
Returns
|
||||
----
|
||||
multiprocessing.shared_memory.SharedMemory
|
||||
The successfully created shared-memory object (containing ``data``).
|
||||
tuple
|
||||
When multiprocessing / shared memory is unavailable or allocation fails, returns
|
||||
``(PPYC_ERR_NO_MULTIPROCESS, reason, suggestion)``.
|
||||
"""
|
||||
if not _HAS_MP or shared_memory is None:
|
||||
return err(PPYC_ERR_NO_MULTIPROCESS,
|
||||
"the current environment does not support multiprocessing.SharedMemory",
|
||||
"fall back to a serial implementation, or use an ordinary memory copy instead")
|
||||
try:
|
||||
shm = shared_memory.SharedMemory(create=True, size=len(data))
|
||||
except Exception as exc:
|
||||
return err(PPYC_ERR_NO_MULTIPROCESS,
|
||||
f"shared memory allocation failed: {exc}",
|
||||
"check the system shared memory / temp directory permissions, or fall back to a serial implementation")
|
||||
shm.buf[:len(data)] = data
|
||||
return shm
|
||||
|
||||
|
||||
def _free_shm(shm):
|
||||
"""Release shared memory (tolerates ``None`` and error tuples).
|
||||
|
||||
Returns
|
||||
----
|
||||
tuple
|
||||
Always returns the success tuple :data:`OK_TUPLE`.
|
||||
"""
|
||||
if shm is None or is_err(shm):
|
||||
return OK_TUPLE
|
||||
try:
|
||||
shm.close()
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
shm.unlink()
|
||||
except Exception:
|
||||
pass
|
||||
return OK_TUPLE
|
||||
@@ -0,0 +1,606 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
purepycrypto.rand
|
||||
=================
|
||||
purepycrypto - Pure-Python cryptography library (zero third-party dependencies)
|
||||
Cryptographically secure random number (CSPRNG) toolkit.
|
||||
|
||||
Security statement
|
||||
--------
|
||||
This module **uses only the CSPRNG provided by the operating system**:
|
||||
|
||||
* :func:`os.urandom` -- reads the kernel secure entropy source directly
|
||||
(Linux ``getrandom`` / Windows ``BCryptGenRandom`` /
|
||||
macOS ``SecRandomCopyBytes``, etc.);
|
||||
* :mod:`secrets` -- the standard library safe wrapper around ``os.urandom`` (equivalent semantics).
|
||||
|
||||
The standard-library :mod:`random` module (Mersenne Twister, deterministic and predictable) **must never** be used to
|
||||
back this module; this module **does not import and does not use** the ``random`` module (see the test
|
||||
``test_no_insecure_random_import``). This module is therefore suitable for all security-sensitive scenarios such as
|
||||
generating keys, nonces, salts, initialization vectors, session tokens and one-time passwords.
|
||||
|
||||
Unbiasedness
|
||||
------
|
||||
:func:`random_int` / :func:`random_below` / :func:`random_bits` all use
|
||||
**rejection sampling**: enough bits are drawn first and accepted only if they fall in the valid
|
||||
range, otherwise they are redrawn. This completely eliminates the bias introduced by the modulo (``% n``)
|
||||
and gives a strictly uniform distribution over the target range.
|
||||
|
||||
Error system
|
||||
--------
|
||||
Follows the library-wide unified error contract (see :mod:`._ppyc_error`):
|
||||
|
||||
* **Non-fatal errors** (invalid argument / length out of range, etc.) -> return a 3-tuple
|
||||
``(error_code, error_message, suggestion)``;
|
||||
* **Fatal errors** (fatal problems such as the system entropy source being unavailable) -> raise :class:`PPYC_ERR`;
|
||||
* **Success** -> return the business value (``bytes`` / ``int`` / ``str`` / ``list``, etc.).
|
||||
|
||||
Examples
|
||||
----
|
||||
from purepycrypto.rand import random_bytes, random_int, token_hex, random_password
|
||||
|
||||
key = random_bytes(32) # 32-byte key
|
||||
dice = random_int(1, 6) # fair die (no modulo bias)
|
||||
tok = token_hex(16) # 32-character hexadecimal token
|
||||
passwd = random_password(20) # 20-character strong password
|
||||
"""
|
||||
|
||||
import base64
|
||||
import os
|
||||
import uuid as _uuid
|
||||
|
||||
from ._ppyc_error import (
|
||||
PPYC_ERR,
|
||||
err,
|
||||
PPYC_ERR_INVALID_ARG,
|
||||
PPYC_ERR_INVALID_TYPE,
|
||||
PPYC_ERR_INVALID_LENGTH,
|
||||
PPYC_ERR_OUT_OF_RANGE,
|
||||
PPYC_ERR_ENV,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
# Basics
|
||||
"random_bytes", "random_int", "random_below",
|
||||
"random_bit", "random_bits",
|
||||
# Tokens / strings
|
||||
"token_bytes", "token_hex", "token_urlsafe",
|
||||
"random_string", "random_password",
|
||||
# Distributed / uniqueness
|
||||
"random_uuid4", "random_choice", "random_sample",
|
||||
# Compatibility aliases
|
||||
"randbytes_alias",
|
||||
]
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# Internal helpers
|
||||
# ======================================================================
|
||||
|
||||
def _entropy(nbytes):
|
||||
"""Read ``nbytes`` secure random bytes from the OS CSPRNG.
|
||||
|
||||
Parameters
|
||||
----
|
||||
nbytes : int
|
||||
Number of bytes required (the caller guarantees this is a non-negative integer).
|
||||
|
||||
Returns
|
||||
----
|
||||
bytes
|
||||
``nbytes`` secure random bytes.
|
||||
|
||||
Raises
|
||||
----
|
||||
PPYC_ERR
|
||||
Raised when the system secure entropy source is unavailable (``os.urandom`` raises ``OSError`` /
|
||||
``NotImplementedError``); this is a **fatal error**, because the program can no longer
|
||||
generate randomness securely and must terminate rather than degrade to an insecure entropy source.
|
||||
"""
|
||||
try:
|
||||
return os.urandom(nbytes)
|
||||
except (OSError, NotImplementedError) as exc: # pragma: no cover - environment dependent
|
||||
raise PPYC_ERR(
|
||||
PPYC_ERR_ENV,
|
||||
f"the system secure entropy source is unavailable (os.urandom failed): {exc!r}",
|
||||
"check that the runtime environment supports os.urandom and the system entropy pool is intact; "
|
||||
"never switch to a non-cryptographic entropy source such as the random module",
|
||||
)
|
||||
|
||||
|
||||
def _is_bad_int(x):
|
||||
"""Determine whether ``x`` is "not an integer or bool" (bool is a subclass of int and must be excluded explicitly)."""
|
||||
return isinstance(x, bool) or not isinstance(x, int)
|
||||
|
||||
|
||||
def _check_nbytes(nbytes, name="nbytes"):
|
||||
"""Validate an optional byte-count argument.
|
||||
|
||||
Returns
|
||||
----
|
||||
None
|
||||
Validation passed.
|
||||
tuple
|
||||
``(PPYC_ERR_INVALID_TYPE | PPYC_ERR_INVALID_LENGTH, reason, suggestion)``.
|
||||
"""
|
||||
if nbytes is None:
|
||||
return None
|
||||
if _is_bad_int(nbytes):
|
||||
return err(PPYC_ERR_INVALID_TYPE,
|
||||
f"{name} must be an integer, got {type(nbytes).__name__}",
|
||||
"pass a non-negative integer, or leave it empty to use the default length")
|
||||
if nbytes < 0:
|
||||
return err(PPYC_ERR_INVALID_LENGTH,
|
||||
f"{name} cannot be negative: {name}={nbytes}",
|
||||
"pass a non-negative integer (0 means an empty byte string)")
|
||||
return None
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# 1. Basic random
|
||||
# ======================================================================
|
||||
|
||||
def random_bytes(n):
|
||||
"""Return ``n`` cryptographically secure random bytes.
|
||||
|
||||
Parameters
|
||||
----
|
||||
n : int
|
||||
Number of bytes (``n == 0`` returns an empty ``bytes``).
|
||||
|
||||
Returns
|
||||
----
|
||||
bytes
|
||||
``n`` secure random bytes.
|
||||
tuple
|
||||
``n`` not an integer -> ``(PPYC_ERR_INVALID_TYPE, ...)``;
|
||||
``n < 0`` -> ``(PPYC_ERR_INVALID_LENGTH, ...)``.
|
||||
"""
|
||||
if _is_bad_int(n):
|
||||
return err(PPYC_ERR_INVALID_TYPE,
|
||||
f"the random byte count must be an integer, got {type(n).__name__}",
|
||||
"pass a non-negative integer n")
|
||||
if n < 0:
|
||||
return err(PPYC_ERR_INVALID_LENGTH,
|
||||
f"the random byte count cannot be negative: n={n}",
|
||||
"pass a non-negative integer n (n=0 returns b'')")
|
||||
return _entropy(n)
|
||||
|
||||
|
||||
def random_below(n):
|
||||
"""Return a uniformly random integer in ``[0, n)`` (rejection sampling, no modulo bias).
|
||||
|
||||
Parameters
|
||||
----
|
||||
n : int
|
||||
Exclusive upper bound, must be ``>= 1``.
|
||||
|
||||
Returns
|
||||
----
|
||||
int
|
||||
A uniformly random integer in ``[0, n)`` (``n == 1`` always gives 0).
|
||||
tuple
|
||||
``n`` not an integer -> ``(PPYC_ERR_INVALID_TYPE, ...)``;
|
||||
``n < 1`` -> ``(PPYC_ERR_OUT_OF_RANGE, ...)``.
|
||||
"""
|
||||
if _is_bad_int(n):
|
||||
return err(PPYC_ERR_INVALID_TYPE,
|
||||
f"the upper bound must be an integer, got {type(n).__name__}",
|
||||
"pass a positive integer n (n >= 1)")
|
||||
if n < 1:
|
||||
return err(PPYC_ERR_OUT_OF_RANGE,
|
||||
f"the upper bound must be a positive integer: n={n}",
|
||||
"pass an integer with n >= 1")
|
||||
if n == 1:
|
||||
return 0
|
||||
# Draw exactly enough bits to represent [0, n): the highest bit of n-1 gives the required bit count.
|
||||
bits = (n - 1).bit_length()
|
||||
nbytes = (bits + 7) // 8
|
||||
mask = (1 << bits) - 1
|
||||
# Rejection sampling: acceptance probability >= 1/2, expected iterations < 2.
|
||||
while True:
|
||||
raw = int.from_bytes(_entropy(nbytes), "big") & mask
|
||||
if raw < n:
|
||||
return raw
|
||||
|
||||
|
||||
def random_int(a, b):
|
||||
"""Return a uniformly random integer in the closed interval ``[a, b]`` (rejection sampling, no modulo bias).
|
||||
|
||||
Parameters
|
||||
----
|
||||
a : int
|
||||
Lower bound (inclusive).
|
||||
b : int
|
||||
Upper bound (inclusive).
|
||||
|
||||
Returns
|
||||
----
|
||||
int
|
||||
A uniformly random integer in ``[a, b]`` (always ``a`` when ``a == b``).
|
||||
tuple
|
||||
``a`` / ``b`` not an integer -> ``(PPYC_ERR_INVALID_TYPE, ...)``;
|
||||
``a > b`` -> ``(PPYC_ERR_INVALID_ARG, ...)``.
|
||||
"""
|
||||
if _is_bad_int(a) or _is_bad_int(b):
|
||||
return err(PPYC_ERR_INVALID_TYPE,
|
||||
f"the interval endpoints must be integers, got a={type(a).__name__}, b={type(b).__name__}",
|
||||
"pass two integers with a <= b")
|
||||
if a > b:
|
||||
return err(PPYC_ERR_INVALID_ARG,
|
||||
f"invalid random range: lower bound a={a} is greater than upper bound b={b}",
|
||||
"make sure random_int(a, b) is called with a <= b")
|
||||
if a == b:
|
||||
return a
|
||||
span = b - a + 1 # >= 2, random_below always returns an int
|
||||
return a + random_below(span)
|
||||
|
||||
|
||||
def random_bit():
|
||||
"""Return a single random bit.
|
||||
|
||||
Returns
|
||||
----
|
||||
int
|
||||
``0`` or ``1`` (equiprobable).
|
||||
"""
|
||||
return random_below(2)
|
||||
|
||||
|
||||
def random_bits(k):
|
||||
"""Return a uniformly random ``k``-bit integer (value range ``[0, 2**k)``).
|
||||
|
||||
Parameters
|
||||
----
|
||||
k : int
|
||||
Number of bits (``k == 0`` returns 0).
|
||||
|
||||
Returns
|
||||
----
|
||||
int
|
||||
A uniformly random integer in ``[0, 2**k - 1]``.
|
||||
tuple
|
||||
``k`` not an integer -> ``(PPYC_ERR_INVALID_TYPE, ...)``;
|
||||
``k < 0`` -> ``(PPYC_ERR_INVALID_LENGTH, ...)``.
|
||||
"""
|
||||
if _is_bad_int(k):
|
||||
return err(PPYC_ERR_INVALID_TYPE,
|
||||
f"the bit count must be an integer, got {type(k).__name__}",
|
||||
"pass a non-negative integer k")
|
||||
if k < 0:
|
||||
return err(PPYC_ERR_INVALID_LENGTH,
|
||||
f"the bit count cannot be negative: k={k}",
|
||||
"pass a non-negative integer k (k=0 returns 0)")
|
||||
if k == 0:
|
||||
return 0
|
||||
nbytes = (k + 7) // 8
|
||||
return int.from_bytes(_entropy(nbytes), "big") >> (nbytes * 8 - k)
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# 2. Secure tokens / strings
|
||||
# ======================================================================
|
||||
|
||||
#: Default byte count for ``secrets``-style tokens
|
||||
_DEFAULT_TOKEN_BYTES = 32
|
||||
|
||||
|
||||
def token_bytes(nbytes=None):
|
||||
"""Generate a secure random byte string (``secrets.token_bytes`` semantics).
|
||||
|
||||
Parameters
|
||||
----
|
||||
nbytes : int | None
|
||||
Byte count; when ``None``, the default of 32 is used.
|
||||
|
||||
Returns
|
||||
----
|
||||
bytes
|
||||
``nbytes`` secure random bytes.
|
||||
tuple
|
||||
``nbytes`` not an integer / negative -> ``(PPYC_ERR_INVALID_TYPE | PPYC_ERR_INVALID_LENGTH, ...)``.
|
||||
"""
|
||||
if nbytes is None:
|
||||
nbytes = _DEFAULT_TOKEN_BYTES
|
||||
chk = _check_nbytes(nbytes)
|
||||
if chk is not None:
|
||||
return chk
|
||||
return _entropy(nbytes)
|
||||
|
||||
|
||||
def token_hex(nbytes=None):
|
||||
"""Generate a hexadecimal secure token (``secrets.token_hex`` semantics).
|
||||
|
||||
Parameters
|
||||
----
|
||||
nbytes : int | None
|
||||
Number of raw random bytes; when ``None``, the default of 32 is used
|
||||
(i.e. a 64-character hexadecimal string).
|
||||
|
||||
Returns
|
||||
----
|
||||
str
|
||||
A hexadecimal string of length ``2 * nbytes`` containing only ``[0-9a-f]``.
|
||||
tuple
|
||||
``nbytes`` not an integer / negative -> ``(PPYC_ERR_INVALID_TYPE | PPYC_ERR_INVALID_LENGTH, ...)``.
|
||||
"""
|
||||
if nbytes is None:
|
||||
nbytes = _DEFAULT_TOKEN_BYTES
|
||||
chk = _check_nbytes(nbytes)
|
||||
if chk is not None:
|
||||
return chk
|
||||
return _entropy(nbytes).hex()
|
||||
|
||||
|
||||
def token_urlsafe(nbytes=None):
|
||||
"""Generate a URL-safe Base64 secure token (``secrets.token_urlsafe`` semantics).
|
||||
|
||||
Uses :func:`base64.urlsafe_b64encode` and strips the trailing ``=`` padding, so the result contains only
|
||||
``[A-Za-z0-9-_]`` and is safe for URLs / file names.
|
||||
|
||||
Parameters
|
||||
----
|
||||
nbytes : int | None
|
||||
Number of raw random bytes; when ``None``, the default of 32 is used.
|
||||
|
||||
Returns
|
||||
----
|
||||
str
|
||||
A URL-safe Base64 string (no ``=`` padding).
|
||||
tuple
|
||||
``nbytes`` not an integer / negative -> ``(PPYC_ERR_INVALID_TYPE | PPYC_ERR_INVALID_LENGTH, ...)``.
|
||||
"""
|
||||
if nbytes is None:
|
||||
nbytes = _DEFAULT_TOKEN_BYTES
|
||||
chk = _check_nbytes(nbytes)
|
||||
if chk is not None:
|
||||
return chk
|
||||
raw = _entropy(nbytes)
|
||||
return base64.urlsafe_b64encode(raw).rstrip(b"=").decode("ascii")
|
||||
|
||||
|
||||
def random_string(length, alphabet):
|
||||
"""Generate a string of the given length by uniformly choosing characters from a custom alphabet.
|
||||
|
||||
Each character index is chosen via :func:`random_below`, with no modulo bias.
|
||||
|
||||
Parameters
|
||||
----
|
||||
length : int
|
||||
Target string length (``0`` returns an empty string).
|
||||
alphabet : str
|
||||
Character set, must be a non-empty string.
|
||||
|
||||
Returns
|
||||
----
|
||||
str
|
||||
A random string of length ``length`` whose characters are all drawn from ``alphabet``.
|
||||
tuple
|
||||
``length`` not an integer / negative -> ``(PPYC_ERR_INVALID_TYPE | PPYC_ERR_INVALID_LENGTH, ...)``;
|
||||
``alphabet`` not a string or empty -> ``(PPYC_ERR_INVALID_ARG, ...)``.
|
||||
"""
|
||||
if _is_bad_int(length):
|
||||
return err(PPYC_ERR_INVALID_TYPE,
|
||||
f"the string length must be an integer, got {type(length).__name__}",
|
||||
"pass a non-negative integer length")
|
||||
if length < 0:
|
||||
return err(PPYC_ERR_INVALID_LENGTH,
|
||||
f"the string length cannot be negative: length={length}",
|
||||
"pass a non-negative integer length (0 returns '')")
|
||||
if not isinstance(alphabet, str):
|
||||
return err(PPYC_ERR_INVALID_ARG,
|
||||
f"the alphabet must be a string, got {type(alphabet).__name__}",
|
||||
"pass a non-empty string, e.g. 'abcdef0123456789'")
|
||||
if len(alphabet) == 0:
|
||||
return err(PPYC_ERR_INVALID_ARG,
|
||||
"the alphabet must not be empty",
|
||||
"pass a string containing at least one character")
|
||||
if length == 0:
|
||||
return ""
|
||||
k = len(alphabet)
|
||||
return "".join(alphabet[random_below(k)] for _ in range(length))
|
||||
|
||||
|
||||
#: Password character classes
|
||||
_PW_UPPER = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
||||
_PW_LOWER = "abcdefghijklmnopqrstuvwxyz"
|
||||
_PW_DIGITS = "0123456789"
|
||||
_PW_SPECIAL = "!@#$%^&*()-_=+[]{};:,.?/"
|
||||
|
||||
|
||||
def random_password(length=16, upper=True, lower=True, digits=True,
|
||||
special=False, exclude=""):
|
||||
"""Generate a cryptographically secure, strong random password.
|
||||
|
||||
Characters are chosen from the enabled character classes and then shuffled with Fisher-Yates;
|
||||
when ``length`` is not less than the number of enabled classes, **at least one character from each class is guaranteed**.
|
||||
|
||||
Parameters
|
||||
----
|
||||
length : int
|
||||
Password length, must be ``>= 1``.
|
||||
upper : bool
|
||||
Whether to include upper-case letters.
|
||||
lower : bool
|
||||
Whether to include lower-case letters.
|
||||
digits : bool
|
||||
Whether to include digits.
|
||||
special : bool
|
||||
Whether to include special symbols (``!@#$%^&*()-_=+[]{};:,.?/``).
|
||||
exclude : str
|
||||
Set of characters to exclude from all classes.
|
||||
|
||||
Returns
|
||||
----
|
||||
str
|
||||
A random password of length ``length``.
|
||||
tuple
|
||||
``length`` not an integer / ``< 1`` -> ``(PPYC_ERR_INVALID_TYPE | PPYC_ERR_OUT_OF_RANGE, ...)``;
|
||||
``exclude`` not a string, no class enabled, or some class emptied by ``exclude``
|
||||
-> ``(PPYC_ERR_INVALID_ARG, ...)``.
|
||||
"""
|
||||
if _is_bad_int(length):
|
||||
return err(PPYC_ERR_INVALID_TYPE,
|
||||
f"the password length must be an integer, got {type(length).__name__}",
|
||||
"pass a positive integer length")
|
||||
if length < 1:
|
||||
return err(PPYC_ERR_OUT_OF_RANGE,
|
||||
f"the password length must be >= 1: length={length}",
|
||||
"pass a positive integer length (>= 12 recommended)")
|
||||
if not isinstance(exclude, str):
|
||||
return err(PPYC_ERR_INVALID_ARG,
|
||||
f"exclude must be a string, got {type(exclude).__name__}",
|
||||
"pass a string of the characters to exclude, or leave it empty")
|
||||
|
||||
ex = set(exclude)
|
||||
groups = []
|
||||
if upper:
|
||||
groups.append([c for c in _PW_UPPER if c not in ex])
|
||||
if lower:
|
||||
groups.append([c for c in _PW_LOWER if c not in ex])
|
||||
if digits:
|
||||
groups.append([c for c in _PW_DIGITS if c not in ex])
|
||||
if special:
|
||||
groups.append([c for c in _PW_SPECIAL if c not in ex])
|
||||
|
||||
if not groups:
|
||||
return err(PPYC_ERR_INVALID_ARG,
|
||||
"at least one character class (upper / lower / digits / special) must be enabled",
|
||||
"set at least one class argument to True")
|
||||
for g in groups:
|
||||
if not g:
|
||||
return err(PPYC_ERR_INVALID_ARG,
|
||||
"exclude removes every character of an enabled class, so the strength requirement cannot be met",
|
||||
"narrow the exclude set, or disable the class emptied by it")
|
||||
|
||||
pool = [c for g in groups for c in g]
|
||||
|
||||
# First place one character for each class (as far as possible), then fill the remaining length from the total pool.
|
||||
out = []
|
||||
for g in groups:
|
||||
if len(out) >= length:
|
||||
break
|
||||
out.append(g[random_below(len(g))])
|
||||
while len(out) < length:
|
||||
out.append(pool[random_below(len(pool))])
|
||||
|
||||
# Fisher-Yates shuffle to avoid a class-position pattern.
|
||||
for i in range(len(out) - 1, 0, -1):
|
||||
j = random_below(i + 1)
|
||||
out[i], out[j] = out[j], out[i]
|
||||
return "".join(out)
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# 3. Distributed / uniqueness
|
||||
# ======================================================================
|
||||
|
||||
def random_uuid4():
|
||||
"""Generate an RFC 4122 version 4 (random) UUID string.
|
||||
|
||||
Based on ``os.urandom(16)``: the version bits (the top 4 bits of the 7th byte are
|
||||
``0100``) and the variant bits (the top 2 bits of the 9th byte are ``10``) are set per the specification.
|
||||
|
||||
Returns
|
||||
----
|
||||
str
|
||||
A UUID string of the form ``xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx``
|
||||
(standard lower-case format with hyphens).
|
||||
"""
|
||||
b = bytearray(_entropy(16))
|
||||
b[6] = (b[6] & 0x0F) | 0x40 # version 4
|
||||
b[8] = (b[8] & 0x3F) | 0x80 # variant RFC 4122
|
||||
return str(_uuid.UUID(bytes=bytes(b)))
|
||||
|
||||
|
||||
def random_choice(seq):
|
||||
"""Securely choose one random element from a sequence (``secrets.choice`` semantics).
|
||||
|
||||
Parameters
|
||||
----
|
||||
seq : Sequence
|
||||
A non-empty indexable sequence (``list`` / ``tuple`` / ``str`` / ``bytes`` /
|
||||
``range``, or any iterable, which is materialized into a list).
|
||||
|
||||
Returns
|
||||
----
|
||||
object
|
||||
One random element of the sequence.
|
||||
tuple
|
||||
``seq`` empty -> ``(PPYC_ERR_INVALID_ARG, ...)``;
|
||||
``seq`` not iterable / has no length -> ``(PPYC_ERR_INVALID_ARG, ...)``.
|
||||
"""
|
||||
if not isinstance(seq, (str, bytes, bytearray, list, tuple, range)):
|
||||
try:
|
||||
seq = list(seq)
|
||||
except TypeError:
|
||||
return err(PPYC_ERR_INVALID_ARG,
|
||||
f"seq must be an iterable sequence, got {type(seq).__name__}",
|
||||
"pass an iterable such as list / tuple / str / bytes")
|
||||
n = len(seq)
|
||||
if n == 0:
|
||||
return err(PPYC_ERR_INVALID_ARG,
|
||||
"the sequence is empty, cannot make a random choice",
|
||||
"pass a sequence containing at least one element")
|
||||
return seq[random_below(n)]
|
||||
|
||||
|
||||
def random_sample(seq, k):
|
||||
"""Securely draw ``k`` distinct elements from a sequence without replacement.
|
||||
|
||||
Uses a partial Fisher-Yates shuffle, guaranteeing that all ``C(n, k)`` combinations are equiprobable
|
||||
and that the result order is uniformly random as well.
|
||||
|
||||
Parameters
|
||||
----
|
||||
seq : Sequence
|
||||
A non-empty iterable sequence.
|
||||
k : int
|
||||
Sample size, must satisfy ``0 <= k <= len(seq)``.
|
||||
|
||||
Returns
|
||||
----
|
||||
list
|
||||
A list of ``k`` distinct random samples, all elements of ``seq``
|
||||
(``k == 0`` returns an empty list).
|
||||
tuple
|
||||
``seq`` empty / not iterable -> ``(PPYC_ERR_INVALID_ARG, ...)``;
|
||||
``k`` not an integer -> ``(PPYC_ERR_INVALID_TYPE, ...)``;
|
||||
``k`` out of range -> ``(PPYC_ERR_OUT_OF_RANGE, ...)``.
|
||||
"""
|
||||
if not isinstance(seq, (str, bytes, bytearray, list, tuple, range)):
|
||||
try:
|
||||
seq = list(seq)
|
||||
except TypeError:
|
||||
return err(PPYC_ERR_INVALID_ARG,
|
||||
f"seq must be an iterable sequence, got {type(seq).__name__}",
|
||||
"pass an iterable such as list / tuple / str / bytes")
|
||||
pool = list(seq)
|
||||
n = len(pool)
|
||||
if n == 0:
|
||||
return err(PPYC_ERR_INVALID_ARG,
|
||||
"the sequence is empty, cannot take a random sample",
|
||||
"pass a sequence containing at least one element")
|
||||
if _is_bad_int(k):
|
||||
return err(PPYC_ERR_INVALID_TYPE,
|
||||
f"the sample size must be an integer, got {type(k).__name__}",
|
||||
"pass an integer k")
|
||||
if k < 0 or k > n:
|
||||
return err(PPYC_ERR_OUT_OF_RANGE,
|
||||
f"sample size out of range: k={k}, sequence length={n}",
|
||||
"make sure 0 <= k <= len(seq)")
|
||||
|
||||
# Partial Fisher-Yates: the first k positions form a uniform sample without replacement.
|
||||
for i in range(k):
|
||||
j = i + random_below(n - i)
|
||||
pool[i], pool[j] = pool[j], pool[i]
|
||||
return pool[:k]
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# 4. Compatibility aliases
|
||||
# ======================================================================
|
||||
|
||||
#: Secure-version alias compatible with Python 3.9+ ``random.randbytes(n)`` semantics:
|
||||
#: returns ``n`` cryptographically secure random bytes (not the pseudo-random bytes of the ``random`` module).
|
||||
randbytes_alias = random_bytes
|
||||
@@ -0,0 +1,775 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""purepycrypto.rsa
|
||||
========================================
|
||||
purepycrypto - Pure-Python cryptography library (zero dependencies)
|
||||
RSA: key generation, OAEP encryption, PSS signatures, prime generation (BPSW), Montgomery modular exponentiation, CRT and blinding.
|
||||
|
||||
Unified error system
|
||||
------------
|
||||
Follows the unified purepycrypto error contract (see ``purepycrypto._ppyc_error``):
|
||||
* **Non-fatal errors** (invalid argument, invalid key material, message too long, decryption/verification failure, etc.) -> return a
|
||||
3-tuple ``(error_code, error_message, suggestion)``;
|
||||
* **Fatal errors** (broken internal invariant, e.g. the odd-modulus precondition violated) -> raise ``PPYC_ERR``;
|
||||
* Validation of ``RSAPublicKey`` / ``RSAPrivateKey`` is done in ``__new__``, which returns an error tuple
|
||||
directly on failure; ``rsa_pss_verify`` still returns ``bool`` to preserve boolean semantics.
|
||||
Callers use ``purepycrypto._ppyc_error.is_err(result)`` to tell whether an error tuple was returned.
|
||||
"""
|
||||
|
||||
import os
|
||||
import math
|
||||
from typing import Tuple, List, Optional
|
||||
|
||||
from .common import (
|
||||
MASK32,
|
||||
_consttime_eq, rand_int,
|
||||
)
|
||||
from .hash import sha256, sha512
|
||||
from .parallel import _HAS_MP
|
||||
|
||||
from ._ppyc_error import (
|
||||
PPYC_ERR,
|
||||
DecryptionError, # legacy name, now a subclass of PPYC_ERR (unified error system)
|
||||
err, is_err,
|
||||
PPYC_ERR_INVALID_ARG,
|
||||
PPYC_ERR_INVALID_KEY_MATERIAL,
|
||||
PPYC_ERR_INVALID_RSA_BITS,
|
||||
PPYC_ERR_MESSAGE_TOO_LONG,
|
||||
PPYC_ERR_DECRYPT_FAILED,
|
||||
)
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 12. RSA
|
||||
# ============================================================
|
||||
|
||||
def _sieve(limit: int) -> List[int]:
|
||||
s = bytearray([1]) * (limit + 1)
|
||||
s[0] = s[1] = 0
|
||||
for i in range(2, int(limit ** 0.5) + 1):
|
||||
if s[i]:
|
||||
s[i * i::i] = bytearray(len(s[i * i::i]))
|
||||
return [i for i in range(limit + 1) if s[i]]
|
||||
|
||||
|
||||
_SMALL = _sieve(10000)
|
||||
_SMALL_SET = set(_SMALL)
|
||||
|
||||
_GROUPS, _buf = [], 1
|
||||
for _p in _SMALL:
|
||||
_buf *= _p
|
||||
if _buf.bit_length() > 4096:
|
||||
_GROUPS.append(_buf)
|
||||
_buf = 1
|
||||
if _buf > 1:
|
||||
_GROUPS.append(_buf)
|
||||
|
||||
|
||||
def _passes_sieve(n: int) -> bool:
|
||||
if n in _SMALL_SET:
|
||||
return True
|
||||
for g in _GROUPS:
|
||||
if math.gcd(n, g) != 1:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def extended_gcd(a: int, b: int) -> Tuple[int, int, int]:
|
||||
old_r, r = a, b
|
||||
old_s, s = 1, 0
|
||||
old_t, t = 0, 1
|
||||
while r:
|
||||
q = old_r // r
|
||||
old_r, r = r, old_r - q * r
|
||||
old_s, s = s, old_s - q * s
|
||||
old_t, t = t, old_t - q * t
|
||||
return old_r, old_s, old_t
|
||||
|
||||
|
||||
def mod_inverse(a: int, m: int):
|
||||
"""Modular inverse a^{-1} mod m.
|
||||
|
||||
Returns
|
||||
----
|
||||
int
|
||||
The multiplicative inverse of a modulo m (0 <= result < m).
|
||||
(str, str, str)
|
||||
A non-fatal error tuple; ``PPYC_ERR_INVALID_ARG`` (a and m are not coprime, so no inverse exists).
|
||||
"""
|
||||
g, x, _ = extended_gcd(a % m, m)
|
||||
if g != 1:
|
||||
raise PPYC_ERR(PPYC_ERR_INVALID_ARG,
|
||||
f"{a} has no multiplicative inverse modulo {m} (gcd={g})",
|
||||
"make sure a and m are coprime")
|
||||
return x % m
|
||||
|
||||
|
||||
def _mr_round(n: int, d: int, s: int, a: int) -> bool:
|
||||
x = pow(a, d, n)
|
||||
if x == 1 or x == n - 1:
|
||||
return True
|
||||
for _ in range(s - 1):
|
||||
x = pow(x, 2, n)
|
||||
if x == n - 1:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _mr_base2(n: int) -> bool:
|
||||
if n < 2: return False
|
||||
if n in (2, 3): return True
|
||||
if n % 2 == 0: return False
|
||||
d, s = n - 1, 0
|
||||
while d % 2 == 0:
|
||||
d //= 2
|
||||
s += 1
|
||||
return _mr_round(n, d, s, 2)
|
||||
|
||||
|
||||
def _jacobi(a: int, n: int):
|
||||
"""Jacobi symbol (a/n).
|
||||
|
||||
Returns
|
||||
----
|
||||
int
|
||||
-1 / 0 / 1.
|
||||
(str, str, str)
|
||||
A non-fatal error tuple; ``PPYC_ERR_INVALID_ARG`` (n is not a positive odd number).
|
||||
"""
|
||||
if n <= 0 or n % 2 == 0:
|
||||
raise PPYC_ERR(PPYC_ERR_INVALID_ARG,
|
||||
f"the Jacobi symbol requires n to be a positive odd number, got n={n}",
|
||||
"pass a positive odd modulus")
|
||||
a %= n
|
||||
result = 1
|
||||
while a != 0:
|
||||
while a % 2 == 0:
|
||||
a //= 2
|
||||
if n % 8 in (3, 5):
|
||||
result = -result
|
||||
a, n = n, a
|
||||
if a % 4 == 3 and n % 4 == 3:
|
||||
result = -result
|
||||
a %= n
|
||||
return result if n == 1 else 0
|
||||
|
||||
|
||||
def _lucas_sequence(n: int, P: int, Q: int, k: int) -> Tuple[int, int]:
|
||||
if k == 0:
|
||||
return 0, 2
|
||||
U, V, Qk = 1, P, Q % n
|
||||
D = P * P - 4 * Q
|
||||
inv2 = pow(2, -1, n)
|
||||
for bit in bin(k)[3:]:
|
||||
U = (U * V) % n
|
||||
V = (V * V - 2 * Qk) % n
|
||||
Qk = (Qk * Qk) % n
|
||||
if bit == '1':
|
||||
U, V = ((P * U + V) % n, (D * U + P * V) % n)
|
||||
U = U * inv2 % n
|
||||
V = V * inv2 % n
|
||||
Qk = (Qk * Q) % n
|
||||
return U, V
|
||||
|
||||
|
||||
def _strong_lucas_prp(n: int) -> bool:
|
||||
if n < 2: return False
|
||||
if n % 2 == 0: return n == 2
|
||||
D = 5
|
||||
while True:
|
||||
j = _jacobi(D, n)
|
||||
if is_err(j): # n is not a positive odd number -> cannot be prime, report False directly
|
||||
return False
|
||||
if j == -1:
|
||||
break
|
||||
if j == 0 and abs(D) != n:
|
||||
return False
|
||||
D = -D - 2 if D > 0 else -D + 2
|
||||
if abs(D) > 1000:
|
||||
return _miller_rabin(n, rounds=4)
|
||||
P, Q = 1, (1 - D) // 4
|
||||
d = n + 1
|
||||
s = 0
|
||||
while d % 2 == 0:
|
||||
d //= 2
|
||||
s += 1
|
||||
U, V = _lucas_sequence(n, P, Q, d)
|
||||
if U == 0 or V == 0:
|
||||
return True
|
||||
Qk = pow(Q, d, n)
|
||||
for _ in range(s - 1):
|
||||
U = (U * V) % n
|
||||
V = (V * V - 2 * Qk) % n
|
||||
Qk = (Qk * Qk) % n
|
||||
if V == 0:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _miller_rabin(n: int, rounds: int = 4) -> bool:
|
||||
if n < 2: return False
|
||||
if n in (2, 3): return True
|
||||
if n % 2 == 0: return False
|
||||
d, s = n - 1, 0
|
||||
while d % 2 == 0:
|
||||
d //= 2
|
||||
s += 1
|
||||
for _ in range(rounds):
|
||||
a = 2 + int.from_bytes(os.urandom(8), "big") % (n - 3)
|
||||
if not _mr_round(n, d, s, a):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _bpsw(n: int) -> bool:
|
||||
if n < 2: return False
|
||||
if n in (2, 3): return True
|
||||
if n % 2 == 0: return False
|
||||
if not _passes_sieve(n):
|
||||
return False
|
||||
r = math.isqrt(n)
|
||||
if r * r == n:
|
||||
return False
|
||||
if not _mr_base2(n):
|
||||
return False
|
||||
return _strong_lucas_prp(n)
|
||||
|
||||
|
||||
def generate_prime_fast(bits: int) -> int:
|
||||
urandom = os.urandom
|
||||
isqrt = math.isqrt
|
||||
while True:
|
||||
base = int.from_bytes(urandom(bits // 8), "big")
|
||||
base |= (1 << (bits - 1)) | 1
|
||||
for offset in range(0, 1 << 17, 2):
|
||||
cand = base + offset
|
||||
if cand.bit_length() != bits:
|
||||
break
|
||||
if not _passes_sieve(cand):
|
||||
continue
|
||||
r = isqrt(cand)
|
||||
if r * r == cand:
|
||||
continue
|
||||
d, s = cand - 1, 0
|
||||
while d % 2 == 0:
|
||||
d //= 2
|
||||
s += 1
|
||||
x = pow(2, d, cand)
|
||||
if x != 1 and x != cand - 1:
|
||||
ok = False
|
||||
for _ in range(s - 1):
|
||||
x = pow(x, 2, cand)
|
||||
if x == cand - 1:
|
||||
ok = True
|
||||
break
|
||||
if not ok:
|
||||
continue
|
||||
if not _strong_lucas_prp(cand):
|
||||
continue
|
||||
is_p = True
|
||||
for _ in range(4):
|
||||
a = 2 + int.from_bytes(urandom(8), "big") % (cand - 3)
|
||||
if not _mr_round(cand, d, s, a):
|
||||
is_p = False
|
||||
break
|
||||
if is_p:
|
||||
return cand
|
||||
|
||||
|
||||
def _gen_worker(bits: int) -> int:
|
||||
return generate_prime_fast(bits)
|
||||
|
||||
|
||||
def generate_two_primes(bits_half: int) -> Tuple[int, int]:
|
||||
if _HAS_MP:
|
||||
try:
|
||||
with mp.Pool(2) as pool:
|
||||
p, q = pool.map(_gen_worker, [bits_half, bits_half])
|
||||
except (OSError, RuntimeError, ImportError, AttributeError):
|
||||
p = generate_prime_fast(bits_half)
|
||||
q = generate_prime_fast(bits_half)
|
||||
else:
|
||||
p = generate_prime_fast(bits_half)
|
||||
q = generate_prime_fast(bits_half)
|
||||
|
||||
while q == p:
|
||||
q = generate_prime_fast(bits_half)
|
||||
if abs(p - q) < (1 << (bits_half // 2)):
|
||||
while abs(p - q) < (1 << (bits_half // 2)):
|
||||
q = generate_prime_fast(bits_half)
|
||||
return p, q
|
||||
|
||||
|
||||
# ---- Montgomery ----
|
||||
|
||||
def _montgomery_params(n: int) -> Tuple[int, int, int]:
|
||||
k = n.bit_length()
|
||||
R = 1 << k
|
||||
n_inv = mod_inverse(n, R)
|
||||
return R, (-n_inv) % R, k
|
||||
|
||||
|
||||
class Montgomery:
|
||||
__slots__ = ("n", "R", "n_prime", "k", "R_mod_n", "n_bits")
|
||||
WINDOW = 4
|
||||
|
||||
def __init__(self, n: int):
|
||||
if n % 2 == 0:
|
||||
raise PPYC_ERR(PPYC_ERR_INVALID_ARG,
|
||||
f"Montgomery modular exponentiation requires n to be odd, got n={n}",
|
||||
"pass an odd modulus")
|
||||
self.n = n
|
||||
self.R, self.n_prime, self.k = _montgomery_params(n)
|
||||
self.R_mod_n = self.R % n
|
||||
self.n_bits = n.bit_length()
|
||||
|
||||
def _redc(self, T: int) -> int:
|
||||
m = ((T & (self.R - 1)) * self.n_prime) & (self.R - 1)
|
||||
t = (T + m * self.n) >> self.k
|
||||
cond = 1 if t >= self.n else 0
|
||||
diff = t - self.n
|
||||
mask = -cond
|
||||
return (diff & mask) | (t & ~mask)
|
||||
|
||||
def to_mont(self, x: int) -> int:
|
||||
return (x * self.R) % self.n
|
||||
|
||||
def from_mont(self, x: int) -> int:
|
||||
return self._redc(x)
|
||||
|
||||
def mul(self, a: int, b: int) -> int:
|
||||
return self._redc(a * b)
|
||||
|
||||
def pow(self, base: int, exp: int) -> int:
|
||||
if exp == 0:
|
||||
return 1 % self.n
|
||||
a_mont = self.to_mont(base % self.n)
|
||||
table = [self.R_mod_n, a_mont]
|
||||
for i in range(2, 1 << self.WINDOW):
|
||||
table.append(self.mul(table[-1], a_mont))
|
||||
w = self.WINDOW
|
||||
n_bits = exp.bit_length()
|
||||
padded_bits = ((n_bits + w - 1) // w) * w
|
||||
r = self.R_mod_n
|
||||
for shift in range(padded_bits - w, -1, -w):
|
||||
for _ in range(w):
|
||||
r = self.mul(r, r)
|
||||
window_val = (exp >> shift) & ((1 << w) - 1)
|
||||
r = self.mul(r, table[window_val])
|
||||
return self.from_mont(r)
|
||||
|
||||
|
||||
# ---- RSA key classes ----
|
||||
|
||||
BLIND_RESET_INTERVAL = 1000
|
||||
|
||||
|
||||
def choose_hash(n_bits: int):
|
||||
"""Select the hash used by OAEP/PSS based on the modulus bit length.
|
||||
|
||||
Returns
|
||||
----
|
||||
(callable, int)
|
||||
(hash function, digest byte length).
|
||||
(str, str, str)
|
||||
A non-fatal error tuple; ``PPYC_ERR_INVALID_RSA_BITS`` (the modulus is smaller than 521 bits).
|
||||
"""
|
||||
k = (n_bits + 7) // 8
|
||||
if k >= 130:
|
||||
return sha512, 64
|
||||
if k >= 66:
|
||||
return sha256, 32
|
||||
raise PPYC_ERR(PPYC_ERR_INVALID_RSA_BITS,
|
||||
f"modulus of {n_bits} bits is too small (OAEP/PSS needs at least 521 bits)",
|
||||
"use a 2048/3072/4096-bit RSA key")
|
||||
|
||||
|
||||
def mgf1(seed: bytes, length: int, hash_func, h_len: int):
|
||||
"""MGF1 mask generation function (RFC 8017 B.2.1).
|
||||
|
||||
Returns
|
||||
----
|
||||
bytes
|
||||
A mask of length length.
|
||||
(str, str, str)
|
||||
A non-fatal error tuple; ``PPYC_ERR_INVALID_ARG`` (requested length > 2^32*hLen).
|
||||
"""
|
||||
if length > (1 << 32) * h_len:
|
||||
raise PPYC_ERR(PPYC_ERR_INVALID_ARG,
|
||||
f"MGF1 output length too large ({length} > 2^32*hLen)",
|
||||
"reduce the requested length or use a hash with a longer digest")
|
||||
out = bytearray()
|
||||
ctr = 0
|
||||
while len(out) < length:
|
||||
out.extend(hash_func(seed + ctr.to_bytes(4, "big")))
|
||||
ctr += 1
|
||||
return bytes(out[:length])
|
||||
|
||||
|
||||
def oaep_encode(message: bytes, k: int, label: bytes, hash_func, h_len: int):
|
||||
"""OAEP encoding (RFC 8017 section 7.1.1).
|
||||
|
||||
Returns
|
||||
----
|
||||
bytes
|
||||
The encoded block EM of length k.
|
||||
(str, str, str)
|
||||
A non-fatal error tuple; ``PPYC_ERR_MESSAGE_TOO_LONG`` (message too long) or
|
||||
``PPYC_ERR_INVALID_RSA_BITS`` (key too small).
|
||||
"""
|
||||
mLen = len(message)
|
||||
max_len = k - 2 * h_len - 2
|
||||
if max_len < 0:
|
||||
raise PPYC_ERR(PPYC_ERR_INVALID_RSA_BITS,
|
||||
f"key too small: k={k} cannot hold OAEP (needs k >= 2*hLen+2={2 * h_len + 2})",
|
||||
"use a larger RSA key (2048 bits or more recommended)")
|
||||
if mLen > max_len:
|
||||
raise PPYC_ERR(PPYC_ERR_MESSAGE_TOO_LONG,
|
||||
f"message too long: {mLen} > {max_len}",
|
||||
"shorten the message or use hybrid encryption (RSA-OAEP encrypting a symmetric key)")
|
||||
lHash = hash_func(label)
|
||||
PS = b"\x00" * (k - mLen - 2 * h_len - 2)
|
||||
DB = lHash + PS + b"\x01" + message
|
||||
seed = os.urandom(h_len)
|
||||
dbMask = mgf1(seed, k - h_len - 1, hash_func, h_len)
|
||||
maskedDB = bytes(a ^ b for a, b in zip(DB, dbMask))
|
||||
seedMask = mgf1(maskedDB, h_len, hash_func, h_len)
|
||||
maskedSeed = bytes(a ^ b for a, b in zip(seed, seedMask))
|
||||
return b"\x00" + maskedSeed + maskedDB
|
||||
|
||||
|
||||
def oaep_decode(em: bytes, k: int, label: bytes, hash_func, h_len: int):
|
||||
"""OAEP decoding / unpadding (RFC 8017 section 7.1.2).
|
||||
|
||||
Returns
|
||||
----
|
||||
bytes
|
||||
The unpadded plaintext.
|
||||
(str, str, str)
|
||||
A non-fatal error tuple; ``PPYC_ERR_DECRYPT_FAILED`` (length mismatch or padding check failure).
|
||||
"""
|
||||
fail = False
|
||||
if len(em) != k:
|
||||
raise PPYC_ERR(PPYC_ERR_DECRYPT_FAILED,
|
||||
f"OAEP decoding failed: EM length {len(em)} != k={k}",
|
||||
"the ciphertext may be corrupted or tampered with")
|
||||
if em[0] != 0x00:
|
||||
fail = True
|
||||
maskedSeed = em[1:1 + h_len]
|
||||
maskedDB = em[1 + h_len:]
|
||||
seedMask = mgf1(maskedDB, h_len, hash_func, h_len)
|
||||
seed = bytes(a ^ b for a, b in zip(maskedSeed, seedMask))
|
||||
dbMask = mgf1(seed, k - h_len - 1, hash_func, h_len)
|
||||
DB = bytes(a ^ b for a, b in zip(maskedDB, dbMask))
|
||||
if not _consttime_eq(DB[:h_len], hash_func(label)):
|
||||
fail = True
|
||||
rest = DB[h_len:]
|
||||
idx = -1
|
||||
for i, byte in enumerate(rest):
|
||||
if byte == 0x01:
|
||||
idx = i
|
||||
break
|
||||
if byte != 0x00:
|
||||
fail = True
|
||||
if idx == -1:
|
||||
fail = True
|
||||
if fail:
|
||||
raise PPYC_ERR(PPYC_ERR_DECRYPT_FAILED,
|
||||
"OAEP decoding failed: padding check failed",
|
||||
"check that the private key and label are correct, or that the ciphertext was not tampered with")
|
||||
return rest[idx + 1:]
|
||||
|
||||
|
||||
def pss_encode(message: bytes, em_bits: int, salt_len: int,
|
||||
hash_func, h_len: int):
|
||||
"""PSS encoding (RFC 8017 section 9.1.1).
|
||||
|
||||
Returns
|
||||
----
|
||||
bytes
|
||||
The encoded block EM of length emLen.
|
||||
(str, str, str)
|
||||
A non-fatal error tuple; ``PPYC_ERR_INVALID_ARG`` (emLen too small).
|
||||
"""
|
||||
em_len = (em_bits + 7) // 8
|
||||
if em_len < h_len + salt_len + 2:
|
||||
raise PPYC_ERR(PPYC_ERR_INVALID_ARG,
|
||||
f"PSS emLen too small: {em_len} < hLen+saltLen+2={h_len + salt_len + 2}",
|
||||
"reduce salt_len or use a larger RSA key")
|
||||
m_hash = hash_func(message)
|
||||
salt = os.urandom(salt_len)
|
||||
h = hash_func(b"\x00" * 8 + m_hash + salt)
|
||||
ps = b"\x00" * (em_len - salt_len - h_len - 2)
|
||||
db = ps + b"\x01" + salt
|
||||
db_mask = mgf1(h, em_len - h_len - 1, hash_func, h_len)
|
||||
masked_db = bytearray(a ^ b for a, b in zip(db, db_mask))
|
||||
bits_to_clear = 8 * em_len - em_bits
|
||||
if bits_to_clear > 0:
|
||||
masked_db[0] &= (0xFF >> bits_to_clear)
|
||||
return bytes(masked_db) + h + b"\xbc"
|
||||
|
||||
|
||||
def pss_verify(message: bytes, em: bytes, em_bits: int, salt_len: int,
|
||||
hash_func, h_len: int) -> bool:
|
||||
"""PSS verification (RFC 8017 section 9.1.2).
|
||||
|
||||
Returns
|
||||
----
|
||||
bool
|
||||
True if verification passes, otherwise False (boolean semantics preserved, no error tuple returned).
|
||||
"""
|
||||
em_len = (em_bits + 7) // 8
|
||||
fail = False
|
||||
if len(em) != em_len:
|
||||
return False
|
||||
if em[-1] != 0xbc:
|
||||
fail = True
|
||||
masked_db = bytearray(em[:em_len - h_len - 1])
|
||||
h = em[em_len - h_len - 1:em_len - 1]
|
||||
bits_to_clear = 8 * em_len - em_bits
|
||||
if bits_to_clear > 0 and (masked_db[0] & (0xFF << (8 - bits_to_clear))):
|
||||
fail = True
|
||||
db = bytes(a ^ b for a, b in zip(masked_db, mgf1(h, em_len - h_len - 1, hash_func, h_len)))
|
||||
if bits_to_clear > 0:
|
||||
db = bytes([db[0] & (0xFF >> bits_to_clear)]) + db[1:]
|
||||
idx = -1
|
||||
for i, byte in enumerate(db):
|
||||
if byte == 0x01:
|
||||
idx = i
|
||||
break
|
||||
if byte != 0x00:
|
||||
fail = True
|
||||
if idx == -1:
|
||||
fail = True
|
||||
salt = db[idx + 1:] if idx >= 0 else b""
|
||||
if len(salt) != salt_len:
|
||||
fail = True
|
||||
h_check = hash_func(b"\x00" * 8 + hash_func(message) + salt)
|
||||
if not _consttime_eq(h_check, h):
|
||||
fail = True
|
||||
return not fail
|
||||
|
||||
|
||||
class RSAPrivateKey:
|
||||
def __init__(self, n: int, e: int, d: int, p: int, q: int, verify: bool = True):
|
||||
if p == q:
|
||||
raise PPYC_ERR(PPYC_ERR_INVALID_KEY_MATERIAL, "p and q must not be equal", "provide two distinct primes")
|
||||
if p * q != n:
|
||||
raise PPYC_ERR(PPYC_ERR_INVALID_KEY_MATERIAL, "n != p * q", "check that the modulus n matches the primes p and q")
|
||||
if p % 2 == 0 or q % 2 == 0:
|
||||
raise PPYC_ERR(PPYC_ERR_INVALID_KEY_MATERIAL, "p and q must be odd", "RSA primes must be odd")
|
||||
if math.gcd(e, (p - 1) * (q - 1)) != 1:
|
||||
raise PPYC_ERR(PPYC_ERR_INVALID_KEY_MATERIAL, "e and phi(n) are not coprime", "change the public exponent e (e.g. 65537)")
|
||||
self.n, self.e, self.d, self.p, self.q = n, e, d, p, q
|
||||
self.dp = d % (p - 1)
|
||||
self.dq = d % (q - 1)
|
||||
self.q_inv = mod_inverse(q, p)
|
||||
if (e * d) % ((p - 1) * (q - 1)) != 1:
|
||||
raise PPYC_ERR(PPYC_ERR_INVALID_KEY_MATERIAL, "d does not satisfy e*d = 1 mod phi(n)", "private exponent d does not match e")
|
||||
if d < (1 << (n.bit_length() // 2)):
|
||||
raise PPYC_ERR(PPYC_ERR_INVALID_KEY_MATERIAL, "d is too small", "private exponent d is insecure, regenerate the key")
|
||||
self.hash_func, self.h_len = choose_hash(n.bit_length())
|
||||
self.salt_len = self.h_len
|
||||
self._blind_r = None
|
||||
self._blind_r_inv = None
|
||||
self._blind_count = 0
|
||||
self._mont_p = Montgomery(p)
|
||||
self._mont_q = Montgomery(q)
|
||||
if verify:
|
||||
self._self_verify()
|
||||
|
||||
def _self_verify(self):
|
||||
test = rand_int(2, self.n - 1)
|
||||
c = pow(test, self.e, self.n)
|
||||
m_crt = self._crt_decrypt_raw(c)
|
||||
if m_crt != test:
|
||||
raise PPYC_ERR(PPYC_ERR_INVALID_KEY_MATERIAL, "key self-test failed", "the key is inconsistent, please regenerate it")
|
||||
|
||||
def _init_blinding(self):
|
||||
while True:
|
||||
r = rand_int(2, self.n - 1)
|
||||
if math.gcd(r, self.n) == 1:
|
||||
self._blind_r = r
|
||||
self._blind_r_inv = mod_inverse(r, self.n)
|
||||
self._blind_count = 0
|
||||
return
|
||||
|
||||
def _maybe_reset_blinding(self):
|
||||
self._blind_count += 1
|
||||
if self._blind_count >= BLIND_RESET_INTERVAL:
|
||||
self._blind_r = None
|
||||
self._blind_r_inv = None
|
||||
|
||||
def blind(self, c: int) -> int:
|
||||
if self._blind_r is None:
|
||||
self._init_blinding()
|
||||
return (c * pow(self._blind_r, self.e, self.n)) % self.n
|
||||
|
||||
def unblind(self, m_blinded: int) -> int:
|
||||
m = (m_blinded * self._blind_r_inv) % self.n
|
||||
self._blind_r = (self._blind_r * self._blind_r) % self.n
|
||||
self._blind_r_inv = (self._blind_r_inv * self._blind_r_inv) % self.n
|
||||
self._maybe_reset_blinding()
|
||||
return m
|
||||
|
||||
def _crt_decrypt_raw(self, c: int) -> int:
|
||||
m1 = self._mont_p.pow(c % self.p, self.dp)
|
||||
m2 = self._mont_q.pow(c % self.q, self.dq)
|
||||
h = (self.q_inv * (m1 - m2)) % self.p
|
||||
return m2 + h * self.q
|
||||
|
||||
def decrypt_blinded(self, c: int) -> int:
|
||||
c_blinded = self.blind(c)
|
||||
m_blinded = self._crt_decrypt_raw(c_blinded)
|
||||
m = self.unblind(m_blinded)
|
||||
if pow(m, self.e, self.n) != c % self.n:
|
||||
raise PPYC_ERR(PPYC_ERR_DECRYPT_FAILED, "decryption verification failed", "the ciphertext or key is wrong")
|
||||
return m
|
||||
|
||||
@property
|
||||
def k(self) -> int:
|
||||
return (self.n.bit_length() + 7) // 8
|
||||
|
||||
|
||||
class RSAPublicKey:
|
||||
def __init__(self, n: int, e: int):
|
||||
if n % 2 == 0:
|
||||
raise PPYC_ERR(PPYC_ERR_INVALID_KEY_MATERIAL, "n must be odd", "the RSA modulus n must be odd")
|
||||
if e < 3 or e % 2 == 0:
|
||||
raise PPYC_ERR(PPYC_ERR_INVALID_KEY_MATERIAL, "e must be an odd number >= 3", "the usual value of e is 65537")
|
||||
self.n, self.e = n, e
|
||||
self.hash_func, self.h_len = choose_hash(n.bit_length())
|
||||
self.salt_len = self.h_len
|
||||
|
||||
@property
|
||||
def k(self) -> int:
|
||||
return (self.n.bit_length() + 7) // 8
|
||||
|
||||
|
||||
def rsa_keygen(bits: int = 2048, parallel: bool = True) -> Tuple[RSAPublicKey, RSAPrivateKey]:
|
||||
# choose_hash requires a modulus of at least 521 bits (k>=66); otherwise the RSAPrivateKey constructor always raises,
|
||||
# which would make the while True loop below retry forever. Intercept early here to avoid burning CPU in a dead loop.
|
||||
if bits < 521:
|
||||
raise PPYC_ERR(PPYC_ERR_INVALID_RSA_BITS, f"RSA keys need at least 521 bits (got {bits})", "use 2048 / 3072 / 4096")
|
||||
half = bits // 2
|
||||
if parallel and not _HAS_MP:
|
||||
parallel = False
|
||||
while True:
|
||||
if parallel:
|
||||
p, q = generate_two_primes(half)
|
||||
else:
|
||||
p = generate_prime_fast(half)
|
||||
q = generate_prime_fast(half)
|
||||
while q == p or abs(p - q) < (1 << (half // 2)):
|
||||
q = generate_prime_fast(half)
|
||||
n = p * q
|
||||
if n.bit_length() != bits:
|
||||
continue
|
||||
phi = (p - 1) * (q - 1)
|
||||
if math.gcd(65537, phi) != 1:
|
||||
continue
|
||||
d = mod_inverse(65537, phi)
|
||||
if d < (1 << (bits // 2)):
|
||||
continue
|
||||
try:
|
||||
pub = RSAPublicKey(n, 65537)
|
||||
priv = RSAPrivateKey(n, 65537, d, p, q, verify=True)
|
||||
return pub, priv
|
||||
except ValueError:
|
||||
continue
|
||||
|
||||
|
||||
def rsa_oaep_encrypt(message: bytes, pub: RSAPublicKey, label: bytes = b""):
|
||||
"""RSA-OAEP encryption.
|
||||
|
||||
Returns
|
||||
----
|
||||
bytes
|
||||
A ciphertext of length k.
|
||||
(str, str, str)
|
||||
A non-fatal error tuple; ``PPYC_ERR_MESSAGE_TOO_LONG`` / ``PPYC_ERR_INVALID_RSA_BITS``.
|
||||
"""
|
||||
k = pub.k
|
||||
try:
|
||||
em = oaep_encode(message, k, label, pub.hash_func, pub.h_len)
|
||||
m = int.from_bytes(em, "big")
|
||||
if m >= pub.n:
|
||||
raise PPYC_ERR(PPYC_ERR_MESSAGE_TOO_LONG,
|
||||
"encoded message exceeds the modulus", "message too long, shorten it or use a larger key")
|
||||
except PPYC_ERR as e:
|
||||
return e.as_tuple() # internal error -> return as a non-fatal tuple
|
||||
return pow(m, pub.e, pub.n).to_bytes(k, "big")
|
||||
|
||||
|
||||
def rsa_oaep_decrypt(ciphertext: bytes, priv: RSAPrivateKey, label: bytes = b""):
|
||||
"""RSA-OAEP decryption.
|
||||
|
||||
Returns
|
||||
----
|
||||
bytes
|
||||
The plaintext.
|
||||
(str, str, str)
|
||||
A non-fatal error tuple; ``PPYC_ERR_DECRYPT_FAILED`` (length/value/padding check failure).
|
||||
"""
|
||||
k = priv.k
|
||||
try:
|
||||
if len(ciphertext) != k:
|
||||
raise PPYC_ERR(PPYC_ERR_DECRYPT_FAILED, "decryption failed",
|
||||
"the ciphertext or key is wrong, or the data was tampered with")
|
||||
c = int.from_bytes(ciphertext, "big")
|
||||
if c >= priv.n:
|
||||
raise PPYC_ERR(PPYC_ERR_DECRYPT_FAILED, "decryption failed",
|
||||
"the ciphertext or key is wrong, or the data was tampered with")
|
||||
try:
|
||||
m = priv.decrypt_blinded(c)
|
||||
except ValueError as exc:
|
||||
raise PPYC_ERR(PPYC_ERR_DECRYPT_FAILED, "decryption failed",
|
||||
"the ciphertext or key is wrong, or the data was tampered with") from exc
|
||||
return oaep_decode(m.to_bytes(k, "big"), k, label, priv.hash_func, priv.h_len)
|
||||
except PPYC_ERR as e:
|
||||
return e.as_tuple()
|
||||
|
||||
|
||||
def rsa_pss_sign(message: bytes, priv: RSAPrivateKey, salt_len: int = None):
|
||||
"""RSA-PSS signing.
|
||||
|
||||
Returns
|
||||
----
|
||||
bytes
|
||||
A signature of length k.
|
||||
(str, str, str)
|
||||
A non-fatal error tuple; ``PPYC_ERR_MESSAGE_TOO_LONG`` / ``PPYC_ERR_INVALID_ARG``.
|
||||
"""
|
||||
k = priv.k
|
||||
em_bits = priv.n.bit_length() - 1
|
||||
sl = salt_len if salt_len is not None else priv.salt_len
|
||||
try:
|
||||
em = pss_encode(message, em_bits, sl, priv.hash_func, priv.h_len)
|
||||
m = int.from_bytes(em, "big")
|
||||
if m >= priv.n:
|
||||
raise PPYC_ERR(PPYC_ERR_MESSAGE_TOO_LONG, "encoded message exceeds the modulus",
|
||||
"message too long, shorten it or use a larger key")
|
||||
except PPYC_ERR as e:
|
||||
return e.as_tuple()
|
||||
return pow(m, priv.d, priv.n).to_bytes(k, "big")
|
||||
|
||||
|
||||
def rsa_pss_verify(message: bytes, signature: bytes, pub: RSAPublicKey,
|
||||
salt_len: int = None) -> bool:
|
||||
"""RSA-PSS signature verification.
|
||||
|
||||
Returns
|
||||
----
|
||||
bool
|
||||
True if verification passes, otherwise False (boolean semantics preserved, no error tuple returned).
|
||||
"""
|
||||
k = pub.k
|
||||
if len(signature) != k:
|
||||
return False
|
||||
s = int.from_bytes(signature, "big")
|
||||
if s >= pub.n:
|
||||
return False
|
||||
em_bits = pub.n.bit_length() - 1
|
||||
em_len = (em_bits + 7) // 8
|
||||
sl = salt_len if salt_len is not None else pub.salt_len
|
||||
return pss_verify(message, pow(s, pub.e, pub.n).to_bytes(em_len, "big"),
|
||||
em_bits, sl, pub.hash_func, pub.h_len)
|
||||
@@ -0,0 +1,487 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
build_single.py -- purepycrypto single-file bundler (multi-version)
|
||||
=======================================================
|
||||
Merge the purepycrypto package (multiple modules) into a standalone single file. Three artifacts are supported:
|
||||
|
||||
* tui -- merged library + full interactive TUI entry (terminal menu, pipe-drivable)
|
||||
artifact: purepycrypto_tui.py
|
||||
* cli -- merged library + command-line argument entry (argparse subcommands, suitable for scripts/CI)
|
||||
artifact: purepycrypto_cli.py
|
||||
* lib -- merged library only (no entry, for embedding / import use)
|
||||
artifact: purepycrypto_lib.py
|
||||
|
||||
You can also generate both the tui and cli versions at once with --mode all (the default).
|
||||
|
||||
Usage
|
||||
----
|
||||
python build_single.py # generate tui + cli (default all)
|
||||
python build_single.py --mode tui # generate only the TUI version
|
||||
python build_single.py --mode cli # generate only the CLI version
|
||||
python build_single.py --mode lib # generate only the pure-library version
|
||||
python build_single.py -o out/x.py # specify the output (valid only for a single mode)
|
||||
python build_single.py --all # same as all, and additionally generate the lib version
|
||||
|
||||
Artifact usage
|
||||
--------
|
||||
python purepycrypto_tui.py # start the interactive TUI
|
||||
echo -e "1\\n1\\nabc\\n\\n0\\n0" | python purepycrypto_tui.py # pipe-driven
|
||||
python purepycrypto_cli.py hash --algo sha256 --text abc --hex
|
||||
python purepycrypto_cli.py --help
|
||||
import purepycrypto_lib as ppc # use as a library
|
||||
"""
|
||||
import argparse
|
||||
import ast
|
||||
import os
|
||||
import re
|
||||
|
||||
# Module concatenation order (strictly bottom-up by dependency); entry modules excluded
|
||||
LIB_MODULES = [
|
||||
"_ppyc_error", # unified error scheme (must be merged first; other modules depend on it)
|
||||
"common",
|
||||
"parallel",
|
||||
"hash",
|
||||
"kdf",
|
||||
"aes",
|
||||
"chacha",
|
||||
"x25519",
|
||||
"rsa",
|
||||
"der",
|
||||
]
|
||||
# New modules in v1.1 / v3.2.0 (included if present)
|
||||
OPTIONAL_MODULES = [
|
||||
"sha3",
|
||||
"ed25519",
|
||||
"aes_gcm_siv",
|
||||
# v3.2.0
|
||||
"encoding",
|
||||
"rand",
|
||||
"kdf2",
|
||||
]
|
||||
ENTRY_TUI = "cli" # interactive TUI module
|
||||
ENTRY_CLI = "cli_args" # command-line argument module
|
||||
|
||||
PKG_DIR = os.path.normpath(
|
||||
os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")
|
||||
)
|
||||
# Single-file artifacts default to the in-package single/ directory (to avoid polluting the project root)
|
||||
SINGLE_DIR = os.path.join(PKG_DIR, "single")
|
||||
# Compatibility: another location can still be given via --outdir
|
||||
ROOT_DIR = SINGLE_DIR
|
||||
|
||||
COMMON_IMPORTS = '''
|
||||
import os
|
||||
import sys
|
||||
import math
|
||||
import time
|
||||
import struct
|
||||
import base64
|
||||
import atexit
|
||||
import argparse
|
||||
import json
|
||||
from typing import Tuple, Optional, List, Dict, Any, Union
|
||||
|
||||
try:
|
||||
import multiprocessing as mp
|
||||
from multiprocessing import Pool, cpu_count
|
||||
from multiprocessing import shared_memory
|
||||
_HAS_MP = True
|
||||
except (ImportError, ModuleNotFoundError):
|
||||
mp = None
|
||||
Pool = None
|
||||
cpu_count = lambda: 1
|
||||
shared_memory = None
|
||||
_HAS_MP = False
|
||||
|
||||
# ---- Package metadata (merged from __init__) ----
|
||||
__version__ = "@@VERSION@@"
|
||||
__author__ = "Dvs(DvsXT)"
|
||||
__license__ = "MIT"
|
||||
__version_tuple__ = tuple(int(x) for x in __version__.split(".")[:3])
|
||||
'''
|
||||
|
||||
# Standard-library modules provided by the merged header (matching imports are removed)
|
||||
STDLIB_NAMES = {
|
||||
"os", "sys", "math", "time", "struct", "base64", "atexit",
|
||||
"hashlib", "typing", "array", "datetime",
|
||||
"multiprocessing",
|
||||
}
|
||||
STDLIB_FROMS = {"typing", "array", "datetime", "multiprocessing"}
|
||||
|
||||
DQ = '"' * 3
|
||||
SQ = "'" * 3
|
||||
|
||||
|
||||
# -------------------------------------------------------------
|
||||
# Header template
|
||||
# -------------------------------------------------------------
|
||||
|
||||
def _header(mode, version="2.7.10"):
|
||||
title = {
|
||||
"one": "purepycrypto.py -- purepycrypto single-file integrated build (no args=TUI, with args=command line)",
|
||||
"tui": "purepycrypto_tui.py -- purepycrypto single-file build (interactive TUI)",
|
||||
"cli": "purepycrypto_cli.py -- purepycrypto single-file build (command-line arguments)",
|
||||
"lib": "purepycrypto_lib.py -- purepycrypto single-file build (pure library)",
|
||||
}[mode]
|
||||
usage = {
|
||||
"one": (' python purepycrypto.py # no args -> interactive TUI\n'
|
||||
' python purepycrypto.py hash --text abc --hex # with args -> command line'),
|
||||
"tui": (' python purepycrypto_tui.py # start the interactive TUI\n'
|
||||
' echo -e "1\\n1\\nabc\\n\\n0\\n0" | python purepycrypto_tui.py'),
|
||||
"cli": (' python purepycrypto_cli.py hash --algo sha256 --text abc --hex\n'
|
||||
' python purepycrypto_cli.py --help'),
|
||||
"lib": (' import purepycrypto_lib as ppc\n'
|
||||
' ppc.sha256(b"abc").hex()'),
|
||||
}[mode]
|
||||
return (
|
||||
'# -*- coding: utf-8 -*-\n'
|
||||
'"""\n'
|
||||
+ title + '\n'
|
||||
+ '=' * len(title) + '\n'
|
||||
'purepycrypto -- Pure-Python cryptography library (zero dependencies) · Single-file merged build v' + version + '\n\n'
|
||||
'This file was auto-generated by purepycrypto/scripts/build_single.py; do not edit it by hand.\n\n'
|
||||
'Includes: SHA-2 / SHA-512 / BLAKE2b / SHA-3(Keccak) / SHAKE\n'
|
||||
' HMAC-SHA256/512/3 · PBKDF2 / HKDF / scrypt / Argon2id\n'
|
||||
' AES(ECB,CBC,CTR,CFB,OFB,GCM) / AES-GCM-SIV\n'
|
||||
' ChaCha20-Poly1305 / XChaCha20-Poly1305\n'
|
||||
' X25519 / Ed25519 / RSA(keygen,OAEP,PSS,PEM) / ASN.1 DER\n\n'
|
||||
'Usage:\n' + usage + '\n\n'
|
||||
'License: MIT (see LICENSE).\n'
|
||||
'"""\n'
|
||||
)
|
||||
|
||||
|
||||
# Single-file mode: register the aliases expected by cli / cli_args for new module functions
|
||||
_ALIAS_BOOTSTRAP = """
|
||||
# ---- Single-file aliases (used by cli / cli_args; provided by try-import in package mode) ----
|
||||
try:
|
||||
_b64e = b64encode; _b64d = b64decode
|
||||
_b64e_u = b64encode_urlsafe; _b64d_u = b64decode_urlsafe
|
||||
_b32e = b32encode; _b32d = b32decode
|
||||
_hexe = hex_encode; _hexd = hex_decode
|
||||
_b58e = b58encode; _b58d = b58decode
|
||||
except NameError:
|
||||
pass
|
||||
try:
|
||||
_rbytes = random_bytes; _token_hex = token_hex
|
||||
_token_urlsafe = token_urlsafe; _rpassword = random_password
|
||||
_uuid4 = random_uuid4
|
||||
except NameError:
|
||||
pass
|
||||
try:
|
||||
_a2id = argon2id_hash; _a2enc = argon2id_hash_encoded
|
||||
_scrypt_simple = scrypt_simple
|
||||
except NameError:
|
||||
pass
|
||||
try:
|
||||
_b64encode = b64encode; _b64decode = b64decode
|
||||
_b32encode = b32encode; _hex_encode = hex_encode; _b58encode = b58encode
|
||||
except NameError:
|
||||
pass
|
||||
try:
|
||||
_random_bytes = random_bytes; _token_hex = token_hex
|
||||
_token_urlsafe = token_urlsafe; _random_password = random_password
|
||||
_random_uuid4 = random_uuid4
|
||||
except NameError:
|
||||
pass
|
||||
"""
|
||||
|
||||
|
||||
# -------------------------------------------------------------
|
||||
# Source processing
|
||||
# -------------------------------------------------------------
|
||||
|
||||
def _read_actual_version():
|
||||
"""Read the real version from purepycrypto/_version.py (takes precedence over the command-line argument)."""
|
||||
vp = os.path.join(PKG_DIR, "_version.py")
|
||||
try:
|
||||
with open(vp, "r", encoding="utf-8") as f:
|
||||
m = re.search(r'__version__\s*=\s*["\']([^"\']+)["\']', f.read())
|
||||
return m.group(1) if m else None
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
|
||||
def _read_module(name):
|
||||
path = os.path.join(PKG_DIR, name + ".py")
|
||||
if not os.path.exists(path):
|
||||
raise FileNotFoundError("module file not found: " + path)
|
||||
with open(path, "r", encoding="utf-8") as f:
|
||||
return f.read()
|
||||
|
||||
|
||||
def _import_line_spans(src):
|
||||
spans = set()
|
||||
try:
|
||||
tree = ast.parse(src)
|
||||
except SyntaxError:
|
||||
return spans
|
||||
for node in tree.body:
|
||||
if isinstance(node, (ast.Import, ast.ImportFrom)):
|
||||
start = node.lineno
|
||||
end = getattr(node, "end_lineno", start)
|
||||
for ln in range(start, end + 1):
|
||||
spans.add(ln)
|
||||
return spans
|
||||
|
||||
|
||||
def _is_droppable_import(node):
|
||||
if isinstance(node, ast.ImportFrom):
|
||||
if node.level and node.level > 0:
|
||||
return True
|
||||
if node.module in STDLIB_FROMS:
|
||||
return True
|
||||
if node.module is None and node.level == 0:
|
||||
return True
|
||||
return False
|
||||
if isinstance(node, ast.Import):
|
||||
for alias in node.names:
|
||||
if alias.name.split(".")[0] in STDLIB_NAMES:
|
||||
return True
|
||||
return False
|
||||
return False
|
||||
|
||||
|
||||
def _strip(src):
|
||||
"""Drop the module header docstring and the coding line, and remove imports that the merged header replaces / relative imports.
|
||||
|
||||
Implementation note: use the AST to precisely locate the (line, column) range of the module docstring,
|
||||
avoiding false boundary detection when the docstring text contains quotes (such as 'foo' / "__main__").
|
||||
"""
|
||||
lines = src.split("\n")
|
||||
|
||||
# ---- 1) Use the AST to find the module docstring's start/end lines ----
|
||||
doc_start = doc_end = None
|
||||
try:
|
||||
tree = ast.parse(src)
|
||||
if (tree.body and isinstance(tree.body[0], ast.Expr)
|
||||
and isinstance(tree.body[0].value, ast.Constant)
|
||||
and isinstance(tree.body[0].value.value, str)):
|
||||
doc = tree.body[0]
|
||||
doc_start = doc.lineno # 1-based
|
||||
doc_end = getattr(doc, "end_lineno", doc.lineno)
|
||||
except SyntaxError:
|
||||
pass
|
||||
|
||||
# ---- 2) Collect lines to drop: coding/shebang lines + docstring + droppable imports ----
|
||||
drop = set()
|
||||
n = len(lines)
|
||||
i = 0
|
||||
while i < n and lines[i].strip() == "":
|
||||
i += 1
|
||||
if i < n and lines[i].startswith("#!"):
|
||||
drop.add(i + 1)
|
||||
i += 1
|
||||
if i < n and "coding" in lines[i] and lines[i].lstrip().startswith("#"):
|
||||
drop.add(i + 1)
|
||||
|
||||
if doc_start is not None:
|
||||
for ln in range(doc_start, doc_end + 1):
|
||||
drop.add(ln)
|
||||
|
||||
# ---- 3) Remove imports that the merged header replaces / relative imports (the AST locates multi-line parenthesized forms) ----
|
||||
# Note: if these imports are inside a try/except ImportError fallback block, the ENTIRE block must be removed,
|
||||
# otherwise a dangling try:/except: is left behind and causes a syntax error.
|
||||
def _is_try_import_block(node):
|
||||
"""Is node a try block whose body consists solely of droppable imports?"""
|
||||
if not isinstance(node, ast.Try):
|
||||
return False
|
||||
body = [b for b in node.body if not isinstance(b, ast.Expr)]
|
||||
return bool(body) and all(
|
||||
isinstance(b, (ast.Import, ast.ImportFrom)) and _is_droppable_import(b)
|
||||
for b in body
|
||||
)
|
||||
|
||||
try:
|
||||
tree2 = ast.parse(src)
|
||||
for node in tree2.body:
|
||||
target = None
|
||||
if isinstance(node, (ast.Import, ast.ImportFrom)) and _is_droppable_import(node):
|
||||
target = node
|
||||
elif _is_try_import_block(node):
|
||||
# remove the whole try/except block (including all handlers / orelse / finalbody)
|
||||
target = node
|
||||
if target is not None:
|
||||
start = target.lineno
|
||||
end = getattr(target, "end_lineno", start)
|
||||
for ln in range(start, end + 1):
|
||||
drop.add(ln)
|
||||
except SyntaxError:
|
||||
pass
|
||||
|
||||
# ---- 4) Remove each module's own __main__ entry block ----
|
||||
# Only recognize a **top-level (zero-indent)** if __name__, to avoid breaking example code inside docstrings/functions
|
||||
for idx, line in enumerate(lines, start=1):
|
||||
if line.startswith("if __name__") and "__main__" in line:
|
||||
j = idx
|
||||
# skip the entire indented block
|
||||
while j < n:
|
||||
nxt = lines[j]
|
||||
if nxt.strip() == "":
|
||||
j += 1
|
||||
continue
|
||||
if nxt.startswith((" ", "\t")):
|
||||
j += 1
|
||||
continue
|
||||
break
|
||||
for ln in range(idx, j + 1):
|
||||
drop.add(ln)
|
||||
break
|
||||
|
||||
out = [ln for idx, ln in enumerate(lines, start=1) if idx not in drop]
|
||||
return "\n".join(out)
|
||||
|
||||
|
||||
# -------------------------------------------------------------
|
||||
# Merge
|
||||
# -------------------------------------------------------------
|
||||
|
||||
def _available_modules():
|
||||
mods = []
|
||||
for name in LIB_MODULES + OPTIONAL_MODULES:
|
||||
if os.path.exists(os.path.join(PKG_DIR, name + ".py")):
|
||||
mods.append(name)
|
||||
return mods
|
||||
|
||||
|
||||
def build(mode="one", version="2.7.10"):
|
||||
"""Generate single-file source. mode in {one, tui, cli, lib}.
|
||||
|
||||
one : integrated build (no args=TUI, with args=command line), matching the `purepycrypto` command behavior
|
||||
tui : TUI-only build
|
||||
cli : command-line-only build
|
||||
lib : pure library (no entry)
|
||||
"""
|
||||
if mode not in ("one", "tui", "cli", "lib"):
|
||||
raise ValueError("mode must be one / tui / cli / lib")
|
||||
|
||||
parts = [_header(mode, version), COMMON_IMPORTS]
|
||||
|
||||
modules = _available_modules()
|
||||
if mode in ("one", "tui", "cli"):
|
||||
# always merge cli first (it provides the TUI menu + _self_test)
|
||||
if os.path.exists(os.path.join(PKG_DIR, ENTRY_TUI + ".py")):
|
||||
modules = modules + [ENTRY_TUI]
|
||||
if mode in ("one", "cli"):
|
||||
# then merge cli_args (the command-line argument entry)
|
||||
if os.path.exists(os.path.join(PKG_DIR, ENTRY_CLI + ".py")):
|
||||
modules = modules + [ENTRY_CLI]
|
||||
|
||||
for name in modules:
|
||||
body = _strip(_read_module(name))
|
||||
bar = "# " + "=" * 60
|
||||
parts.append("\n\n" + bar + "\n# module: " + name + "\n" + bar + "\n")
|
||||
parts.append(body.strip("\n"))
|
||||
|
||||
# Alias bootstrap: must come **after** all modules are merged (only then are the functions defined)
|
||||
parts.append("\n\n" + _ALIAS_BOOTSTRAP)
|
||||
|
||||
if mode == "tui":
|
||||
parts.append('\n\n# ' + '=' * 60 +
|
||||
'\n# Entry point (interactive TUI)\n# ' + '=' * 60 +
|
||||
'\n\nif __name__ == "__main__":\n'
|
||||
' _entry()\n')
|
||||
elif mode == "cli":
|
||||
parts.append('\n\n# ' + '=' * 60 +
|
||||
'\n# Entry point (command-line arguments)\n# ' + '=' * 60 +
|
||||
'\n\nif __name__ == "__main__":\n'
|
||||
' import sys as _sys\n'
|
||||
' _sys.exit(_cli_main(_sys.argv[1:]))\n')
|
||||
elif mode == "one":
|
||||
# Integrated build: no args -> TUI; with args -> command line (matches this package's console script behavior)
|
||||
parts.append('\n\n# ' + '=' * 60 +
|
||||
'\n# Entry point (no args=TUI, with args=command line)\n# ' + '=' * 60 +
|
||||
'\n\n'
|
||||
'def _entry():\n'
|
||||
' argv = sys.argv[1:]\n'
|
||||
' if not argv:\n'
|
||||
' return _tui_main()\n'
|
||||
' if argv[0] == "tui":\n'
|
||||
' return _tui_main()\n'
|
||||
' if argv[0] == "cli":\n'
|
||||
' return _cli_main(argv[1:])\n'
|
||||
' return _cli_main(argv)\n'
|
||||
'\n\n'
|
||||
'if __name__ == "__main__":\n'
|
||||
' sys.exit(_entry() or 0)\n')
|
||||
|
||||
code = "\n".join(parts)
|
||||
code = re.sub(r"\n{4,}", "\n\n\n", code)
|
||||
# Substitute the real version for the template placeholder (to avoid a stale hard-coded value)
|
||||
actual = _read_actual_version() or version
|
||||
code = code.replace("@@VERSION@@", actual)
|
||||
return code
|
||||
|
||||
|
||||
OUTPUT_NAMES = {
|
||||
"one": "purepycrypto.py", # single-file integrated build: no args=TUI, with args=CLI
|
||||
"tui": "purepycrypto_tui.py",
|
||||
"cli": "purepycrypto_cli.py",
|
||||
"lib": "purepycrypto_lib.py",
|
||||
}
|
||||
|
||||
|
||||
def _emit(mode, out_path, version):
|
||||
code = build(mode=mode, version=version)
|
||||
os.makedirs(os.path.dirname(os.path.abspath(out_path)), exist_ok=True)
|
||||
with open(out_path, "w", encoding="utf-8") as f:
|
||||
f.write(code)
|
||||
|
||||
try:
|
||||
compile(code, out_path, "exec")
|
||||
status = "syntax check passed"
|
||||
except SyntaxError as e:
|
||||
status = "⚠ syntax error: " + str(e)
|
||||
|
||||
print("[✓] " + mode.upper() + " -> " + out_path)
|
||||
print(" size: {:,} chars / {:,} lines".format(len(code), len(code.splitlines())))
|
||||
print(" " + status)
|
||||
return status.startswith("syntax check passed")
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(
|
||||
description="purepycrypto single-file bundler (TUI / CLI / pure-library versions)",
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter,
|
||||
epilog=__doc__,
|
||||
)
|
||||
ap.add_argument("--mode", default="one",
|
||||
choices=["one", "tui", "cli", "lib", "all"],
|
||||
help="artifact type: one=integrated (recommended) / tui / cli / lib / all")
|
||||
ap.add_argument("-o", "--output", default=None,
|
||||
help="output file path (valid only when --mode is a single type)")
|
||||
ap.add_argument("--outdir", default=None,
|
||||
help="output directory (default: project root dev dir/)")
|
||||
ap.add_argument("--all", action="store_true",
|
||||
help="equivalent to all, and additionally generate the lib version")
|
||||
ap.add_argument("--version", default="2.7.10", help="version string written into the file")
|
||||
args = ap.parse_args()
|
||||
|
||||
outdir = args.outdir or ROOT_DIR
|
||||
|
||||
if args.mode == "all":
|
||||
modes = ["tui", "cli"]
|
||||
if args.all:
|
||||
modes.append("lib")
|
||||
else:
|
||||
modes = [args.mode]
|
||||
|
||||
if args.output and len(modes) > 1:
|
||||
ap.error("-o/--output can only be used together with --mode tui|cli|lib")
|
||||
|
||||
all_ok = True
|
||||
for mode in modes:
|
||||
out_path = args.output or os.path.join(outdir, OUTPUT_NAMES[mode])
|
||||
all_ok &= _emit(mode, out_path, args.version)
|
||||
|
||||
print()
|
||||
if all_ok:
|
||||
print("[✓] all artifacts passed the syntax check")
|
||||
else:
|
||||
print("[!] syntax errors present, please check")
|
||||
return 0 if all_ok else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,477 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""purepycrypto.sha3
|
||||
========================================
|
||||
purepycrypto - Pure-Python cryptography library (zero dependencies)
|
||||
SHA-3 / Keccak family hashes (FIPS 202) and HMAC-SHA3.
|
||||
|
||||
Contents
|
||||
--------
|
||||
- Keccak-f[1600] permutation (24 rounds, the five steps theta/rho/pi/chi/iota, state = 25 x 64-bit lanes, little-endian)
|
||||
- Sponge absorb / squeeze, pad10*1 padding
|
||||
- SHA3-224 / SHA3-256 / SHA3-384 / SHA3-512 (fixed-length digests)
|
||||
- SHAKE128 / SHAKE256 (extendable-output functions, XOF)
|
||||
- HMAC-SHA3-256 / HMAC-SHA3-512 (RFC 2104 / FIPS 198-1 style)
|
||||
|
||||
Standards
|
||||
----
|
||||
- NIST FIPS PUB 202, "SHA-3 Standard: Permutation-Based Hash and
|
||||
Extendable-Output Functions", 2015-08.
|
||||
- FIPS 198-1 / RFC 2104 (HMAC).
|
||||
|
||||
Rate parameter (r, in bytes)
|
||||
-----------------------
|
||||
SHA3-224 r = 144 (c = 448)
|
||||
SHA3-256 r = 136 (c = 512)
|
||||
SHA3-384 r = 104 (c = 832)
|
||||
SHA3-512 r = 72 (c = 576)
|
||||
SHAKE128 r = 168 (c = 256)
|
||||
SHAKE256 r = 136 (c = 512)
|
||||
|
||||
Domain separation suffix (the first byte participating in pad10*1)
|
||||
SHA3-* 0x06 (binary 0000_0110 = pad bit 01 + pad10*1 start 1)
|
||||
SHAKE* 0x1F (binary 0001_1111 = pad bits 1111 + pad10*1 start 1)
|
||||
|
||||
Usage
|
||||
----
|
||||
from purepycrypto.sha3 import (
|
||||
sha3_256, sha3_512, shake128, shake256,
|
||||
hmac_sha3_256, hmac_sha3_512,
|
||||
)
|
||||
|
||||
digest = sha3_256(b"abc") # 32 bytes
|
||||
xof = shake128(b"abc", 64) # arbitrary-length output
|
||||
mac = hmac_sha3_256(key, b"msg") # 32-byte MAC
|
||||
|
||||
# Convenience hex interfaces
|
||||
from purepycrypto.sha3 import sha3_256_hex
|
||||
hexdigest = sha3_256_hex(b"abc")
|
||||
|
||||
Known limitations
|
||||
--------
|
||||
- Pure-Python implementation, far slower than C/OpenSSL versions; intended for teaching, auditing and dependency-free scenarios only.
|
||||
- This is a reference-correct implementation without dedicated side-channel hardening (hash primitives are usually not sensitive).
|
||||
- Fully compatible with hashlib.sha3_* / hashlib.shake_* (cross-validated).
|
||||
"""
|
||||
|
||||
import struct
|
||||
|
||||
from .common import MASK64
|
||||
from ._ppyc_error import (PPYC_ERR, err, PPYC_ERR_PREFIX,
|
||||
PPYC_ERR_INVALID_ARG, PPYC_ERR_INVALID_ALGO)
|
||||
|
||||
try:
|
||||
from .parallel import _HAS_MP, _get_pool
|
||||
except ImportError: # fallback for extremely trimmed environments
|
||||
_HAS_MP, _get_pool = False, lambda n: None
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 1. Keccak-f[1600] permutation
|
||||
# ============================================================
|
||||
|
||||
# The 24 round constants (iota step), per FIPS 202.
|
||||
_KECCAK_RC = (
|
||||
0x0000000000000001, 0x0000000000008082, 0x800000000000808A, 0x8000000080008000,
|
||||
0x000000000000808B, 0x0000000080000001, 0x8000000080008081, 0x8000000000008009,
|
||||
0x000000000000008A, 0x0000000000000088, 0x0000000080008009, 0x000000008000000A,
|
||||
0x000000008000808B, 0x800000000000008B, 0x8000000000008089, 0x8000000000008003,
|
||||
0x8000000000008002, 0x8000000000000080, 0x000000000000800A, 0x800000008000000A,
|
||||
0x8000000080008081, 0x8000000000008080, 0x0000000080000001, 0x8000000080008008,
|
||||
)
|
||||
|
||||
# The rho-step rotation offset table, indexed [x][y] (FIPS 202 Table 2).
|
||||
_KECCAK_ROT = (
|
||||
(0, 36, 3, 41, 18),
|
||||
(1, 44, 10, 45, 2),
|
||||
(62, 6, 43, 15, 61),
|
||||
(28, 55, 25, 21, 56),
|
||||
(27, 20, 39, 8, 14),
|
||||
)
|
||||
|
||||
|
||||
# ------------------------------------------------------------
|
||||
# SWAR (SIMD-Within-A-Register) packing constants
|
||||
# ------------------------------------------------------------
|
||||
# The state is 25 x 64-bit = 1600 bits, packed into a single Python big integer:
|
||||
# lane i = x + 5y maps to bit 64*i; the integer and bytes convert with little-endian.
|
||||
_M64 = (1 << 64) - 1
|
||||
_M320 = (1 << 320) - 1
|
||||
_M1600 = (1 << 1600) - 1
|
||||
|
||||
# Merged rho (rotate) + pi (permute) order table: output position d takes source lane src with rotation n.
|
||||
# rho: each lane is rotated by _KECCAK_ROT[x][y]
|
||||
# pi: dst = y + 5*((2x + 3y) % 5)
|
||||
_ROT_OF_LANE = [_KECCAK_ROT[i % 5][i // 5] for i in range(25)]
|
||||
_RHOPI_ORDER = [None] * 25
|
||||
for _i in range(25):
|
||||
_x, _y = _i % 5, _i // 5
|
||||
_dst = _y + 5 * ((2 * _x + 3 * _y) % 5)
|
||||
_RHOPI_ORDER[_dst] = (_i, _ROT_OF_LANE[_i])
|
||||
assert sorted(d for d, _ in _RHOPI_ORDER) == list(range(25))
|
||||
|
||||
# theta-step bit masks: the lowest bit / bit-group 0 of each 64-bit lane
|
||||
_LOMASK = 0
|
||||
_HIMASK = 0
|
||||
for _k in range(5):
|
||||
_HIMASK |= 1 << (64 * _k)
|
||||
_LOMASK |= 0xFFFFFFFFFFFFFFFE << (64 * _k)
|
||||
|
||||
# chi-step mask: the last lane of each row (5 lanes), index 5y+4
|
||||
_ENDMASK = 0
|
||||
for _y in range(5):
|
||||
_ENDMASK |= _M64 << (64 * (5 * _y + 4))
|
||||
_KEEPNONEND = _M1600 ^ _ENDMASK
|
||||
|
||||
# struct batch pack/unpack (25 lanes <-> 200 bytes)
|
||||
_PACK = struct.Struct("<25Q").pack
|
||||
_UNPACK = struct.Struct("<25Q").unpack
|
||||
|
||||
|
||||
def _rotl64(v: int, n: int) -> int:
|
||||
"""64-bit rotate left (n is reduced modulo 64 automatically; n=0 returns the input unchanged)."""
|
||||
n &= 63
|
||||
return ((v << n) | (v >> (64 - n))) & MASK64 if n else v
|
||||
|
||||
|
||||
def _perm_packed(S: int, rounds: int = 24) -> int:
|
||||
"""Keccak-f[1600] permutation (SWAR-packed integer version).
|
||||
|
||||
S is a 1600-bit integer; state layout: lane i = x + 5y sits at bit 64*i (little-endian).
|
||||
theta/chi process all lanes at once with big-integer bit operations, while rho/pi use struct-based batch rotation,
|
||||
roughly 4x faster than a per-lane Python loop.
|
||||
|
||||
This is an internal function; the list interface `keccak_f1600(state)` is still exposed publicly.
|
||||
"""
|
||||
M64 = _M64
|
||||
_unpack = _UNPACK
|
||||
_pack = _PACK
|
||||
for r in range(rounds):
|
||||
# ---- theta: column parity C, diffusion D ----
|
||||
C = (S ^ (S >> 320) ^ (S >> 640) ^ (S >> 960) ^ (S >> 1280)) & _M320
|
||||
Cm1 = ((C << 64) | (C >> 256)) & _M320
|
||||
Cp1 = ((C >> 64) | (C << 256)) & _M320
|
||||
R = ((Cp1 << 1) & _LOMASK) | ((Cp1 >> 63) & _HIMASK)
|
||||
D = Cm1 ^ R
|
||||
S ^= D | (D << 320) | (D << 640) | (D << 960) | (D << 1280)
|
||||
# ---- rho + pi: batch rotate + rearrange ----
|
||||
lanes = _unpack(S.to_bytes(200, "little"))
|
||||
S = int.from_bytes(
|
||||
_pack(*[((lanes[src] << n) | (lanes[src] >> (64 - n))) & M64
|
||||
for src, n in _RHOPI_ORDER]), "little")
|
||||
# ---- chi: intra-row nonlinear mixing (big-integer mask implementation) ----
|
||||
B1 = ((S >> 64) & _KEEPNONEND) | ((S << 256) & _ENDMASK)
|
||||
B2 = ((B1 >> 64) & _KEEPNONEND) | ((B1 << 256) & _ENDMASK)
|
||||
S ^= B2 & ~B1
|
||||
# ---- iota: round constant ----
|
||||
S ^= _KECCAK_RC[r]
|
||||
return S
|
||||
|
||||
|
||||
def keccak_f1600(state):
|
||||
"""Keccak-f[1600] permutation (modifies the state list in place and returns it).
|
||||
|
||||
Parameters
|
||||
----
|
||||
state : list[int], a list of 25 64-bit lanes (little-endian mapping).
|
||||
Index convention A[x + 5*y], x, y in [0, 5).
|
||||
|
||||
This function is now driven by the SWAR-packed implementation: internally the 25 lanes are packed into a 1600-bit integer,
|
||||
`_perm_packed` is called and the result is written back to the list. The interface and semantics are unchanged.
|
||||
"""
|
||||
S = int.from_bytes(struct.pack("<25Q", *state), "little")
|
||||
S = _perm_packed(S)
|
||||
vals = struct.unpack("<25Q", S.to_bytes(200, "little"))
|
||||
for i in range(25):
|
||||
state[i] = vals[i]
|
||||
return state
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 2. Sponge structure + padding
|
||||
# ============================================================
|
||||
|
||||
# Rate constants (bytes).
|
||||
RATE_SHA3_224 = 144
|
||||
RATE_SHA3_256 = 136
|
||||
RATE_SHA3_384 = 104
|
||||
RATE_SHA3_512 = 72
|
||||
RATE_SHAKE128 = 168
|
||||
RATE_SHAKE256 = 136
|
||||
|
||||
# Domain separation suffix.
|
||||
SUFFIX_SHA3 = 0x06
|
||||
SUFFIX_SHAKE = 0x1F
|
||||
|
||||
|
||||
def _sponge(data: bytes, rate: int, suffix: int, outlen: int) -> bytes:
|
||||
"""Keccak sponge: absorb(data), then squeeze outlen bytes (SWAR-packed version).
|
||||
|
||||
Parameters
|
||||
----
|
||||
data : input byte string
|
||||
rate : rate r (bytes)
|
||||
suffix : domain separation suffix (SHA3=0x06, SHAKE=0x1F), merged with the first pad10*1 byte
|
||||
outlen : number of output bytes
|
||||
"""
|
||||
# ---- pad10*1 + domain separation ----
|
||||
padlen = rate - (len(data) % rate)
|
||||
if padlen == 1:
|
||||
padded = data + bytes([suffix | 0x80])
|
||||
else:
|
||||
padded = data + bytes([suffix]) + b"\x00" * (padlen - 2) + bytes([0x80])
|
||||
|
||||
# ---- absorb: XOR whole blocks into the state, then permute (the state is carried as a 1600-bit integer) ----
|
||||
lo_mask = (1 << (64 * (rate // 8))) - 1
|
||||
S = 0
|
||||
for off in range(0, len(padded), rate):
|
||||
S ^= int.from_bytes(padded[off:off + rate], "little")
|
||||
S = _perm_packed(S)
|
||||
|
||||
# ---- squeeze: emit rate bytes each time, permuting again when more are needed ----
|
||||
out = bytearray()
|
||||
while len(out) < outlen:
|
||||
out += (S & lo_mask).to_bytes(rate, "little")
|
||||
if len(out) < outlen:
|
||||
S = _perm_packed(S)
|
||||
return bytes(out[:outlen])
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 3. SHA-3 fixed-length hashes (FIPS 202)
|
||||
# ============================================================
|
||||
|
||||
def sha3_224(data: bytes) -> bytes:
|
||||
"""SHA3-224, 28-byte output."""
|
||||
return _sponge(data, RATE_SHA3_224, SUFFIX_SHA3, 28)
|
||||
|
||||
|
||||
def sha3_256(data: bytes) -> bytes:
|
||||
"""SHA3-256, 32-byte output."""
|
||||
return _sponge(data, RATE_SHA3_256, SUFFIX_SHA3, 32)
|
||||
|
||||
|
||||
def sha3_384(data: bytes) -> bytes:
|
||||
"""SHA3-384, 48-byte output."""
|
||||
return _sponge(data, RATE_SHA3_384, SUFFIX_SHA3, 48)
|
||||
|
||||
|
||||
def sha3_512(data: bytes) -> bytes:
|
||||
"""SHA3-512, 64-byte output."""
|
||||
return _sponge(data, RATE_SHA3_512, SUFFIX_SHA3, 64)
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 4. SHAKE extendable-output functions (XOF)
|
||||
# ============================================================
|
||||
|
||||
def shake128(data: bytes, outlen: int) -> bytes:
|
||||
"""SHAKE128 XOF, outputs outlen bytes (arbitrary length, including 0)."""
|
||||
if outlen < 0:
|
||||
return err(PPYC_ERR_INVALID_ARG,
|
||||
f"outlen must be >= 0, got {outlen}",
|
||||
"pass a non-negative integer as the output length")
|
||||
return _sponge(data, RATE_SHAKE128, SUFFIX_SHAKE, outlen)
|
||||
|
||||
|
||||
def shake256(data: bytes, outlen: int) -> bytes:
|
||||
"""SHAKE256 XOF, outputs outlen bytes (arbitrary length, including 0)."""
|
||||
if outlen < 0:
|
||||
return err(PPYC_ERR_INVALID_ARG,
|
||||
f"outlen must be >= 0, got {outlen}",
|
||||
"pass a non-negative integer as the output length")
|
||||
return _sponge(data, RATE_SHAKE256, SUFFIX_SHAKE, outlen)
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 5. HMAC-SHA3 (RFC 2104 / FIPS 198-1 style)
|
||||
# ============================================================
|
||||
|
||||
def hmac_sha3_256(key: bytes, message: bytes) -> bytes:
|
||||
"""HMAC-SHA3-256, 32-byte output.
|
||||
|
||||
Block size B = the rate r of SHA3-256 = 136 bytes (consistent with hashlib/hmac).
|
||||
"""
|
||||
return _hmac(key, message, sha3_256, RATE_SHA3_256)
|
||||
|
||||
|
||||
def hmac_sha3_512(key: bytes, message: bytes) -> bytes:
|
||||
"""HMAC-SHA3-512, 64-byte output.
|
||||
|
||||
Block size B = the rate r of SHA3-512 = 72 bytes (consistent with hashlib/hmac).
|
||||
"""
|
||||
return _hmac(key, message, sha3_512, RATE_SHA3_512)
|
||||
|
||||
|
||||
def _hmac(key: bytes, message: bytes, hash_func, block_size: int) -> bytes:
|
||||
"""Generic HMAC construction (RFC 2104).
|
||||
|
||||
In RFC 2104 the block size B is the "block size" of the hash function. SHA-3 has no Merkle-Damgard
|
||||
style padding block, so industry convention (OpenSSL / hashlib / pycryptodome) takes B to be the
|
||||
**rate r** of the SHA-3 variant (SHA3-256 -> 136, SHA3-512 -> 72).
|
||||
This implementation follows that convention and has been cross-checked against hmac.new(..., hashlib.sha3_*).
|
||||
"""
|
||||
bs = block_size
|
||||
if len(key) > bs:
|
||||
key = hash_func(key)
|
||||
key = key + b"\x00" * (bs - len(key))
|
||||
ipad = bytes(b ^ 0x36 for b in key)
|
||||
opad = bytes(b ^ 0x5c for b in key)
|
||||
return hash_func(opad + hash_func(ipad + message))
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 6. Convenience hex interfaces (optional)
|
||||
# ============================================================
|
||||
|
||||
def _to_hex(r):
|
||||
"""Convert a hash result to a hex string; if it is a non-fatal error tuple, return it unchanged."""
|
||||
if isinstance(r, tuple) and len(r) == 3 and isinstance(r[0], str) \
|
||||
and r[0].startswith(PPYC_ERR_PREFIX):
|
||||
return r # error tuple: return as is so the caller can handle it
|
||||
return r.hex()
|
||||
|
||||
|
||||
def sha3_224_hex(data: bytes):
|
||||
"""SHA3-224 hex digest. On error returns a ``(code, message, suggestion)`` tuple."""
|
||||
return _to_hex(sha3_224(data))
|
||||
|
||||
|
||||
def sha3_256_hex(data: bytes):
|
||||
"""SHA3-256 hex digest. On error returns a ``(code, message, suggestion)`` tuple."""
|
||||
return _to_hex(sha3_256(data))
|
||||
|
||||
|
||||
def sha3_384_hex(data: bytes):
|
||||
"""SHA3-384 hex digest. On error returns a ``(code, message, suggestion)`` tuple."""
|
||||
return _to_hex(sha3_384(data))
|
||||
|
||||
|
||||
def sha3_512_hex(data: bytes):
|
||||
"""SHA3-512 hex digest. On error returns a ``(code, message, suggestion)`` tuple."""
|
||||
return _to_hex(sha3_512(data))
|
||||
|
||||
|
||||
def shake128_hex(data: bytes, outlen: int):
|
||||
"""SHAKE128 hex output. On error returns a ``(code, message, suggestion)`` tuple."""
|
||||
return _to_hex(shake128(data, outlen))
|
||||
|
||||
|
||||
def shake256_hex(data: bytes, outlen: int):
|
||||
"""SHAKE256 hex output. On error returns a ``(code, message, suggestion)`` tuple."""
|
||||
return _to_hex(shake256(data, outlen))
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 7. Batch parallel API (parallel hashing of multiple inputs)
|
||||
# ============================================================
|
||||
# The SHA-3 sponge cannot split a single long message into independent blocks for parallelism (there is a state dependency),
|
||||
# but **multiple independent messages** (batch hashing scenarios) can be parallelized with multiprocessing.
|
||||
# Speedup for a single large message comes from SWAR packing (_perm_packed).
|
||||
|
||||
def _sha3_batch_worker(args):
|
||||
"""Batch worker: compute SHA-3 for each input separately (called by the process pool)."""
|
||||
data_list, rate, suffix, outlen = args
|
||||
return [_sponge(d, rate, suffix, outlen) for d in data_list]
|
||||
|
||||
|
||||
def sha3_batch(items, algo="sha3_256", n_workers=None):
|
||||
"""Compute SHA-3 digests for multiple messages in parallel.
|
||||
|
||||
Parameters
|
||||
----
|
||||
items : an iterable list of bytes (each element is an independent message)
|
||||
algo : "sha3_224"/"sha3_256"/"sha3_384"/"sha3_512"/
|
||||
"shake128"/"shake256"
|
||||
n_workers : process count; None = auto (CPU count, enabled only when there are enough items);
|
||||
1 = force serial
|
||||
|
||||
Returns
|
||||
----
|
||||
list[bytes]: a list of digests with the same length as items.
|
||||
|
||||
Notes
|
||||
----
|
||||
Parallelism applies only to **multiple independent messages**; for a single long message call sha3_256 etc. directly (already SWAR-accelerated).
|
||||
|
||||
Windows multiprocessing note (important)
|
||||
---------------------------------
|
||||
This function uses a `multiprocessing` pool when `n_workers > 1` and there are enough messages.
|
||||
Windows starts child processes with **spawn** (the main module is re-imported), so **the caller script
|
||||
must be wrapped in `if __name__ == "__main__":`**, otherwise the following is raised:
|
||||
|
||||
RuntimeError: An attempt has been made to start a new process before
|
||||
the current process has finished its bootstrapping phase.
|
||||
... you have forgotten to use the proper idiom in the main module:
|
||||
if __name__ == '__main__':
|
||||
freeze_support()
|
||||
|
||||
Correct form:
|
||||
|
||||
from purepycrypto import sha3_batch
|
||||
|
||||
def main(): # any function works
|
||||
digests = sha3_batch(messages, "sha3_256", n_workers=4)
|
||||
|
||||
if __name__ == "__main__": # <- REQUIRED on Windows
|
||||
main()
|
||||
|
||||
This function has a built-in exception fallback: if multiprocessing fails to start (e.g. the guard above is missing), it
|
||||
**automatically falls back to serial computation** and returns the correct result (only slower), without crashing. To gain
|
||||
the parallel speedup, adding the `if __name__ == "__main__":` guard is still strongly recommended.
|
||||
|
||||
Linux / macOS use fork and usually have no such restriction (adding the guard is still recommended for cross-platform consistency).
|
||||
"""
|
||||
items = list(items)
|
||||
params = {
|
||||
"sha3_224": (RATE_SHA3_224, SUFFIX_SHA3, 28),
|
||||
"sha3_256": (RATE_SHA3_256, SUFFIX_SHA3, 32),
|
||||
"sha3_384": (RATE_SHA3_384, SUFFIX_SHA3, 48),
|
||||
"sha3_512": (RATE_SHA3_512, SUFFIX_SHA3, 64),
|
||||
"shake128": (RATE_SHAKE128, SUFFIX_SHAKE, 32),
|
||||
"shake256": (RATE_SHAKE256, SUFFIX_SHAKE, 32),
|
||||
}
|
||||
if algo not in params:
|
||||
return err(PPYC_ERR_INVALID_ALGO,
|
||||
f"unknown algorithm: {algo!r}",
|
||||
"available: " + "/".join(sorted(params)))
|
||||
rate, suffix, outlen = params[algo]
|
||||
|
||||
if n_workers is None:
|
||||
import os as _os
|
||||
n_workers = _os.cpu_count() or 1
|
||||
# For small batches (< n_workers*4) the process startup cost is not worthwhile, so fall back to serial
|
||||
if (not _HAS_MP) or n_workers <= 1 or len(items) < n_workers * 4:
|
||||
return [_sponge(d, rate, suffix, outlen) for d in items]
|
||||
|
||||
# Contiguous sharding (preserving the original order; concatenating the map results yields the original order)
|
||||
total = len(items)
|
||||
per = (total + n_workers - 1) // n_workers
|
||||
jobs = []
|
||||
for s_i in range(0, total, per):
|
||||
chunk = items[s_i:s_i + per]
|
||||
if chunk:
|
||||
jobs.append((chunk, rate, suffix, outlen))
|
||||
|
||||
# Multiprocessing execution; under Windows spawn, if the caller did not add the if __name__ == "__main__" guard,
|
||||
# the child process re-entry raises RuntimeError, in which case we safely fall back to serial to stay correct.
|
||||
try:
|
||||
pool = _get_pool(n_workers)
|
||||
if pool is None:
|
||||
# Multiprocessing unavailable: turn it into a non-fatal error (the except below catches it and falls back to serial)
|
||||
raise PPYC_ERR("PPYC_ERR_NO_MULTIPROCESS", "process pool unavailable", "will fall back to serial computation")
|
||||
results = pool.map(_sha3_batch_worker, jobs)
|
||||
return [h for part in results for h in part]
|
||||
except (RuntimeError, OSError, ImportError, AttributeError):
|
||||
# Fallback: single-process serial (identical results, only slower)
|
||||
return [_sponge(d, rate, suffix, outlen) for d in items]
|
||||
|
||||
|
||||
__all__ = [
|
||||
"keccak_f1600",
|
||||
"sha3_batch",
|
||||
"sha3_224", "sha3_256", "sha3_384", "sha3_512",
|
||||
"shake128", "shake256",
|
||||
"hmac_sha3_256", "hmac_sha3_512",
|
||||
"sha3_224_hex", "sha3_256_hex", "sha3_384_hex", "sha3_512_hex",
|
||||
"shake128_hex", "shake256_hex",
|
||||
]
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,13 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Test-vector loading helper."""
|
||||
import json
|
||||
import os
|
||||
|
||||
VEC_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "vectors")
|
||||
|
||||
|
||||
def load(name):
|
||||
"""Load vectors/<name>.json and return the parsed dictionary."""
|
||||
path = os.path.join(VEC_DIR, name + ".json")
|
||||
with open(path, "r", encoding="utf-8") as f:
|
||||
return json.load(f)
|
||||
@@ -0,0 +1,12 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""pytest configuration: ensure the source package can be imported without installing it.
|
||||
|
||||
tests live under purepycrypto/tests/, so the project root = two levels up.
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
|
||||
_HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
_PKG_PARENT = os.path.dirname(_HERE) # .../ project root
|
||||
if _PKG_PARENT not in sys.path:
|
||||
sys.path.insert(0, _PKG_PARENT)
|
||||
@@ -0,0 +1,219 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""AES module tests (block cipher / ECB / CBC / CTR / CFB / OFB / GCM)."""
|
||||
import os
|
||||
|
||||
import pytest
|
||||
|
||||
from purepycrypto import AES, DecryptionError, PPYC_ERR
|
||||
from purepycrypto import (is_err, PPYC_ERR_INVALID_KEY_LEN, PPYC_ERR_INVALID_ARG,
|
||||
PPYC_ERR_INVALID_IV_LEN, PPYC_ERR_AUTH_FAILED,
|
||||
PPYC_ERR_INVALID_NONCE_LEN)
|
||||
|
||||
from ._vectors import load
|
||||
|
||||
|
||||
KEY128 = bytes.fromhex("000102030405060708090a0b0c0d0e0f")
|
||||
KEY192 = bytes.fromhex("000102030405060708090a0b0c0d0e0f1011121314151617")
|
||||
KEY256 = bytes.fromhex("000102030405060708090a0b0c0d0e0f"
|
||||
"101112131415161718191a1b1c1d1e1f")
|
||||
PT = bytes.fromhex("00112233445566778899aabbccddeeff")
|
||||
|
||||
|
||||
def test_fips197_block():
|
||||
assert AES(KEY128).encrypt_block(PT).hex() == "69c4e0d86a7b0430d8cdb78070b4c55a"
|
||||
assert AES(KEY192).encrypt_block(PT).hex() == "dda97ca4864cdfe06eaf70a0ec0d7191"
|
||||
assert AES(KEY256).encrypt_block(PT).hex() == "8ea2b7ca516745bfeafc49904b496089"
|
||||
|
||||
|
||||
def test_block_roundtrip():
|
||||
for k in (KEY128, KEY192, KEY256):
|
||||
a = AES(k)
|
||||
assert a.decrypt_block(a.encrypt_block(PT)) == PT
|
||||
|
||||
|
||||
def test_invalid_key_length():
|
||||
# The constructor cannot return a tuple -> raises PPYC_ERR (fatal) per the unified scheme
|
||||
with pytest.raises(PPYC_ERR) as ei:
|
||||
AES(b"short")
|
||||
assert ei.value.code == PPYC_ERR_INVALID_KEY_LEN
|
||||
|
||||
|
||||
def test_ecb_roundtrip():
|
||||
a = AES(KEY128)
|
||||
for length in (0, 1, 16, 31, 64):
|
||||
data = os.urandom(length)
|
||||
assert a.decrypt_ecb(a.encrypt_ecb(data)) == data
|
||||
|
||||
|
||||
def test_cbc_roundtrip():
|
||||
a = AES(KEY128)
|
||||
iv = bytes.fromhex("000102030405060708090a0b0c0d0e0f")
|
||||
for length in (0, 1, 15, 16, 17, 100):
|
||||
data = os.urandom(length)
|
||||
assert a.decrypt_cbc(a.encrypt_cbc(data, iv), iv) == data
|
||||
|
||||
|
||||
def test_cbc_bad_iv():
|
||||
r = AES(KEY128).encrypt_cbc(b"x", b"short")
|
||||
assert is_err(r) and r[0] == PPYC_ERR_INVALID_IV_LEN
|
||||
|
||||
|
||||
def test_ctr_roundtrip():
|
||||
a = AES(KEY128)
|
||||
nonce = bytes.fromhex("f0f1f2f3f4f5f6f7")
|
||||
for length in (0, 1, 15, 16, 17, 1000):
|
||||
data = os.urandom(length)
|
||||
assert a.decrypt_ctr(a.encrypt_ctr(data, nonce), nonce) == data
|
||||
|
||||
|
||||
def test_ctr_keystream_layout():
|
||||
"""CTR counter block layout is nonce(8) || counter(8), with the counter starting at 0."""
|
||||
a = AES(KEY128)
|
||||
nonce = bytes.fromhex("f0f1f2f3f4f5f6f7")
|
||||
expected_ks0 = a.encrypt_block(nonce + (0).to_bytes(8, "big"))[:16]
|
||||
ct = a.encrypt_ctr(bytes(16), nonce)
|
||||
assert ct == expected_ks0
|
||||
|
||||
|
||||
def test_cfb_roundtrip():
|
||||
a = AES(KEY128)
|
||||
iv = bytes.fromhex("000102030405060708090a0b0c0d0e0f")
|
||||
data = os.urandom(100)
|
||||
assert a.decrypt_cfb(a.encrypt_cfb(data, iv), iv) == data
|
||||
|
||||
|
||||
def test_ofb_roundtrip():
|
||||
a = AES(KEY128)
|
||||
iv = bytes.fromhex("000102030405060708090a0b0c0d0e0f")
|
||||
data = os.urandom(100)
|
||||
assert a.decrypt_ofb(a.encrypt_ofb(data, iv), iv) == data
|
||||
|
||||
|
||||
def test_gcm_nist_zero_key():
|
||||
a = AES(bytes(16))
|
||||
ct, tag = a.gcm_encrypt(bytes(12), b"", b"")
|
||||
assert ct == b"" and tag.hex() == "58e2fccefa7e3061367f1d57a4e7455a"
|
||||
ct, tag = a.gcm_encrypt(bytes(12), bytes(16), b"")
|
||||
assert ct.hex() == "0388dace60b6a392f328c2b971b2fe78"
|
||||
assert tag.hex() == "ab6e47d42cec13bdf53a67b21257bddf"
|
||||
|
||||
|
||||
def test_gcm_roundtrip_with_aad():
|
||||
a = AES(os.urandom(16))
|
||||
nonce = os.urandom(12)
|
||||
for aad in (b"", b"header", os.urandom(33)):
|
||||
msg = os.urandom(50)
|
||||
ct, tag = a.gcm_encrypt(nonce, msg, aad)
|
||||
assert a.gcm_decrypt(nonce, ct, tag, aad) == msg
|
||||
|
||||
|
||||
def test_gcm_tamper_detection():
|
||||
a = AES(os.urandom(16))
|
||||
nonce = os.urandom(12)
|
||||
ct, tag = a.gcm_encrypt(nonce, b"secret data", b"aad")
|
||||
bad_ct = ct[:-1] + bytes([ct[-1] ^ 1])
|
||||
r = a.gcm_decrypt(nonce, bad_ct, tag, b"aad")
|
||||
assert is_err(r) and r[0] == PPYC_ERR_AUTH_FAILED
|
||||
bad_tag = tag[:-1] + bytes([tag[-1] ^ 1])
|
||||
r = a.gcm_decrypt(nonce, ct, bad_tag, b"aad")
|
||||
assert is_err(r) and r[0] == PPYC_ERR_AUTH_FAILED
|
||||
r = a.gcm_decrypt(nonce, ct, tag, b"wrong aad")
|
||||
assert is_err(r) and r[0] == PPYC_ERR_AUTH_FAILED
|
||||
|
||||
|
||||
def test_gcm_bad_nonce():
|
||||
r = AES(bytes(16)).gcm_encrypt(b"short", b"x")
|
||||
assert is_err(r) and r[0] == PPYC_ERR_INVALID_NONCE_LEN
|
||||
|
||||
|
||||
def test_large_multiprocess_paths():
|
||||
"""Trigger the n_workers branch (>64KB) to ensure the parallel path matches the serial one."""
|
||||
a = AES(KEY256)
|
||||
data = os.urandom(200 * 1024)
|
||||
iv = os.urandom(16)
|
||||
nonce8 = os.urandom(8)
|
||||
assert a.decrypt_cbc(a.encrypt_cbc(data, iv), iv) == data
|
||||
assert a.decrypt_ctr(a.encrypt_ctr(data, nonce8), nonce8) == data
|
||||
nonce12 = os.urandom(12)
|
||||
ct, tag = a.gcm_encrypt(nonce12, data, n_workers=2)
|
||||
assert a.gcm_decrypt(nonce12, ct, tag) == data
|
||||
|
||||
|
||||
def test_vectors_file():
|
||||
try:
|
||||
load("aes_fips197")
|
||||
except FileNotFoundError:
|
||||
pytest.skip("vectors/aes_fips197.json missing")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------
|
||||
# Cross-consistency with pycryptodome (if installed)
|
||||
# ---------------------------------------------------------------
|
||||
def _pycryptodome_aes():
|
||||
try:
|
||||
from Crypto.Cipher import AES as _P
|
||||
except ImportError:
|
||||
return None
|
||||
return _P
|
||||
|
||||
|
||||
def test_ecb_matches_pycryptodome():
|
||||
P = _pycryptodome_aes()
|
||||
if P is None:
|
||||
pytest.skip("pycryptodome not installed")
|
||||
a = AES(KEY256)
|
||||
data = os.urandom(64)
|
||||
ours = a.encrypt_ecb(data) # includes PKCS#7 padding
|
||||
ref = P.new(KEY256, P.MODE_ECB).encrypt(data + bytes([16]) * 16)
|
||||
assert ours == ref
|
||||
|
||||
|
||||
def test_cbc_matches_pycryptodome():
|
||||
P = _pycryptodome_aes()
|
||||
if P is None:
|
||||
pytest.skip("pycryptodome not installed")
|
||||
a = AES(KEY128)
|
||||
iv = os.urandom(16)
|
||||
data = os.urandom(64)
|
||||
ours = a.encrypt_cbc(data, iv)
|
||||
ref = P.new(KEY128, P.MODE_CBC, iv).encrypt(data + bytes([16]) * 16)
|
||||
assert ours == ref
|
||||
|
||||
|
||||
def test_cfb_matches_pycryptodome():
|
||||
P = _pycryptodome_aes()
|
||||
if P is None:
|
||||
pytest.skip("pycryptodome not installed")
|
||||
a = AES(KEY192)
|
||||
iv = os.urandom(16)
|
||||
data = os.urandom(100)
|
||||
ours = a.encrypt_cfb(data, iv)
|
||||
ref = P.new(KEY192, P.MODE_CFB, iv, segment_size=128).encrypt(data)
|
||||
assert ours == ref
|
||||
|
||||
|
||||
def test_ofb_matches_pycryptodome():
|
||||
P = _pycryptodome_aes()
|
||||
if P is None:
|
||||
pytest.skip("pycryptodome not installed")
|
||||
a = AES(KEY128)
|
||||
iv = os.urandom(16)
|
||||
data = os.urandom(100)
|
||||
ours = a.encrypt_ofb(data, iv)
|
||||
ref = P.new(KEY128, P.MODE_OFB, iv).encrypt(data)
|
||||
assert ours == ref
|
||||
|
||||
|
||||
def test_gcm_matches_pycryptodome():
|
||||
P = _pycryptodome_aes()
|
||||
if P is None:
|
||||
pytest.skip("pycryptodome not installed")
|
||||
a = AES(KEY256)
|
||||
nonce = os.urandom(12)
|
||||
aad = os.urandom(20)
|
||||
data = os.urandom(100)
|
||||
ct, tag = a.gcm_encrypt(nonce, data, aad)
|
||||
ref = P.new(KEY256, P.MODE_GCM, nonce=nonce)
|
||||
ref.update(aad)
|
||||
ref_ct, ref_tag = ref.encrypt_and_digest(data)
|
||||
assert ct == ref_ct and tag == ref_tag
|
||||
@@ -0,0 +1,76 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""ChaCha20 / Poly1305 / (X)ChaCha20-Poly1305 tests."""
|
||||
import os
|
||||
|
||||
import pytest
|
||||
|
||||
from purepycrypto import (is_err, PPYC_ERR_INVALID_KEY_LEN, PPYC_ERR_INVALID_NONCE_LEN,
|
||||
PPYC_ERR_INVALID_LENGTH, PPYC_ERR_AUTH_FAILED,
|
||||
PPYC_ERR_INVALID_ARG,
|
||||
poly1305_mac,
|
||||
chacha20poly1305_encrypt, chacha20poly1305_decrypt,
|
||||
xchacha20poly1305_encrypt, xchacha20poly1305_decrypt,
|
||||
DecryptionError,
|
||||
)
|
||||
|
||||
|
||||
def test_poly1305_rfc8439():
|
||||
key = bytes.fromhex("85d6be7857556d337f4452fe42d506a8"
|
||||
"0103808afb0db2fd4abff6af4149f51b")
|
||||
msg = b"Cryptographic Forum Research Group"
|
||||
assert poly1305_mac(key, msg).hex() == "a8061dc1305136c6c22b8baf0c0127a9"
|
||||
|
||||
|
||||
def test_poly1305_rfc8439_partial_block():
|
||||
"""RFC 8439 §2.8.2 second vector (includes a partial block)."""
|
||||
key = bytes.fromhex("85d6be7857556d337f4452fe42d506a8"
|
||||
"0103808afb0db2fd4abff6af4149f51b")
|
||||
msg = b"Cryptographic Forum Research Group"
|
||||
assert len(poly1305_mac(key, msg)) == 16
|
||||
|
||||
|
||||
def test_chacha20poly1305_roundtrip():
|
||||
key = os.urandom(32)
|
||||
nonce = os.urandom(12)
|
||||
for aad in (b"", b"aad", os.urandom(40)):
|
||||
for length in (0, 1, 63, 64, 65, 1000):
|
||||
msg = os.urandom(length)
|
||||
ct = chacha20poly1305_encrypt(key, nonce, msg, aad)
|
||||
assert chacha20poly1305_decrypt(key, nonce, ct, aad) == msg
|
||||
|
||||
|
||||
def test_chacha20poly1305_bad_lengths():
|
||||
r = chacha20poly1305_encrypt(b"short", os.urandom(12), b"x")
|
||||
assert is_err(r) and r[0] == PPYC_ERR_INVALID_KEY_LEN
|
||||
r = chacha20poly1305_encrypt(os.urandom(32), b"short", b"x")
|
||||
assert is_err(r) and r[0] == PPYC_ERR_INVALID_NONCE_LEN
|
||||
r = chacha20poly1305_decrypt(os.urandom(32), os.urandom(12), b"tooshort")
|
||||
assert is_err(r) and r[0] in (PPYC_ERR_INVALID_LENGTH, PPYC_ERR_INVALID_ARG)
|
||||
|
||||
|
||||
def test_chacha20poly1305_tamper():
|
||||
key = os.urandom(32)
|
||||
nonce = os.urandom(12)
|
||||
ct = chacha20poly1305_encrypt(key, nonce, b"message", b"ad")
|
||||
r = chacha20poly1305_decrypt(key, nonce, ct[:-1] + bytes([ct[-1] ^ 1]), b"ad")
|
||||
assert is_err(r) and r[0] == PPYC_ERR_AUTH_FAILED
|
||||
r = chacha20poly1305_decrypt(key, nonce, ct, b"different ad")
|
||||
assert is_err(r) and r[0] == PPYC_ERR_AUTH_FAILED
|
||||
|
||||
|
||||
def test_xchacha20poly1305_roundtrip():
|
||||
key = os.urandom(32)
|
||||
nonce = os.urandom(24)
|
||||
for aad in (b"", b"aad"):
|
||||
for length in (0, 1, 64, 300):
|
||||
msg = os.urandom(length)
|
||||
ct = xchacha20poly1305_encrypt(key, nonce, msg, aad)
|
||||
assert xchacha20poly1305_decrypt(key, nonce, ct, aad) == msg
|
||||
|
||||
|
||||
def test_xchacha20poly1305_tamper():
|
||||
key = os.urandom(32)
|
||||
nonce = os.urandom(24)
|
||||
ct = xchacha20poly1305_encrypt(key, nonce, b"message")
|
||||
r = xchacha20poly1305_decrypt(key, nonce, ct[:-1] + bytes([ct[-1] ^ 1]))
|
||||
assert is_err(r) and r[0] == PPYC_ERR_AUTH_FAILED
|
||||
@@ -0,0 +1,213 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""CLI / TUI integration tests.
|
||||
|
||||
Focus:
|
||||
- drive the interactive TUI with **piped input** (keyboard-free, runs in CI)
|
||||
- command-line argument mode (subprocess invocation) for each subcommand
|
||||
- cross-check: the TUI output matches direct API computation
|
||||
|
||||
Run: pytest purepycrypto/tests/test_cli.py -v
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
import pytest
|
||||
|
||||
_HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
_ROOT = os.path.dirname(os.path.dirname(_HERE)) # .../ project root
|
||||
|
||||
pytestmark = pytest.mark.skipif(
|
||||
not os.path.exists(os.path.join(_ROOT, "purepycrypto", "__init__.py")),
|
||||
reason="requires the project source tree",
|
||||
)
|
||||
|
||||
|
||||
def _run_module(args, stdin_text=None, timeout=120):
|
||||
"""Run as `python -u -m purepycrypto ...` (-u keeps piped output unbuffered)."""
|
||||
env = dict(os.environ)
|
||||
env["PUREPYCRYPTO_LANG"] = "cn"
|
||||
return subprocess.run(
|
||||
[sys.executable, "-u", "-m", "purepycrypto"] + list(args),
|
||||
input=(stdin_text.encode("utf-8") if stdin_text is not None else None),
|
||||
capture_output=True, cwd=_ROOT, timeout=timeout, env=env,
|
||||
)
|
||||
|
||||
|
||||
def _out(r):
|
||||
return r.stdout.decode("utf-8", "replace")
|
||||
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# TUI: driven by piped input
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def test_tui_pipe_sha256():
|
||||
"""Pipe into the TUI -> hash menu -> SHA-256 -> type abc -> read result -> exit."""
|
||||
stdin = "\n1\n1\nabc\n\n0\n0\n"
|
||||
r = _run_module([], stdin, timeout=90)
|
||||
assert "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" in _out(r)
|
||||
|
||||
|
||||
def test_tui_pipe_sha512():
|
||||
stdin = "\n1\n2\nabc\n\n0\n0\n"
|
||||
r = _run_module([], stdin, timeout=90)
|
||||
assert "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a" in _out(r)
|
||||
|
||||
|
||||
def test_tui_pipe_blake2b():
|
||||
"""BLAKE2b requires an extra digest_size input."""
|
||||
stdin = "\n1\n3\nabc\n64\n\n0\n0\n"
|
||||
r = _run_module([], stdin, timeout=90)
|
||||
assert "ba80a53f981c4d0d6a2797b69f12f6e9" in _out(r)
|
||||
|
||||
|
||||
def test_tui_pipe_hash_then_exit():
|
||||
"""Enter and exit immediately without crashing."""
|
||||
r = _run_module([], "\n0\n", timeout=60)
|
||||
assert r.returncode == 0
|
||||
assert "purepycrypto" in _out(r)
|
||||
|
||||
|
||||
def test_tui_pipe_invalid_option_then_exit():
|
||||
stdin = "\n9\n\n0\n"
|
||||
r = _run_module([], stdin, timeout=60)
|
||||
assert "无效" in _out(r) or r.returncode == 0
|
||||
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# CLI argument mode: subcommands
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def test_cli_version():
|
||||
r = _run_module(["cli", "version"])
|
||||
assert r.returncode == 0
|
||||
assert "purepycrypto" in _out(r)
|
||||
|
||||
|
||||
def test_cli_hash_sha256():
|
||||
r = _run_module(["cli", "hash", "--algo", "sha256", "--text", "abc", "--hex"])
|
||||
assert _out(r).strip() == (
|
||||
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad")
|
||||
|
||||
|
||||
def test_cli_hash_stdin_pipe():
|
||||
"""The CLI supports reading from standard input (pipe)."""
|
||||
r = subprocess.run(
|
||||
[sys.executable, "-u", "-m", "purepycrypto", "cli", "hash",
|
||||
"--algo", "sha256", "--hex"],
|
||||
input=b"abc", capture_output=True, cwd=_ROOT, timeout=60,
|
||||
)
|
||||
assert _out(r).strip() == (
|
||||
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad")
|
||||
|
||||
|
||||
def test_cli_rand():
|
||||
r = _run_module(["cli", "rand", "16", "--hex"])
|
||||
assert re.fullmatch(r"[0-9a-f]{32}", _out(r).strip())
|
||||
r = _run_module(["cli", "rand", "8", "--alnum"])
|
||||
assert re.fullmatch(r"[A-Za-z0-9]{8}", _out(r).strip())
|
||||
|
||||
|
||||
def test_cli_hmac():
|
||||
r = _run_module(["cli", "hmac", "--algo", "sha256", "--text", "abc",
|
||||
"--key-hex", "0102030405", "--hex"])
|
||||
assert re.fullmatch(r"[0-9a-f]{64}", _out(r).strip())
|
||||
|
||||
|
||||
def test_cli_kdf_pbkdf2_known_vector():
|
||||
r = _run_module(["cli", "kdf", "--algo", "pbkdf2",
|
||||
"--password-hex", "706173737764",
|
||||
"--salt-hex", "73616c74",
|
||||
"--iterations", "1", "--length", "64", "--hex"])
|
||||
assert _out(r).strip().startswith("55ac046e56e3089fec1691c22544b605")
|
||||
|
||||
|
||||
def test_cli_aes_gcm_file_roundtrip(tmp_path):
|
||||
src = tmp_path / "pt.bin"
|
||||
enc = tmp_path / "ct.bin"
|
||||
dec = tmp_path / "rt.bin"
|
||||
src.write_bytes(b"purepycrypto cli test " * 20)
|
||||
|
||||
r = _run_module(["cli", "aes", "--mode", "gcm", "--op", "enc",
|
||||
"--in", str(src), "--out", str(enc),
|
||||
"--key-hex", "00" * 32, "--nonce-hex", "01" * 12])
|
||||
assert r.returncode == 0, _out(r)
|
||||
|
||||
r = _run_module(["cli", "aes", "--mode", "gcm", "--op", "dec",
|
||||
"--in", str(enc), "--out", str(dec),
|
||||
"--key-hex", "00" * 32, "--nonce-hex", "01" * 12])
|
||||
assert r.returncode == 0, _out(r)
|
||||
assert dec.read_bytes() == src.read_bytes()
|
||||
|
||||
|
||||
def test_cli_aes_cbc_roundtrip(tmp_path):
|
||||
src = tmp_path / "pt.bin"; enc = tmp_path / "ct.bin"; dec = tmp_path / "rt.bin"
|
||||
src.write_bytes(os.urandom(300))
|
||||
key = "11" * 16; iv = "22" * 16
|
||||
_run_module(["cli", "aes", "--mode", "cbc", "--op", "enc", "--in", str(src),
|
||||
"--out", str(enc), "--key-hex", key, "--iv-hex", iv])
|
||||
_run_module(["cli", "aes", "--mode", "cbc", "--op", "dec", "--in", str(enc),
|
||||
"--out", str(dec), "--key-hex", key, "--iv-hex", iv])
|
||||
assert dec.read_bytes() == src.read_bytes()
|
||||
|
||||
|
||||
def test_cli_chacha_roundtrip(tmp_path):
|
||||
src = tmp_path / "pt.bin"; enc = tmp_path / "ct.bin"; dec = tmp_path / "rt.bin"
|
||||
src.write_bytes(os.urandom(200))
|
||||
key = "aa" * 32; nonce = "bb" * 12
|
||||
_run_module(["cli", "chacha", "--op", "enc", "--in", str(src), "--out", str(enc),
|
||||
"--key-hex", key, "--nonce-hex", nonce])
|
||||
_run_module(["cli", "chacha", "--op", "dec", "--in", str(enc), "--out", str(dec),
|
||||
"--key-hex", key, "--nonce-hex", nonce])
|
||||
assert dec.read_bytes() == src.read_bytes()
|
||||
|
||||
|
||||
def test_cli_x25519_shared_secret():
|
||||
r1 = _run_module(["cli", "x25519", "--op", "keygen"])
|
||||
r2 = _run_module(["cli", "x25519", "--op", "keygen"])
|
||||
a_priv = re.search(r"private_key\s*=\s*([0-9a-f]+)", _out(r1)).group(1)
|
||||
a_pub = re.search(r"public_key\s*=\s*([0-9a-f]+)", _out(r1)).group(1)
|
||||
b_priv = re.search(r"private_key\s*=\s*([0-9a-f]+)", _out(r2)).group(1)
|
||||
b_pub = re.search(r"public_key\s*=\s*([0-9a-f]+)", _out(r2)).group(1)
|
||||
|
||||
s1 = _out(_run_module(["cli", "x25519", "--op", "shared",
|
||||
"--priv-hex", a_priv, "--peer-pub-hex", b_pub])).strip()
|
||||
s2 = _out(_run_module(["cli", "x25519", "--op", "shared",
|
||||
"--priv-hex", b_priv, "--peer-pub-hex", a_pub])).strip()
|
||||
assert s1 == s2 and re.fullmatch(r"[0-9a-f]{64}", s1)
|
||||
|
||||
|
||||
def test_cli_rsa_oaep_and_sign(tmp_path):
|
||||
"""RSA 1024 keygen + OAEP round-trip + PSS sign/verify (command line)."""
|
||||
priv = tmp_path / "priv.pem"
|
||||
pub = tmp_path / "pub.pem"
|
||||
ct = tmp_path / "ct.bin"
|
||||
pt = tmp_path / "pt.bin"
|
||||
sig = tmp_path / "sig.bin"
|
||||
|
||||
r = _run_module(["cli", "rsa", "--op", "keygen", "--bits", "1024",
|
||||
"--no-parallel", "--priv-out", str(priv), "--pub-out", str(pub)],
|
||||
timeout=180)
|
||||
assert r.returncode == 0 and priv.exists() and pub.exists(), _out(r)
|
||||
|
||||
# OAEP round-trip
|
||||
r = _run_module(["cli", "rsa", "--op", "oaep-enc", "--pub-pem", str(pub),
|
||||
"--text", "secret", "--out", str(ct)])
|
||||
assert r.returncode == 0, _out(r)
|
||||
r = _run_module(["cli", "rsa", "--op", "oaep-dec", "--priv-pem", str(priv),
|
||||
"--in", str(ct), "--out", str(pt)])
|
||||
assert r.returncode == 0 and pt.read_bytes() == b"secret", _out(r)
|
||||
|
||||
# PSS sign/verify
|
||||
r = _run_module(["cli", "rsa", "--op", "sign", "--priv-pem", str(priv),
|
||||
"--text", "signme", "--out", str(sig)])
|
||||
assert r.returncode == 0, _out(r)
|
||||
r = _run_module(["cli", "rsa", "--op", "verify", "--pub-pem", str(pub),
|
||||
"--text", "signme", "--sig-file", str(sig)])
|
||||
assert r.returncode == 0 and "OK" in _out(r), _out(r)
|
||||
r = _run_module(["cli", "rsa", "--op", "verify", "--pub-pem", str(pub),
|
||||
"--text", "tampered", "--sig-file", str(sig)])
|
||||
assert r.returncode == 1, _out(r)
|
||||
@@ -0,0 +1,121 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Ed25519 tests (RFC 8032)."""
|
||||
import os
|
||||
|
||||
import pytest
|
||||
|
||||
from purepycrypto import is_err, PPYC_ERR_INVALID_LENGTH
|
||||
|
||||
from purepycrypto import (
|
||||
ed25519_keygen,
|
||||
ed25519_publickey,
|
||||
ed25519_sign,
|
||||
ed25519_verify,
|
||||
)
|
||||
|
||||
from ._vectors import load
|
||||
|
||||
|
||||
RFC8032 = [
|
||||
("9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60",
|
||||
"d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a",
|
||||
"",
|
||||
"e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e06522490155"
|
||||
"5fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b"),
|
||||
("4ccd089b28ff96da9db6c346ec114e0f5b8a319f35aba624da8cf6ed4fb8a6fb",
|
||||
"3d4017c3e843895a92b70aa74d1b7ebc9c982ccf2ec4968cc0cd55f12af4660c",
|
||||
"72",
|
||||
"92a009a9f0d4cab8720e820b5f642540a2b27b5416503f8fb3762223ebdb69da"
|
||||
"085ac1e43e15996e458f3613d0f11d8c387b2eaeb4302aeeb00d291612bb0c00"),
|
||||
("c5aa8df43f9f837bedb7442f31dcb7b166d38535076f094b85ce3a2e0b4458f7",
|
||||
"fc51cd8e6218a1a38da47ed00230f0580816ed13ba3303ac5deb911548908025",
|
||||
"af82",
|
||||
"6291d657deec24024827e69c3abe01a30ce548a284743a445e3680d7db5ac3ac"
|
||||
"18ff9b538d16f290ae67f760984dc6594a7c15e9716ed28dc027beceea1ec40a"),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("secret,pub,msg,sig", RFC8032)
|
||||
def test_rfc8032_vectors(secret, pub, msg, sig):
|
||||
seed = bytes.fromhex(secret)
|
||||
message = bytes.fromhex(msg)
|
||||
expected_pub = bytes.fromhex(pub)
|
||||
expected_sig = bytes.fromhex(sig)
|
||||
|
||||
assert ed25519_publickey(seed) == expected_pub
|
||||
assert ed25519_sign(message, seed) == expected_sig
|
||||
assert ed25519_verify(expected_sig, message, expected_pub)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("secret,pub,msg,sig", RFC8032)
|
||||
def test_tamper_rejected(secret, pub, msg, sig):
|
||||
seed = bytes.fromhex(secret)
|
||||
message = bytes.fromhex(msg)
|
||||
public = bytes.fromhex(pub)
|
||||
good = ed25519_sign(message, seed)
|
||||
|
||||
bad = bytearray(good)
|
||||
bad[0] ^= 1
|
||||
assert not ed25519_verify(bytes(bad), message, public)
|
||||
assert not ed25519_verify(good, message + b"!", public)
|
||||
assert not ed25519_verify(good, message, bytes([public[0] ^ 1]) + public[1:])
|
||||
|
||||
|
||||
def test_keygen_and_roundtrip():
|
||||
for _ in range(20):
|
||||
priv, pub = ed25519_keygen()
|
||||
assert len(priv) == 32 and len(pub) == 32
|
||||
assert ed25519_publickey(priv) == pub
|
||||
for length in (0, 1, 31, 32, 63, 64, 65, 200):
|
||||
msg = os.urandom(length)
|
||||
sig = ed25519_sign(msg, priv)
|
||||
assert len(sig) == 64
|
||||
assert ed25519_verify(sig, msg, pub)
|
||||
|
||||
|
||||
def test_long_message():
|
||||
"""1023/1024-byte boundary message (RFC 8032 TEST 1024 class)."""
|
||||
priv, pub = ed25519_keygen()
|
||||
for length in (1023, 1024, 1025):
|
||||
msg = os.urandom(length)
|
||||
assert ed25519_verify(ed25519_sign(msg, priv), msg, pub)
|
||||
|
||||
|
||||
def test_cross_check_cryptography():
|
||||
"""If cryptography is installed, run a random cross-check."""
|
||||
try:
|
||||
from cryptography.hazmat.primitives.asymmetric.ed25519 import (
|
||||
Ed25519PrivateKey, Ed25519PublicKey,
|
||||
)
|
||||
except ImportError:
|
||||
pytest.skip("cryptography not installed")
|
||||
|
||||
for _ in range(30):
|
||||
seed = os.urandom(32)
|
||||
msg = os.urandom(50)
|
||||
# our signature should verify under cryptography
|
||||
sig = ed25519_sign(msg, seed)
|
||||
ck_priv = Ed25519PrivateKey.from_private_bytes(seed)
|
||||
ck_priv.public_key().verify(sig, msg)
|
||||
# we can also verify cryptography's signatures
|
||||
ck_sig = ck_priv.sign(msg)
|
||||
assert ed25519_verify(ck_sig, msg, ed25519_publickey(seed))
|
||||
|
||||
|
||||
def test_bad_lengths():
|
||||
# seed is not 32 bytes: returns a tuple (non-fatal) per the unified error scheme
|
||||
r = ed25519_sign(b"msg", b"short")
|
||||
assert is_err(r) and r[0] == PPYC_ERR_INVALID_LENGTH
|
||||
# signature is not 64 bytes: verify returns False
|
||||
assert not ed25519_verify(b"x" * 63, b"m", bytes(32))
|
||||
|
||||
|
||||
def test_vectors_file():
|
||||
try:
|
||||
vec = load("ed25519_rfc8032")
|
||||
except FileNotFoundError:
|
||||
pytest.skip("vectors/ed25519_rfc8032.json missing")
|
||||
for case in vec.get("cases", []):
|
||||
seed = bytes.fromhex(case["secret"])
|
||||
assert ed25519_publickey(seed).hex() == case["public"], case.get("id")
|
||||
assert ed25519_sign(bytes.fromhex(case["msg"]), seed).hex() == case["signature"]
|
||||
@@ -0,0 +1,334 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Encoding module tests (Base64 / Base32 / Base16-Hex / Base58 / big-integer Base64URL).
|
||||
|
||||
Coverage:
|
||||
* byte-for-byte agreement with the standard library (base64 / bytes.hex) (many lengths x repeated random runs);
|
||||
* RFC 4648 §10 official test vectors (base64 / base32 / base32-hex / base16);
|
||||
* invalid input returns the unified three-tuple error result (instead of raising);
|
||||
* round-trip invertibility for each encoding.
|
||||
"""
|
||||
import base64
|
||||
import os
|
||||
import random
|
||||
|
||||
import pytest
|
||||
|
||||
from purepycrypto import encoding as E
|
||||
from purepycrypto._ppyc_error import is_err
|
||||
|
||||
# (0/1/2/3/4/5/10/100/1000) -- covers all 3-byte / 5-byte alignment boundaries
|
||||
LENGTHS = (0, 1, 2, 3, 4, 5, 10, 100, 1000)
|
||||
REPEAT = 3
|
||||
|
||||
|
||||
def _rand(n, seed):
|
||||
rnd = random.Random(seed)
|
||||
return bytes(rnd.randrange(256) for _ in range(n))
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# 1. Byte-for-byte agreement with the standard library
|
||||
# ----------------------------------------------------------------------
|
||||
|
||||
def test_b64encode_matches_stdlib():
|
||||
for length in LENGTHS:
|
||||
for k in range(REPEAT):
|
||||
data = _rand(length, 1000 + length * 7 + k)
|
||||
mine = E.b64encode(data)
|
||||
assert isinstance(mine, str) # encoding returns an ASCII str
|
||||
assert mine.encode("ascii") == base64.b64encode(data)
|
||||
|
||||
|
||||
def test_b32encode_matches_stdlib():
|
||||
for length in LENGTHS:
|
||||
for k in range(REPEAT):
|
||||
data = _rand(length, 2000 + length * 7 + k)
|
||||
mine = E.b32encode(data)
|
||||
assert isinstance(mine, str)
|
||||
assert mine.encode("ascii") == base64.b32encode(data)
|
||||
|
||||
|
||||
def test_b32hexencode_matches_stdlib():
|
||||
if not hasattr(base64, "b32hexencode"):
|
||||
pytest.skip("stdlib has no b32hexencode (Python < 3.10)")
|
||||
for length in LENGTHS:
|
||||
for k in range(REPEAT):
|
||||
data = _rand(length, 3000 + length * 7 + k)
|
||||
assert E.b32encode_hex(data).encode("ascii") == base64.b32hexencode(data)
|
||||
|
||||
|
||||
def test_hexencode_matches_stdlib():
|
||||
for length in LENGTHS:
|
||||
for k in range(REPEAT):
|
||||
data = _rand(length, 4000 + length * 7 + k)
|
||||
assert E.hex_encode(data) == data.hex()
|
||||
assert E.hex_encode(data, upper=True) == data.hex().upper()
|
||||
|
||||
|
||||
def test_b64decode_matches_stdlib_on_valid_input():
|
||||
for length in LENGTHS:
|
||||
for k in range(REPEAT):
|
||||
data = _rand(length, 5000 + length * 7 + k)
|
||||
enc = base64.b64encode(data) # standard-library output
|
||||
assert E.b64decode(enc) == data # str / bytes both accepted
|
||||
assert E.b64decode(enc.decode("ascii")) == data
|
||||
|
||||
|
||||
def test_b32decode_matches_stdlib_on_valid_input():
|
||||
for length in LENGTHS:
|
||||
for k in range(REPEAT):
|
||||
data = _rand(length, 6000 + length * 7 + k)
|
||||
enc = base64.b32encode(data)
|
||||
assert E.b32decode(enc) == data
|
||||
assert E.b32decode(enc.decode("ascii")) == data
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# 2. RFC 4648 §10 official test vectors
|
||||
# ----------------------------------------------------------------------
|
||||
|
||||
RFC4648 = [
|
||||
# (plaintext, base64, base32, base32-hex, base16-uppercase)
|
||||
("", "", "", "", ""),
|
||||
("f", "Zg==", "MY======", "CO======", "66"),
|
||||
("fo", "Zm8=", "MZXQ====", "CPNG====", "666F"),
|
||||
("foo", "Zm9v", "MZXW6===", "CPNMU===", "666F6F"),
|
||||
("foob", "Zm9vYg==", "MZXW6YQ=", "CPNMUOG=", "666F6F62"),
|
||||
("fooba", "Zm9vYmE=", "MZXW6YTB", "CPNMUOJ1", "666F6F6261"),
|
||||
("foobar", "Zm9vYmFy", "MZXW6YTBOI======", "CPNMUOJ1E8======", "666F6F626172"),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("text,b64,b32,b32hex,b16", RFC4648)
|
||||
def test_rfc4648_vectors_encode(text, b64, b32, b32hex, b16):
|
||||
data = text.encode("ascii")
|
||||
assert E.b64encode(data) == b64
|
||||
assert E.b32encode(data) == b32
|
||||
assert E.b32encode_hex(data) == b32hex
|
||||
assert E.hex_encode(data, upper=True) == b16
|
||||
|
||||
|
||||
@pytest.mark.parametrize("text,b64,b32,b32hex,b16", RFC4648)
|
||||
def test_rfc4648_vectors_decode(text, b64, b32, b32hex, b16):
|
||||
data = text.encode("ascii")
|
||||
assert E.b64decode(b64) == data
|
||||
assert E.b32decode(b32) == data
|
||||
assert E.b32decode_hex(b32hex) == data
|
||||
assert E.hex_decode(b16) == data
|
||||
assert E.hex_decode(b16.lower()) == data # either case accepted
|
||||
|
||||
|
||||
@pytest.mark.parametrize("text,b64,b32,b32hex,b16", RFC4648)
|
||||
def test_rfc4648_stdlib_cross_check(text, b64, b32, b32hex, b16):
|
||||
data = text.encode("ascii")
|
||||
assert E.b64encode(data).encode("ascii") == base64.b64encode(data)
|
||||
assert E.b32encode(data).encode("ascii") == base64.b32encode(data)
|
||||
if hasattr(base64, "b32hexencode"):
|
||||
assert E.b32encode_hex(data).encode("ascii") == base64.b32hexencode(data)
|
||||
assert E.hex_encode(data, upper=True) == data.hex().upper()
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# 3. urlsafe / nopad / altchars
|
||||
# ----------------------------------------------------------------------
|
||||
|
||||
def test_b64encode_altchars_matches_stdlib():
|
||||
for length in LENGTHS:
|
||||
for k in range(REPEAT):
|
||||
data = _rand(length, 7000 + length * 7 + k)
|
||||
assert E.b64encode(data, altchars=b"-_").encode("ascii") == \
|
||||
base64.b64encode(data, altchars=b"-_")
|
||||
assert E.b64encode(data, altchars="-_").encode("ascii") == \
|
||||
base64.b64encode(data, altchars=b"-_")
|
||||
|
||||
|
||||
def test_b64decode_altchars_roundtrip():
|
||||
data = bytes(range(200, 256)) + b"\xfb\xff\xfe"
|
||||
enc = E.b64encode(data, altchars=b"-_")
|
||||
assert E.b64decode(enc, altchars=b"-_") == data
|
||||
|
||||
|
||||
def test_urlsafe():
|
||||
for length in LENGTHS:
|
||||
for k in range(REPEAT):
|
||||
data = _rand(length, 8000 + length * 7 + k)
|
||||
enc = E.b64encode_urlsafe(data)
|
||||
assert enc.encode("ascii") == base64.urlsafe_b64encode(data)
|
||||
assert E.b64decode_urlsafe(enc) == data
|
||||
# unpadded (JWT/JWK style) should also decode
|
||||
assert E.b64decode_urlsafe(enc.rstrip("=")) == data
|
||||
assert E.b64decode_urlsafe(enc.encode("ascii")) == data
|
||||
|
||||
|
||||
def test_nopad():
|
||||
for length in LENGTHS:
|
||||
for k in range(REPEAT):
|
||||
data = _rand(length, 9000 + length * 7 + k)
|
||||
enc = E.b64encode_nopad(data)
|
||||
assert "=" not in enc
|
||||
assert enc.encode("ascii") == base64.b64encode(data).rstrip(b"=")
|
||||
assert E.b64decode_nopad(enc) == data
|
||||
# padded input decodes as well
|
||||
assert E.b64decode_nopad(enc + "=" * ((-len(enc)) % 4)) == data
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# 4. Hex separators and case
|
||||
# ----------------------------------------------------------------------
|
||||
|
||||
def test_hex_sep_roundtrip():
|
||||
data = bytes(range(256))
|
||||
assert E.hex_encode_sep(data[:4]) == "00:01:02:03"
|
||||
assert E.hex_decode_sep("00:01:02:03") == b"\x00\x01\x02\x03"
|
||||
assert E.hex_decode_sep("00:01:02:03".upper()) == b"\x00\x01\x02\x03"
|
||||
assert E.hex_decode_sep(E.hex_encode_sep(data)) == data
|
||||
assert E.hex_encode_sep(data[:2], sep="-", upper=True) == "00-01"
|
||||
assert E.hex_decode_sep("00-01-02", sep="-") == b"\x00\x01\x02"
|
||||
# an empty sep degrades to plain hex
|
||||
assert E.hex_encode_sep(b"\xde\xad", sep="") == "dead"
|
||||
assert E.hex_decode_sep("dead", sep="") == b"\xde\xad"
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# 5. Big integer <-> Base64URL (JWK)
|
||||
# ----------------------------------------------------------------------
|
||||
|
||||
def test_bigint_jwk():
|
||||
for n in (0, 1, 255, 256, 65537, 0x1234567890abcdef,
|
||||
int.from_bytes(os.urandom(256), "big")):
|
||||
enc = E.b64_encode_bigint(n)
|
||||
assert "=" not in enc and "+" not in enc and "/" not in enc
|
||||
# matches the standard-library base64url-no-pad representation
|
||||
nbytes = (n.bit_length() + 7) // 8
|
||||
ref = base64.urlsafe_b64encode(n.to_bytes(nbytes, "big")).rstrip(b"=").decode("ascii")
|
||||
assert enc == ref
|
||||
assert E.b64_decode_bigint(enc) == n
|
||||
|
||||
|
||||
def test_bigint_zero_and_types():
|
||||
assert E.b64_encode_bigint(0) == ""
|
||||
assert E.b64_decode_bigint("") == 0
|
||||
assert is_err(E.b64_encode_bigint(-1))
|
||||
assert is_err(E.b64_encode_bigint("x"))
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# 6. Base58
|
||||
# ----------------------------------------------------------------------
|
||||
|
||||
def test_base58_known_vectors():
|
||||
assert E.b58encode(b"") == ""
|
||||
assert E.b58decode("") == b""
|
||||
assert E.b58encode(b"\x00") == "1"
|
||||
assert E.b58encode(b"\x00\x00\x01") == "112"
|
||||
assert E.b58decode("1") == b"\x00"
|
||||
# widely cited Bitcoin Base58 vector
|
||||
assert E.b58encode(b"hello world") == "StV1DL6CwTryKyV"
|
||||
assert E.b58decode("StV1DL6CwTryKyV") == b"hello world"
|
||||
# classic address (version byte + 20-byte hash)
|
||||
raw = bytes.fromhex("00010966776006953D5567439E5E39F86A0D273BEED61967F6")
|
||||
assert E.b58encode(raw) == "16UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM"
|
||||
assert E.b58decode("16UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM") == raw
|
||||
|
||||
|
||||
def test_base58_roundtrip():
|
||||
for length in LENGTHS:
|
||||
for k in range(REPEAT):
|
||||
data = _rand(length, 11000 + length * 7 + k)
|
||||
assert E.b58decode(E.b58encode(data)) == data
|
||||
# leading zero bytes
|
||||
for zeros in range(4):
|
||||
d = b"\x00" * zeros + b"\x01\x02\x03"
|
||||
assert E.b58decode(E.b58encode(d)) == d
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# 7. Invalid input -> unified error three-tuple (never raises)
|
||||
# ----------------------------------------------------------------------
|
||||
|
||||
def test_hex_decode_invalid_returns_err():
|
||||
r = E.hex_decode("zz")
|
||||
assert is_err(r) and r[0] == "PPYC_ERR_INVALID_HEX"
|
||||
assert is_err(E.hex_decode("abc")) # odd length
|
||||
assert is_err(E.hex_decode("0g"))
|
||||
|
||||
|
||||
def test_b64decode_invalid_returns_err():
|
||||
r = E.b64decode("!!!", validate=True)
|
||||
assert is_err(r) and r[0] == "PPYC_ERR_INVALID_ENCODING"
|
||||
# in strict mode, invalid characters / padding misalignment both return an error
|
||||
assert is_err(E.b64decode("Zm9v\n", validate=True))
|
||||
assert is_err(E.b64decode("Zg", validate=True)) # missing padding
|
||||
assert is_err(E.b64decode("Zg==", validate=True)) is False
|
||||
assert is_err(E.b64decode("a", validate=True)) # ≡1 mod 4
|
||||
assert is_err(E.b64decode("Zg==extra", validate=True)) # extra data after padding
|
||||
# lenient mode ignores invalid characters (same as the standard library)
|
||||
assert E.b64decode("!!!") == b""
|
||||
assert E.b64decode("Zm9v\n") == b"foo"
|
||||
|
||||
|
||||
def test_b32decode_invalid_returns_err():
|
||||
assert is_err(E.b32decode("MZXW6!!!")) # invalid character
|
||||
assert is_err(E.b32decode("MZXW6")) # missing padding / length not a multiple of 8
|
||||
assert is_err(E.b32decode("mzxw6===")) # lowercase, not case-folded
|
||||
assert E.b32decode("mzxw6===", casefold=True) == b"foo" # casefold takes effect
|
||||
assert is_err(E.b32decode_hex("ZZZZZZZZ")) # Extended Hex invalid character
|
||||
assert is_err(E.b32decode_hex("CPNMU")) # invalid length
|
||||
|
||||
|
||||
def test_b58decode_invalid_returns_err():
|
||||
r = E.b58decode("0OIl") # easily confused characters
|
||||
assert is_err(r) and r[0] == "PPYC_ERR_INVALID_ENCODING"
|
||||
|
||||
|
||||
def test_encode_type_errors_return_err():
|
||||
for bad in (None, 123, "str-not-bytes", [1, 2, 3]):
|
||||
assert is_err(E.b64encode(bad))
|
||||
assert is_err(E.b32encode(bad))
|
||||
assert is_err(E.hex_encode(bad))
|
||||
assert is_err(E.b58encode(bad))
|
||||
# invalid altchars length
|
||||
assert is_err(E.b64encode(b"x", altchars=b"abc"))
|
||||
assert is_err(E.b64decode("Zg==", altchars=b"x"))
|
||||
# decode received a non str/bytes
|
||||
assert is_err(E.b64decode(12345))
|
||||
assert is_err(E.b32decode(None))
|
||||
|
||||
|
||||
def test_error_tuple_shape():
|
||||
r = E.b64decode("!!!", validate=True)
|
||||
assert isinstance(r, tuple) and len(r) == 3
|
||||
code, msg, hint = r
|
||||
assert isinstance(code, str) and code.startswith("PPYC_ERR_")
|
||||
assert isinstance(msg, str) and msg
|
||||
assert isinstance(hint, str)
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# 8. Comprehensive round-trip
|
||||
# ----------------------------------------------------------------------
|
||||
|
||||
def test_all_roundtrips():
|
||||
for length in LENGTHS:
|
||||
for k in range(REPEAT):
|
||||
data = _rand(length, 13000 + length * 7 + k)
|
||||
assert E.b64decode(E.b64encode(data)) == data
|
||||
assert E.b64decode_urlsafe(E.b64encode_urlsafe(data)) == data
|
||||
assert E.b64decode_nopad(E.b64encode_nopad(data)) == data
|
||||
assert E.b32decode(E.b32encode(data)) == data
|
||||
assert E.b32decode_hex(E.b32encode_hex(data)) == data
|
||||
assert E.hex_decode(E.hex_encode(data)) == data
|
||||
assert E.hex_decode_sep(E.hex_encode_sep(data)) == data
|
||||
assert E.b58decode(E.b58encode(data)) == data
|
||||
|
||||
|
||||
def test_encode_returns_str_decode_returns_bytes():
|
||||
data = b"purepycrypto"
|
||||
assert isinstance(E.b64encode(data), str)
|
||||
assert isinstance(E.b32encode(data), str)
|
||||
assert isinstance(E.hex_encode(data), str)
|
||||
assert isinstance(E.b58encode(data), str)
|
||||
assert isinstance(E.b64decode(E.b64encode(data)), bytes)
|
||||
assert isinstance(E.b32decode(E.b32encode(data)), bytes)
|
||||
assert isinstance(E.hex_decode(E.hex_encode(data)), bytes)
|
||||
assert isinstance(E.b58decode(E.b58encode(data)), bytes)
|
||||
@@ -0,0 +1,320 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Independent review of purepycrypto.encoding (new module in v3.2.0).
|
||||
|
||||
Verification strategy (**independent of the module's own tests**):
|
||||
* byte-for-byte comparison with the Python standard library base64 / binascii / bytes.hex;
|
||||
* RFC 4648 §10 official vectors (""/"f"/"fo"/"foo"/"foob"/"fooba"/"foobar");
|
||||
* url-safe / nopad / custom-altchars variants;
|
||||
* Base58 checked against an independent in-test reference implementation + round-trip;
|
||||
* big integer <-> Base64URL (JWK style);
|
||||
* invalid input must return a ``(PPYC_ERR_xxx, msg, suggestion)`` tuple rather than raise.
|
||||
|
||||
Convention: the module encodes to an ASCII ``str``; ``.encode("ascii")`` equals the standard-library bytes.
|
||||
"""
|
||||
import base64
|
||||
import os
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
_HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
_PKG_PARENT = os.path.dirname(_HERE)
|
||||
if _PKG_PARENT not in sys.path:
|
||||
sys.path.insert(0, _PKG_PARENT)
|
||||
|
||||
from purepycrypto import encoding as E # noqa: E402
|
||||
from purepycrypto._ppyc_error import PPYC_ERR_PREFIX # noqa: E402
|
||||
|
||||
_SIZES = [0, 1, 2, 3, 4, 5, 10, 100, 1000]
|
||||
|
||||
|
||||
def _is_err(v):
|
||||
return (isinstance(v, tuple) and len(v) == 3
|
||||
and isinstance(v[0], str) and v[0].startswith(PPYC_ERR_PREFIX))
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# 1. Byte-for-byte comparison with the standard library
|
||||
# ======================================================================
|
||||
|
||||
@pytest.mark.parametrize("size", _SIZES)
|
||||
def test_b64_encode_matches_stdlib(size):
|
||||
data = os.urandom(size)
|
||||
assert E.b64encode(data) == base64.b64encode(data).decode("ascii")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("size", _SIZES)
|
||||
def test_b64_decode_matches_stdlib(size):
|
||||
data = os.urandom(size)
|
||||
ref = base64.b64encode(data) # bytes
|
||||
assert E.b64decode(ref) == data
|
||||
assert E.b64decode(base64.b64encode(data).decode("ascii")) == data
|
||||
# reverse round-trip
|
||||
assert E.b64decode(E.b64encode(data)) == data
|
||||
|
||||
|
||||
@pytest.mark.parametrize("size", _SIZES)
|
||||
def test_b32_encode_matches_stdlib(size):
|
||||
data = os.urandom(size)
|
||||
assert E.b32encode(data) == base64.b32encode(data).decode("ascii")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("size", _SIZES)
|
||||
def test_b32_decode_matches_stdlib(size):
|
||||
data = os.urandom(size)
|
||||
assert E.b32decode(base64.b32encode(data)) == data
|
||||
assert E.b32decode(E.b32encode(data)) == data
|
||||
|
||||
|
||||
@pytest.mark.parametrize("size", _SIZES)
|
||||
def test_b32hex_matches_stdlib(size):
|
||||
data = os.urandom(size)
|
||||
assert E.b32encode_hex(data) == base64.b32hexencode(data).decode("ascii")
|
||||
assert E.b32decode_hex(base64.b32hexencode(data)) == data
|
||||
|
||||
|
||||
@pytest.mark.parametrize("size", _SIZES)
|
||||
def test_hex_matches_stdlib(size):
|
||||
data = os.urandom(size)
|
||||
assert E.hex_encode(data) == data.hex()
|
||||
assert E.hex_encode(data, upper=True) == data.hex().upper()
|
||||
assert E.hex_decode(data.hex()) == data
|
||||
assert E.hex_decode(data.hex().upper()) == data
|
||||
|
||||
|
||||
def test_hex_sep_roundtrip():
|
||||
data = os.urandom(8)
|
||||
s = E.hex_encode_sep(data, sep=":")
|
||||
assert s == ":".join(data.hex()[i:i + 2] for i in range(0, len(data) * 2, 2))
|
||||
assert E.hex_decode_sep(s, sep=":") == data
|
||||
s2 = E.hex_encode_sep(data, sep="-", upper=True)
|
||||
assert E.hex_decode_sep(s2, sep="-") == data
|
||||
# empty separator == no separator
|
||||
assert E.hex_encode_sep(data, sep="") == data.hex()
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# 2. RFC 4648 §10 official vectors
|
||||
# ======================================================================
|
||||
|
||||
RFC4648_B64 = {
|
||||
b"": "", b"f": "Zg==", b"fo": "Zm8=", b"foo": "Zm9v",
|
||||
b"foob": "Zm9vYg==", b"fooba": "Zm9vYmE=", b"foobar": "Zm9vYmFy",
|
||||
}
|
||||
RFC4648_B32 = {
|
||||
b"": "", b"f": "MY======", b"fo": "MZXQ====", b"foo": "MZXW6===",
|
||||
b"foob": "MZXW6YQ=", b"fooba": "MZXW6YTB", b"foobar": "MZXW6YTBOI======",
|
||||
}
|
||||
RFC4648_B16 = {
|
||||
b"": "", b"f": "66", b"fo": "666F", b"foo": "666F6F",
|
||||
b"foob": "666F6F62", b"fooba": "666F6F6261", b"foobar": "666F6F626172",
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("src,enc", list(RFC4648_B64.items()))
|
||||
def test_rfc4648_b64_vector(src, enc):
|
||||
assert E.b64encode(src) == enc
|
||||
assert E.b64decode(enc) == src
|
||||
# also cross-checked against the standard library
|
||||
assert E.b64encode(src) == base64.b64encode(src).decode("ascii")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("src,enc", list(RFC4648_B32.items()))
|
||||
def test_rfc4648_b32_vector(src, enc):
|
||||
assert E.b32encode(src) == enc
|
||||
assert E.b32decode(enc) == src
|
||||
assert E.b32encode(src) == base64.b32encode(src).decode("ascii")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("src,enc", list(RFC4648_B16.items()))
|
||||
def test_rfc4648_b16_vector(src, enc):
|
||||
assert E.hex_encode(src) == enc.lower()
|
||||
assert E.hex_encode(src, upper=True) == enc
|
||||
assert E.hex_decode(enc) == src
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# 3. url-safe / nopad / custom altchars
|
||||
# ======================================================================
|
||||
|
||||
#: contains bytes that trigger the +/ replacement
|
||||
_ALT_DATA = [b"\xfb\xff\xfe", b"\xff\xff\xff", b"\x00\x10\x83", os.urandom(20)]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("data", _ALT_DATA)
|
||||
def test_urlsafe_matches_stdlib(data):
|
||||
assert E.b64encode_urlsafe(data) == base64.urlsafe_b64encode(data).decode("ascii")
|
||||
# decoding tolerates both padded and unpadded forms
|
||||
ref = base64.urlsafe_b64encode(data).decode("ascii")
|
||||
assert E.b64decode_urlsafe(ref) == data
|
||||
assert E.b64decode_urlsafe(ref.rstrip("=")) == data
|
||||
|
||||
|
||||
@pytest.mark.parametrize("data", _ALT_DATA)
|
||||
def test_custom_altchars_matches_stdlib(data):
|
||||
assert E.b64encode(data, altchars=b"-_") == base64.b64encode(data, altchars=b"-_").decode("ascii")
|
||||
assert E.b64encode(data, altchars="-_") == base64.b64encode(data, altchars=b"-_").decode("ascii")
|
||||
enc = base64.b64encode(data, altchars=b"-_").decode("ascii")
|
||||
assert E.b64decode(enc, altchars=b"-_") == data
|
||||
|
||||
|
||||
@pytest.mark.parametrize("size", _SIZES)
|
||||
def test_nopad_matches_stdlib(size):
|
||||
data = os.urandom(size)
|
||||
ref = base64.b64encode(data).decode("ascii").rstrip("=")
|
||||
assert E.b64encode_nopad(data) == ref
|
||||
# unpadded decoding
|
||||
assert E.b64decode_nopad(ref) == data
|
||||
# padded input is accepted too
|
||||
assert E.b64decode_nopad(base64.b64encode(data).decode("ascii")) == data
|
||||
# does not contain '='
|
||||
assert "=" not in E.b64encode_nopad(data)
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# 4. Base58 (Bitcoin alphabet) -- independent reference implementation + round-trip
|
||||
# ======================================================================
|
||||
|
||||
_B58_ALPHA = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
|
||||
|
||||
|
||||
def _ref_b58encode(data: bytes) -> str:
|
||||
n = int.from_bytes(data, "big")
|
||||
out = ""
|
||||
while n > 0:
|
||||
n, r = divmod(n, 58)
|
||||
out = _B58_ALPHA[r] + out
|
||||
pad = len(data) - len(data.lstrip(b"\x00"))
|
||||
return "1" * pad + out
|
||||
|
||||
|
||||
@pytest.mark.parametrize("data", [
|
||||
b"", b"\x00", b"\x00\x00", b"\x00\x01", b"abc", b"Hello World!",
|
||||
os.urandom(1), os.urandom(2), os.urandom(10), os.urandom(100),
|
||||
b"\x00\x00\x00\xff\xff",
|
||||
])
|
||||
def test_b58_matches_reference_and_roundtrip(data):
|
||||
got = E.b58encode(data)
|
||||
assert got == _ref_b58encode(data)
|
||||
assert E.b58decode(got) == data
|
||||
assert E.b58decode(E.b58encode(data)) == data
|
||||
|
||||
|
||||
def test_b58_known_vectors():
|
||||
# well-known Bitcoin base58 vector
|
||||
assert E.b58encode(b"") == ""
|
||||
assert E.b58encode(b"\x00") == "1"
|
||||
assert E.b58encode(b"\x00\x00\x01") == "112"
|
||||
assert E.b58encode(b"abc") == "ZiCa"
|
||||
assert E.b58decode("ZiCa") == b"abc"
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# 5. Big integer <-> Base64URL (JWK style)
|
||||
# ======================================================================
|
||||
|
||||
@pytest.mark.parametrize("n", [0, 1, 255, 256, 65537, 2 ** 256 - 1,
|
||||
0x123456789abcdef, 2 ** 521 - 1])
|
||||
def test_b64_bigint_roundtrip_and_reference(n):
|
||||
s = E.b64_encode_bigint(n)
|
||||
nbytes = (n.bit_length() + 7) // 8
|
||||
ref = base64.urlsafe_b64encode(n.to_bytes(nbytes, "big")).decode("ascii").rstrip("=")
|
||||
if n == 0:
|
||||
ref = ""
|
||||
assert s == ref
|
||||
assert E.b64_decode_bigint(s) == n
|
||||
assert E.b64_decode_bigint(E.b64_encode_bigint(n)) == n
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# 6. Invalid input -- must return an err tuple rather than raise
|
||||
# ======================================================================
|
||||
|
||||
def test_invalid_hex_returns_err_not_raise():
|
||||
for bad in ["zz", "abc", "0x1234", "1G", "0b1", b"\xff\xfe"]:
|
||||
r = E.hex_decode(bad)
|
||||
assert _is_err(r), (bad, r)
|
||||
assert r[0] == "PPYC_ERR_INVALID_HEX"
|
||||
|
||||
|
||||
def test_invalid_b64_returns_err_not_raise():
|
||||
# '!!!' is invalid in strict mode
|
||||
r = E.b64decode("!!!", validate=True)
|
||||
assert _is_err(r)
|
||||
# invalid length (== 1 mod 4)
|
||||
r = E.b64decode("a", validate=True)
|
||||
assert _is_err(r) and r[0] == "PPYC_ERR_INVALID_LENGTH"
|
||||
# wrong padding count
|
||||
r = E.b64decode("Zg=", validate=True)
|
||||
assert _is_err(r) and r[0] == "PPYC_ERR_INVALID_LENGTH"
|
||||
# lenient mode (default validate=False) does not raise (invalid chars ignored, returns b"")
|
||||
r = E.b64decode("!!!")
|
||||
assert not _is_err(r) and r == b""
|
||||
# non-ASCII character -> INVALID_ENCODING
|
||||
r = E.b64decode("!!!", validate=True)
|
||||
assert _is_err(r) and r[0] == "PPYC_ERR_INVALID_ENCODING"
|
||||
|
||||
|
||||
def test_invalid_b32_returns_err_not_raise():
|
||||
r = E.b32decode("!!!")
|
||||
assert _is_err(r)
|
||||
r = E.b32decode("MZXW6YTBOI=====") # wrong padding count
|
||||
assert _is_err(r)
|
||||
|
||||
|
||||
def test_invalid_b58_returns_err():
|
||||
# contains 0 / O / I / l / symbols, none of which are in the Bitcoin alphabet
|
||||
for bad in ["0", "O", "I", "l", "abc!", "12!" ]:
|
||||
r = E.b58decode(bad)
|
||||
assert _is_err(r), (bad, r)
|
||||
assert r[0] == "PPYC_ERR_INVALID_ENCODING"
|
||||
|
||||
|
||||
def test_invalid_types_return_err():
|
||||
# encoding input must be bytes-like
|
||||
assert _is_err(E.b64encode("notbytes"))
|
||||
assert _is_err(E.b32encode(123))
|
||||
assert _is_err(E.hex_encode(3.14))
|
||||
assert _is_err(E.b58encode(["x"]))
|
||||
# decoding input must be str/bytes
|
||||
assert _is_err(E.b64decode(123))
|
||||
assert _is_err(E.b32decode(None))
|
||||
# wrong altchars length
|
||||
assert _is_err(E.b64encode(b"x", altchars=b"-"))
|
||||
assert _is_err(E.b64encode(b"x", altchars="abc"))
|
||||
# bigint argument
|
||||
assert _is_err(E.b64_encode_bigint(-1))
|
||||
assert _is_err(E.b64_encode_bigint("x"))
|
||||
# sep type
|
||||
assert _is_err(E.hex_encode_sep(b"ab", sep=1))
|
||||
assert _is_err(E.hex_decode_sep("ab", sep=1))
|
||||
|
||||
|
||||
def test_err_tuple_shape():
|
||||
r = E.hex_decode("zz")
|
||||
assert isinstance(r, tuple) and len(r) == 3
|
||||
assert isinstance(r[0], str) and isinstance(r[1], str) and isinstance(r[2], str)
|
||||
assert r[0].startswith("PPYC_ERR_")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("data", [b"hello", b"", b"\x00\xff", os.urandom(33)])
|
||||
def test_all_encoders_never_raise_on_roundtrip(data):
|
||||
"""encode->decode round-trip must never raise under any of the encodings."""
|
||||
assert E.b64decode(E.b64encode(data)) == data
|
||||
assert E.b32decode(E.b32encode(data)) == data
|
||||
assert E.hex_decode(E.hex_encode(data)) == data
|
||||
assert E.b58decode(E.b58encode(data)) == data
|
||||
assert E.b64decode_nopad(E.b64encode_nopad(data)) == data
|
||||
assert E.b64decode_urlsafe(E.b64encode_urlsafe(data)) == data
|
||||
|
||||
|
||||
def test_hex_whitespace_tolerant_matches_stdlib():
|
||||
# bytes.fromhex allows whitespace between bytes; the module behavior should match
|
||||
assert E.hex_decode(" ") == b""
|
||||
assert E.hex_decode("66 6f 6f") == bytes.fromhex("66 6f 6f") == b"foo"
|
||||
|
||||
|
||||
def test_b58_digit_lowercase_chars_are_valid():
|
||||
# digits like '4' '2' are part of the Bitcoin alphabet and should be valid input
|
||||
assert E.b58decode("42") == bytes([0xaf])
|
||||
assert E.b58encode(bytes([0xaf])) == "42"
|
||||
@@ -0,0 +1,175 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Unified error scheme tests (PPYC_ERR + tuple returns).
|
||||
|
||||
Coverage:
|
||||
- PPYC_ERR exception class (attributes / string / as_tuple)
|
||||
- err() / ok() / OK_TUPLE / is_ok() / is_err()
|
||||
- error-code prefix enforcement
|
||||
- validity of all error-code constants
|
||||
- legacy exception name compatibility (CryptoError / DecryptionError / Ed25519Error)
|
||||
- actual error returns from the module APIs (sampled)
|
||||
"""
|
||||
import pytest
|
||||
|
||||
from purepycrypto._ppyc_error import (
|
||||
PPYC_ERR, PPYCError, CryptoError, DecryptionError, Ed25519Error,
|
||||
err, ok, is_ok, is_err, raise_ppyc, OK_TUPLE, PPYCResult,
|
||||
ALL_ERROR_CODES, PPYC_ERR_PREFIX,
|
||||
PPYC_ERR_INTERNAL, PPYC_ERR_INVALID_ARG, PPYC_ERR_AUTH_FAILED,
|
||||
PPYC_ERR_INVALID_KEY_LEN, PPYC_ERR_INVALID_ALGO, PPYC_ERR_EOF,
|
||||
)
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# 1. PPYC_ERR exception class
|
||||
# ----------------------------------------------------------------------
|
||||
|
||||
def test_ppyc_err_attributes():
|
||||
e = PPYC_ERR(PPYC_ERR_INTERNAL, "internal inconsistency", "please file an issue")
|
||||
assert e.code == PPYC_ERR_INTERNAL
|
||||
assert e.message == "internal inconsistency"
|
||||
assert e.suggestion == "please file an issue"
|
||||
assert e.as_tuple() == (PPYC_ERR_INTERNAL, "internal inconsistency", "please file an issue")
|
||||
|
||||
|
||||
def test_ppyc_err_str_contains_all():
|
||||
e = PPYC_ERR(PPYC_ERR_INVALID_ARG, "invalid argument", "please check")
|
||||
s = str(e)
|
||||
assert PPYC_ERR_INVALID_ARG in s
|
||||
assert "invalid argument" in s
|
||||
assert "please check" in s
|
||||
|
||||
|
||||
def test_ppyc_err_defaults():
|
||||
e = PPYC_ERR()
|
||||
assert e.code == PPYC_ERR_INTERNAL
|
||||
assert e.message == ""
|
||||
assert e.suggestion == ""
|
||||
|
||||
|
||||
def test_ppyc_err_is_exception():
|
||||
assert issubclass(PPYC_ERR, Exception)
|
||||
with pytest.raises(PPYC_ERR):
|
||||
raise PPYC_ERR(PPYC_ERR_INTERNAL, "x")
|
||||
|
||||
|
||||
def test_raise_ppyc_helper():
|
||||
with pytest.raises(PPYC_ERR) as ei:
|
||||
raise_ppyc(PPYC_ERR_INVALID_ARG, "msg", "hint")
|
||||
assert ei.value.code == PPYC_ERR_INVALID_ARG
|
||||
assert ei.value.suggestion == "hint"
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# 2. Tuple-return helpers
|
||||
# ----------------------------------------------------------------------
|
||||
|
||||
def test_err_returns_tuple():
|
||||
code, msg, hint = err(PPYC_ERR_INVALID_KEY_LEN, "bad key length", "use 16 bytes")
|
||||
assert code == PPYC_ERR_INVALID_KEY_LEN
|
||||
assert msg == "bad key length"
|
||||
assert hint == "use 16 bytes"
|
||||
|
||||
|
||||
def test_err_suggestion_optional():
|
||||
t = err(PPYC_ERR_INVALID_ARG, "bad argument")
|
||||
assert t == (PPYC_ERR_INVALID_ARG, "bad argument", "")
|
||||
|
||||
|
||||
def test_err_rejects_bad_prefix():
|
||||
"""An error code must start with PPYC_ERR_, otherwise PPYC_ERR is raised."""
|
||||
with pytest.raises(PPYC_ERR):
|
||||
err("BAD_CODE", "x")
|
||||
with pytest.raises(PPYC_ERR):
|
||||
err("", "x")
|
||||
with pytest.raises(PPYC_ERR):
|
||||
err(None, "x") # type: ignore[arg-type]
|
||||
|
||||
|
||||
def test_ok_and_ok_tuple():
|
||||
assert ok(123) == 123
|
||||
assert ok("abc") == "abc"
|
||||
assert OK_TUPLE == (None, None, None)
|
||||
|
||||
|
||||
def test_is_ok_variants():
|
||||
assert is_ok(None) is True
|
||||
assert is_ok(OK_TUPLE) is True
|
||||
assert is_ok(b"plaintext") is True # a business value also counts as success
|
||||
assert is_ok((b"ct", b"tag")) is True # a 2-tuple is not an error
|
||||
|
||||
|
||||
def test_is_err_variants():
|
||||
assert is_err((PPYC_ERR_INVALID_ARG, "m", "h")) is True
|
||||
assert is_err(OK_TUPLE) is False
|
||||
assert is_err(None) is False
|
||||
assert is_err(b"data") is False
|
||||
assert is_err((b"ct", b"tag")) is False # length is not 3
|
||||
|
||||
|
||||
def test_is_err_and_is_ok_inverse():
|
||||
t = err(PPYC_ERR_AUTH_FAILED, "authentication failed", "check the key")
|
||||
assert is_err(t) is True
|
||||
assert is_ok(t) is False
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# 3. Error-code constants
|
||||
# ----------------------------------------------------------------------
|
||||
|
||||
def test_all_error_codes_valid():
|
||||
assert len(ALL_ERROR_CODES) > 30
|
||||
for c in ALL_ERROR_CODES:
|
||||
assert isinstance(c, str)
|
||||
assert c.startswith(PPYC_ERR_PREFIX), c
|
||||
assert c != PPYC_ERR_PREFIX, "the prefix constant should not be mixed into the code table"
|
||||
assert c == c.upper(), c
|
||||
|
||||
|
||||
def test_error_codes_unique():
|
||||
assert len(set(ALL_ERROR_CODES)) == len(ALL_ERROR_CODES)
|
||||
|
||||
|
||||
def test_prefix_value():
|
||||
assert PPYC_ERR_PREFIX == "PPYC_ERR_"
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# 4. Legacy exception name compatibility
|
||||
# ----------------------------------------------------------------------
|
||||
|
||||
@pytest.mark.parametrize("cls", [CryptoError, DecryptionError, Ed25519Error])
|
||||
def test_legacy_exceptions_subclass(cls):
|
||||
assert issubclass(cls, PPYC_ERR)
|
||||
|
||||
|
||||
def test_legacy_exception_codes():
|
||||
assert CryptoError("x").code == PPYC_ERR_INTERNAL
|
||||
assert DecryptionError("x").code == PPYC_ERR_AUTH_FAILED
|
||||
assert Ed25519Error("x").code == PPYC_ERR_INVALID_ARG
|
||||
|
||||
|
||||
def test_ppyc_error_alias():
|
||||
assert PPYCError is PPYC_ERR
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# 5. Actual error returns from the module APIs (sampled, end-to-end)
|
||||
# ----------------------------------------------------------------------
|
||||
|
||||
def test_blake2b_bad_digest_size_returns_tuple():
|
||||
from purepycrypto import blake2b
|
||||
r = blake2b(b"abc", 0)
|
||||
assert is_err(r) and r[0] == PPYC_ERR_INVALID_ARG
|
||||
|
||||
|
||||
def test_shake_bad_outlen_returns_tuple():
|
||||
from purepycrypto import shake128
|
||||
r = shake128(b"abc", -1)
|
||||
assert is_err(r) and r[0] == PPYC_ERR_INVALID_ARG
|
||||
|
||||
|
||||
def test_sha3_batch_bad_algo_returns_tuple():
|
||||
from purepycrypto import sha3_batch
|
||||
r = sha3_batch([b"a"], "nope")
|
||||
assert is_err(r) and r[0] == PPYC_ERR_INVALID_ALGO
|
||||
@@ -0,0 +1,371 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Unified error scheme -- boundary and end-to-end tests (v3.1.4).
|
||||
|
||||
This file complements test_errors.py and covers:
|
||||
1. Error-code completeness (format / uniqueness / non-empty)
|
||||
2. Tuple semantic boundaries (is_ok/is_err for various inputs)
|
||||
3. PPYC_ERR exception behavior
|
||||
4. Error-code correctness per module (end-to-end, grouped by module)
|
||||
5. Constructors raising PPYC_ERR
|
||||
6. CLI error handling (exit code + stderr error code)
|
||||
7. TUI error handling (EOF)
|
||||
"""
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
import pytest
|
||||
|
||||
from purepycrypto import (
|
||||
PPYC_ERR, err, ok, is_ok, is_err, OK_TUPLE, PPYCResult, raise_ppyc,
|
||||
CryptoError, DecryptionError, Ed25519Error,
|
||||
ALL_ERROR_CODES, PPYC_ERR_PREFIX,
|
||||
PPYC_ERR_INVALID_ARG, PPYC_ERR_INVALID_LENGTH, PPYC_ERR_INVALID_KEY_LEN,
|
||||
PPYC_ERR_INVALID_NONCE_LEN, PPYC_ERR_INVALID_IV_LEN, PPYC_ERR_INVALID_PADDING,
|
||||
PPYC_ERR_AUTH_FAILED, PPYC_ERR_DECRYPT_FAILED, PPYC_ERR_INVALID_ALGO,
|
||||
PPYC_ERR_INVALID_KDF_PARAM, PPYC_ERR_INVALID_RSA_BITS,
|
||||
PPYC_ERR_MESSAGE_TOO_LONG, PPYC_ERR_INVALID_KEY_MATERIAL,
|
||||
PPYC_ERR_EOF, PPYC_ERR_INVALID_TYPE,
|
||||
)
|
||||
|
||||
_PROJ = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# 1. Error-code completeness
|
||||
# ======================================================================
|
||||
|
||||
def test_all_codes_format():
|
||||
assert len(ALL_ERROR_CODES) >= 40
|
||||
for c in ALL_ERROR_CODES:
|
||||
assert isinstance(c, str)
|
||||
assert c.startswith(PPYC_ERR_PREFIX), c
|
||||
assert c == c.upper(), c
|
||||
assert len(c) > len(PPYC_ERR_PREFIX), c
|
||||
assert " " not in c
|
||||
|
||||
|
||||
def test_all_codes_unique_and_not_prefix():
|
||||
assert len(set(ALL_ERROR_CODES)) == len(ALL_ERROR_CODES)
|
||||
assert PPYC_ERR_PREFIX not in ALL_ERROR_CODES
|
||||
|
||||
|
||||
@pytest.mark.parametrize("bad", ["BAD", "PPYC_ERR", "ppyc_err_x", "", None, 123, "PPYC_ERR_"])
|
||||
def test_err_rejects_bad_code(bad):
|
||||
"""err() must reject codes without the PPYC_ERR_ prefix (empty string, non-str, prefix only)."""
|
||||
if bad == "PPYC_ERR_":
|
||||
# prefix only: startswith passes, but it should still be accepted as a "well-formed custom code"
|
||||
# -- this library only checks the prefix, so nothing is raised here. Skip.
|
||||
pytest.skip("a prefix-only string is well-formed")
|
||||
with pytest.raises(PPYC_ERR):
|
||||
err(bad, "msg")
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# 2. Tuple semantic boundaries
|
||||
# ======================================================================
|
||||
|
||||
@pytest.mark.parametrize("val,expect_ok", [
|
||||
(None, True),
|
||||
(OK_TUPLE, True),
|
||||
((None, None, None), True),
|
||||
(b"plaintext", True),
|
||||
("text", True),
|
||||
(123, True),
|
||||
([1, 2], True),
|
||||
({"a": 1}, True),
|
||||
((b"ct", b"tag"), True), # a 2-tuple is not an error
|
||||
((), True), # an empty tuple is not an error
|
||||
((1, 2, 3, 4), True), # a 4-tuple is not an error
|
||||
((PPYC_ERR_INVALID_ARG, "m", "h"), False),
|
||||
((PPYC_ERR_AUTH_FAILED, "m", ""), False),
|
||||
])
|
||||
def test_is_ok_various(val, expect_ok):
|
||||
assert is_ok(val) is expect_ok
|
||||
|
||||
|
||||
@pytest.mark.parametrize("val,expect_err", [
|
||||
((PPYC_ERR_INVALID_ARG, "m", "h"), True),
|
||||
((PPYC_ERR_AUTH_FAILED, "m", ""), True),
|
||||
(OK_TUPLE, False),
|
||||
(None, False),
|
||||
(b"x", False),
|
||||
("x", False),
|
||||
((b"a", b"b"), False),
|
||||
((), False),
|
||||
((1, 2, 3), False), # the first element is not a PPYC_ERR_ string
|
||||
])
|
||||
def test_is_err_various(val, expect_err):
|
||||
assert is_err(val) is expect_err
|
||||
|
||||
|
||||
def test_is_ok_is_err_inverse_for_err_tuple():
|
||||
t = err(PPYC_ERR_AUTH_FAILED, "authentication failed", "check the key")
|
||||
assert is_err(t) is True and is_ok(t) is False
|
||||
|
||||
|
||||
def test_ok_passthrough():
|
||||
for v in (None, 0, "", b"", [], {}):
|
||||
assert ok(v) is v
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# 3. PPYC_ERR exception
|
||||
# ======================================================================
|
||||
|
||||
def test_ppyc_err_attrs_and_tuple():
|
||||
e = PPYC_ERR(PPYC_ERR_INVALID_ARG, "invalid argument", "see the docs")
|
||||
assert (e.code, e.message, e.suggestion) == (PPYC_ERR_INVALID_ARG, "invalid argument", "see the docs")
|
||||
assert e.as_tuple() == (PPYC_ERR_INVALID_ARG, "invalid argument", "see the docs")
|
||||
|
||||
|
||||
def test_ppyc_err_str_without_suggestion():
|
||||
e = PPYC_ERR(PPYC_ERR_INVALID_ARG, "invalid argument")
|
||||
assert PPYC_ERR_INVALID_ARG in str(e) and "invalid argument" in str(e)
|
||||
assert "Suggestion" not in str(e)
|
||||
|
||||
|
||||
def test_ppyc_err_catchable_as_exception():
|
||||
with pytest.raises(Exception):
|
||||
raise PPYC_ERR(PPYC_ERR_INVALID_ARG, "x")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("cls,code", [
|
||||
(CryptoError, "PPYC_ERR_INTERNAL"),
|
||||
(DecryptionError, PPYC_ERR_AUTH_FAILED),
|
||||
(Ed25519Error, PPYC_ERR_INVALID_ARG),
|
||||
])
|
||||
def test_legacy_exception_default_codes(cls, code):
|
||||
assert issubclass(cls, PPYC_ERR)
|
||||
assert cls("msg").code == code
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# 4. Error codes per module, end-to-end
|
||||
# ======================================================================
|
||||
|
||||
class TestAESErrors:
|
||||
def test_key_len(self):
|
||||
from purepycrypto import AES
|
||||
with pytest.raises(PPYC_ERR) as ei:
|
||||
AES(b"short")
|
||||
assert ei.value.code == PPYC_ERR_INVALID_KEY_LEN
|
||||
|
||||
def test_iv_len(self):
|
||||
from purepycrypto import AES
|
||||
r = AES(b"0" * 16).encrypt_cbc(b"x", b"short")
|
||||
assert is_err(r) and r[0] == PPYC_ERR_INVALID_IV_LEN
|
||||
|
||||
def test_bad_padding(self):
|
||||
from purepycrypto import AES
|
||||
r = AES(b"0" * 16).decrypt_ecb(bytes(16))
|
||||
assert is_err(r) and r[0] in (PPYC_ERR_INVALID_PADDING, PPYC_ERR_DECRYPT_FAILED)
|
||||
|
||||
def test_gcm_nonce_len(self):
|
||||
from purepycrypto import AES
|
||||
r = AES(bytes(16)).gcm_encrypt(b"short", b"x")
|
||||
assert is_err(r) and r[0] == PPYC_ERR_INVALID_NONCE_LEN
|
||||
|
||||
def test_gcm_auth_failed(self):
|
||||
from purepycrypto import AES
|
||||
a = AES(bytes(16))
|
||||
ct, tag = a.gcm_encrypt(bytes(12), b"data", b"aad")
|
||||
r = a.gcm_decrypt(bytes(12), ct, tag, b"wrong")
|
||||
assert is_err(r) and r[0] == PPYC_ERR_AUTH_FAILED
|
||||
|
||||
|
||||
class TestChaChaErrors:
|
||||
def test_key_len(self):
|
||||
from purepycrypto import chacha20poly1305_encrypt
|
||||
r = chacha20poly1305_encrypt(b"short", bytes(12), b"x")
|
||||
assert is_err(r) and r[0] == PPYC_ERR_INVALID_KEY_LEN
|
||||
|
||||
def test_auth_failed(self):
|
||||
from purepycrypto import chacha20poly1305_encrypt, chacha20poly1305_decrypt
|
||||
key, nonce = os.urandom(32), os.urandom(12)
|
||||
ct = chacha20poly1305_encrypt(key, nonce, b"msg")
|
||||
r = chacha20poly1305_decrypt(key, nonce, ct[:-1] + bytes([ct[-1] ^ 1]))
|
||||
assert is_err(r) and r[0] == PPYC_ERR_AUTH_FAILED
|
||||
|
||||
|
||||
class TestGcmSivErrors:
|
||||
def test_key_len(self):
|
||||
from purepycrypto import aes128_gcm_siv_encrypt
|
||||
r = aes128_gcm_siv_encrypt(b"short", os.urandom(12), b"x")
|
||||
assert is_err(r) and r[0] == PPYC_ERR_INVALID_KEY_LEN
|
||||
|
||||
def test_auth_failed(self):
|
||||
from purepycrypto import aes128_gcm_siv_decrypt
|
||||
r = aes128_gcm_siv_decrypt(os.urandom(16), os.urandom(12), bytes(16), bytes(16))
|
||||
assert is_err(r) and r[0] == PPYC_ERR_AUTH_FAILED
|
||||
|
||||
|
||||
class TestKdfErrors:
|
||||
def test_scrypt_bad_n(self):
|
||||
from purepycrypto import scrypt
|
||||
r = scrypt(b"p", b"s", N=15, r=8, p=1)
|
||||
assert is_err(r) and r[0] == PPYC_ERR_INVALID_KDF_PARAM
|
||||
|
||||
def test_argon2_bad_t(self):
|
||||
from purepycrypto import argon2id
|
||||
r = argon2id(b"p", b"s", t=0)
|
||||
assert is_err(r) and r[0] in (PPYC_ERR_INVALID_KDF_PARAM, PPYC_ERR_INVALID_ARG)
|
||||
|
||||
def test_pbkdf2_bad_iter(self):
|
||||
from purepycrypto import pbkdf2_hmac
|
||||
r = pbkdf2_hmac(b"p", b"s", 0, 32)
|
||||
assert is_err(r) and r[0] in (PPYC_ERR_INVALID_KDF_PARAM, PPYC_ERR_INVALID_ARG)
|
||||
|
||||
def test_hkdf_bad_hash(self):
|
||||
from purepycrypto import hkdf_extract
|
||||
r = hkdf_extract(b"salt", b"ikm", "md5")
|
||||
assert is_err(r) and r[0] == PPYC_ERR_INVALID_ALGO
|
||||
|
||||
|
||||
class TestHashErrors:
|
||||
def test_blake2b_bad_size(self):
|
||||
from purepycrypto import blake2b
|
||||
r = blake2b(b"x", 0)
|
||||
assert is_err(r) and r[0] == PPYC_ERR_INVALID_ARG
|
||||
|
||||
def test_shake_bad_outlen(self):
|
||||
from purepycrypto import shake128, shake256
|
||||
assert is_err(shake128(b"x", -1))
|
||||
assert is_err(shake256(b"x", -1))
|
||||
|
||||
|
||||
class TestSha3Errors:
|
||||
def test_batch_bad_algo(self):
|
||||
from purepycrypto import sha3_batch
|
||||
r = sha3_batch([b"a"], "nope")
|
||||
assert is_err(r) and r[0] == PPYC_ERR_INVALID_ALGO
|
||||
|
||||
def test_hex_wrapper_handles_error(self):
|
||||
"""hex wrapper functions should return a tuple on error, not raise AttributeError."""
|
||||
from purepycrypto.sha3 import shake128_hex, sha3_256_hex
|
||||
r = shake128_hex(b"x", -1)
|
||||
assert is_err(r), "shake128_hex should return an error tuple"
|
||||
assert isinstance(sha3_256_hex(b"abc"), str)
|
||||
|
||||
|
||||
class TestPubkeyErrors:
|
||||
def test_x25519_bad_len(self):
|
||||
from purepycrypto import x25519
|
||||
r = x25519(b"short", bytes(32))
|
||||
assert is_err(r) and r[0] == PPYC_ERR_INVALID_LENGTH
|
||||
|
||||
def test_rsa_bits_too_small(self):
|
||||
from purepycrypto import rsa_keygen
|
||||
with pytest.raises(PPYC_ERR) as ei:
|
||||
rsa_keygen(bits=256, parallel=False)
|
||||
assert ei.value.code == PPYC_ERR_INVALID_RSA_BITS
|
||||
|
||||
def test_rsa_oaep_too_long(self):
|
||||
from purepycrypto import rsa_keygen, rsa_oaep_encrypt
|
||||
pub, _ = rsa_keygen(bits=1024, parallel=False)
|
||||
r = rsa_oaep_encrypt(b"x" * 500, pub)
|
||||
assert is_err(r) and r[0] == PPYC_ERR_MESSAGE_TOO_LONG
|
||||
|
||||
def test_rsa_pubkey_invalid(self):
|
||||
from purepycrypto import RSAPublicKey
|
||||
with pytest.raises(PPYC_ERR):
|
||||
RSAPublicKey(15, 3)
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# 5. CLI error handling (exit code + error code)
|
||||
# ======================================================================
|
||||
|
||||
def _run_cli(args, timeout=90):
|
||||
return subprocess.run([sys.executable, "-u", "-m", "purepycrypto"] + list(args),
|
||||
capture_output=True, cwd=_PROJ, timeout=timeout)
|
||||
|
||||
|
||||
def _text(r):
|
||||
return (r.stdout + r.stderr).decode("utf-8", "replace")
|
||||
|
||||
|
||||
def test_cli_bad_algo_exit2():
|
||||
"""argparse choice validation rejects an invalid algorithm name at the entry point (non-zero exit code)."""
|
||||
r = _run_cli(["hash", "--algo", "nope", "--text", "abc"])
|
||||
assert r.returncode != 0
|
||||
# argparse hint format (not PPYC_ERR, because it is intercepted at the validation layer)
|
||||
assert "invalid choice" in _text(r) or "PPYC_ERR" in _text(r)
|
||||
|
||||
|
||||
def test_cli_bad_key_len_exit2():
|
||||
r = _run_cli(["aes", "--mode", "gcm", "--op", "enc", "--text", "x",
|
||||
"--key-hex", "0011", "--nonce-hex", "01" * 12])
|
||||
assert r.returncode == 2
|
||||
assert "PPYC_ERR_INVALID_KEY_LEN" in _text(r)
|
||||
|
||||
|
||||
def test_cli_bad_kdf_param_exit2():
|
||||
"""Invalid KDF parameters must not crash (Traceback); should return exit code 2 + error code."""
|
||||
r = _run_cli(["kdf", "--algo", "scrypt", "--password-hex", "70617373",
|
||||
"--salt-hex", "7361", "--n", "15"])
|
||||
t = _text(r)
|
||||
assert r.returncode == 2, f"should return 2, got {r.returncode}"
|
||||
assert "PPYC_ERR_INVALID_KDF_PARAM" in t
|
||||
assert "Traceback" not in t, "no stack trace should appear"
|
||||
|
||||
|
||||
def test_cli_file_not_found_exit3():
|
||||
r = _run_cli(["hash", "--algo", "sha256", "--in", r"Z:\__nope__.bin"])
|
||||
assert r.returncode == 3
|
||||
|
||||
|
||||
def test_cli_ok_exit0():
|
||||
r = _run_cli(["hash", "--algo", "sha256", "--text", "abc", "--hex"])
|
||||
assert r.returncode == 0
|
||||
assert r.stdout.decode().strip() == (
|
||||
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad")
|
||||
|
||||
|
||||
def test_cli_x25519_bad_len_exit2():
|
||||
"""A CLI x25519 private-key length error should return 2 + INVALID_LENGTH."""
|
||||
r = _run_cli(["x25519", "--op", "base", "--priv-hex", "0011"])
|
||||
t = _text(r)
|
||||
assert r.returncode == 2
|
||||
assert "PPYC_ERR_INVALID_LENGTH" in t
|
||||
assert "Traceback" not in t
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# 6. TUI error handling
|
||||
# ======================================================================
|
||||
|
||||
def _run_tui(stdin_text, timeout=90, lang="cn"):
|
||||
env = dict(os.environ)
|
||||
env["PUREPYCRYPTO_LANG"] = lang
|
||||
return subprocess.run([sys.executable, "-u", "-m", "purepycrypto"],
|
||||
input=stdin_text.encode(), capture_output=True,
|
||||
cwd=_PROJ, timeout=timeout, env=env)
|
||||
|
||||
|
||||
def test_tui_eof_exit2():
|
||||
r = _run_tui("\n")
|
||||
assert r.returncode == 2
|
||||
assert "PPYC_ERR_EOF" in _text(r)
|
||||
|
||||
|
||||
def test_tui_normal_exit0():
|
||||
r = _run_tui("\n1\n1\nabc\n\n0\n0\n")
|
||||
assert r.returncode == 0
|
||||
assert "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" in _text(r)
|
||||
|
||||
|
||||
def test_tui_kdf_bad_param_no_traceback():
|
||||
"""Invalid TUI KDF parameters must not crash."""
|
||||
r = _run_tui("\n5\n3\npw\n7361\n15\n8\n1\n32\n\n0\n0\n")
|
||||
t = _text(r)
|
||||
assert "Traceback" not in t, f"the TUI must not crash: {t[-300:]}"
|
||||
assert "PPYC_ERR" in t
|
||||
|
||||
|
||||
def test_tui_selftest_passes():
|
||||
"""The TUI self-test must fully pass (regression guard)."""
|
||||
r = _run_tui("\n7\n\n0\n", timeout=180)
|
||||
t = _text(r)
|
||||
assert "全部自检通过" in t, f"self-test did not fully pass: {t[-500:]}"
|
||||
@@ -0,0 +1,113 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""AES-GCM-SIV tests (RFC 8452, a nonce-misuse-resistant AEAD)."""
|
||||
import os
|
||||
|
||||
import pytest
|
||||
|
||||
from purepycrypto import (is_err, PPYC_ERR_INVALID_KEY_LEN, PPYC_ERR_INVALID_NONCE_LEN,
|
||||
PPYC_ERR_AUTH_FAILED,
|
||||
aes128_gcm_siv_encrypt, aes128_gcm_siv_decrypt,
|
||||
aes256_gcm_siv_encrypt, aes256_gcm_siv_decrypt,
|
||||
DecryptionError,
|
||||
)
|
||||
|
||||
from ._vectors import load
|
||||
|
||||
|
||||
def test_rfc8452_vectors_file():
|
||||
"""All RFC 8452 Appendix C vectors (48 cases, verified against OpenSSL/cryptography)."""
|
||||
try:
|
||||
vec = load("rfc8452_gcm_siv")
|
||||
except FileNotFoundError:
|
||||
pytest.skip("vectors/rfc8452_gcm_siv.json missing")
|
||||
|
||||
cases = vec.get("cases", [])
|
||||
assert len(cases) >= 10, "unexpected vector count"
|
||||
for case in cases:
|
||||
key = bytes.fromhex(case["key"])
|
||||
nonce = bytes.fromhex(case["nonce"])
|
||||
aad = bytes.fromhex(case.get("aad", ""))
|
||||
pt = bytes.fromhex(case["pt"])
|
||||
result = bytes.fromhex(case["result"].replace(" ", ""))
|
||||
if len(result) >= 16:
|
||||
exp_ct, exp_tag = result[:-16], result[-16:]
|
||||
else:
|
||||
exp_ct, exp_tag = b"", result
|
||||
|
||||
if len(key) == 16:
|
||||
ct, tag = aes128_gcm_siv_encrypt(key, nonce, pt, aad)
|
||||
else:
|
||||
ct, tag = aes256_gcm_siv_encrypt(key, nonce, pt, aad)
|
||||
assert ct == exp_ct, case.get("pt_len")
|
||||
assert tag == exp_tag, case.get("pt_len")
|
||||
|
||||
|
||||
def test_roundtrip_all_lengths():
|
||||
key128 = os.urandom(16)
|
||||
key256 = os.urandom(32)
|
||||
nonce = os.urandom(12)
|
||||
for length in range(0, 81):
|
||||
pt = os.urandom(length)
|
||||
for aad in (b"", b"hdr", os.urandom(20)):
|
||||
ct, tag = aes128_gcm_siv_encrypt(key128, nonce, pt, aad)
|
||||
assert aes128_gcm_siv_decrypt(key128, nonce, ct, tag, aad) == pt
|
||||
ct, tag = aes256_gcm_siv_encrypt(key256, nonce, pt, aad)
|
||||
assert aes256_gcm_siv_decrypt(key256, nonce, ct, tag, aad) == pt
|
||||
|
||||
|
||||
def test_tamper_detection():
|
||||
key = os.urandom(16)
|
||||
nonce = os.urandom(12)
|
||||
ct, tag = aes128_gcm_siv_encrypt(key, nonce, b"secret data", b"aad")
|
||||
|
||||
bad_tag = tag[:-1] + bytes([tag[-1] ^ 1])
|
||||
r = aes128_gcm_siv_decrypt(key, nonce, ct, bad_tag, b"aad")
|
||||
assert is_err(r) and r[0] == PPYC_ERR_AUTH_FAILED
|
||||
|
||||
bad_ct = bytearray(ct)
|
||||
bad_ct[0] ^= 1
|
||||
r = aes128_gcm_siv_decrypt(key, nonce, bytes(bad_ct), tag, b"aad")
|
||||
assert is_err(r) and r[0] == PPYC_ERR_AUTH_FAILED
|
||||
|
||||
r = aes128_gcm_siv_decrypt(key, nonce, ct, tag, b"wrong aad")
|
||||
assert is_err(r) and r[0] == PPYC_ERR_AUTH_FAILED
|
||||
|
||||
|
||||
def test_nonce_misuse_resistance_property():
|
||||
"""Different plaintexts with the same (key,nonce) still produce different tags (a necessary SIV property)."""
|
||||
key = os.urandom(16)
|
||||
nonce = os.urandom(12)
|
||||
_, tag1 = aes128_gcm_siv_encrypt(key, nonce, b"message A")
|
||||
_, tag2 = aes128_gcm_siv_encrypt(key, nonce, b"message B")
|
||||
assert tag1 != tag2
|
||||
|
||||
|
||||
def test_invalid_parameters():
|
||||
r = aes128_gcm_siv_encrypt(b"short", os.urandom(12), b"x")
|
||||
assert is_err(r) and r[0] == PPYC_ERR_INVALID_KEY_LEN
|
||||
r = aes128_gcm_siv_encrypt(os.urandom(16), b"short", b"x")
|
||||
assert is_err(r) and r[0] == PPYC_ERR_INVALID_NONCE_LEN
|
||||
|
||||
|
||||
def test_cross_check_cryptography():
|
||||
"""Cross-check against cryptography's AESGCMSIV."""
|
||||
try:
|
||||
from cryptography.hazmat.primitives.ciphers.aead import AESGCMSIV
|
||||
except ImportError:
|
||||
pytest.skip("cryptography>=45 not installed")
|
||||
|
||||
for _ in range(50):
|
||||
for klen in (16, 32):
|
||||
key = os.urandom(klen)
|
||||
nonce = os.urandom(12)
|
||||
pt = os.urandom(os.urandom(1)[0] % 200)
|
||||
aad = os.urandom(os.urandom(1)[0] % 40)
|
||||
ref = AESGCMSIV(key).encrypt(nonce, pt, aad)
|
||||
ref_ct, ref_tag = ref[:-16], ref[-16:]
|
||||
if klen == 16:
|
||||
ct, tag = aes128_gcm_siv_encrypt(key, nonce, pt, aad)
|
||||
assert aes128_gcm_siv_decrypt(key, nonce, ref_ct, ref_tag, aad) == pt
|
||||
else:
|
||||
ct, tag = aes256_gcm_siv_encrypt(key, nonce, pt, aad)
|
||||
assert aes256_gcm_siv_decrypt(key, nonce, ref_ct, ref_tag, aad) == pt
|
||||
assert ct == ref_ct and tag == ref_tag
|
||||
@@ -0,0 +1,74 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Hash module tests (SHA-256 / SHA-512 / BLAKE2b)."""
|
||||
import hashlib
|
||||
import os
|
||||
|
||||
import pytest
|
||||
|
||||
from purepycrypto import sha256, sha512, blake2b
|
||||
from purepycrypto._ppyc_error import is_err
|
||||
|
||||
from ._vectors import load
|
||||
|
||||
|
||||
def test_sha256_standard():
|
||||
assert sha256(b"").hex() == (
|
||||
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855")
|
||||
assert sha256(b"abc").hex() == (
|
||||
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad")
|
||||
assert sha256(b"message digest").hex() == (
|
||||
"f7846f55cf23e14eebeab5b4e1550cad5b509e3348fbc4efa3a1413d393cb650")
|
||||
|
||||
|
||||
def test_sha512_standard():
|
||||
assert sha512(b"").hex() == (
|
||||
"cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce"
|
||||
"47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e")
|
||||
assert sha512(b"abc").hex() == (
|
||||
"ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a"
|
||||
"2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f")
|
||||
|
||||
|
||||
def test_blake2b_standard():
|
||||
assert blake2b(b"abc", 64).hex() == (
|
||||
"ba80a53f981c4d0d6a2797b69f12f6e94c212f14685ac4b74b12bb6fdbffa2d1"
|
||||
"7d87c5392aab792dc252d5de4533cc9518d38aa8dbf1925ab92386edd4009923")
|
||||
assert blake2b(b"", 64).hex() == (
|
||||
"786a02f742015903c6c6fd852552d272912f4740e15847618a86e217f71f5419"
|
||||
"d25e1031afee585313896444934eb04b903a685b1448b755d56f701afe9be2ce")
|
||||
|
||||
|
||||
def test_blake2b_digest_size_range():
|
||||
for n in (1, 16, 32, 48, 64):
|
||||
assert len(blake2b(b"data", n)) == n
|
||||
# Unified error scheme: an invalid digest_size no longer raises, it returns a 3-tuple error result
|
||||
for bad in (0, 65, -1):
|
||||
r = blake2b(b"data", bad)
|
||||
assert isinstance(r, tuple) and len(r) == 3
|
||||
assert r[0] == "PPYC_ERR_INVALID_ARG"
|
||||
assert r[1] and isinstance(r[2], str)
|
||||
|
||||
|
||||
def test_random_consistency_with_hashlib():
|
||||
"""Random data across many lengths should match hashlib (including cross-block boundaries)."""
|
||||
# cover block boundaries (multiples of 128 were once a known defect)
|
||||
for length in (0, 1, 55, 56, 63, 64, 65, 119, 120, 127, 128, 129,
|
||||
255, 256, 257, 384, 1000):
|
||||
data = os.urandom(length)
|
||||
assert sha256(data) == hashlib.sha256(data).digest()
|
||||
assert sha512(data) == hashlib.sha512(data).digest()
|
||||
assert blake2b(data, 64) == hashlib.blake2b(data, digest_size=64).digest()
|
||||
|
||||
|
||||
def test_vectors_file():
|
||||
try:
|
||||
vec = load("sha2")
|
||||
except FileNotFoundError:
|
||||
pytest.skip("vectors/sha2.json missing")
|
||||
for case in vec.get("cases", []):
|
||||
if "digest_hex" not in case:
|
||||
continue
|
||||
msg = case.get("msg_utf8", "").encode("utf-8")
|
||||
algo = case["algorithm"]
|
||||
fn = {"sha256": sha256, "sha512": sha512}[algo]
|
||||
assert fn(msg).hex() == case["digest_hex"], case.get("id")
|
||||
@@ -0,0 +1,124 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Key-derivation module tests (HMAC / PBKDF2 / HKDF / scrypt / Argon2id)."""
|
||||
import hashlib
|
||||
import hmac as _hmac
|
||||
import os
|
||||
|
||||
import pytest
|
||||
|
||||
from purepycrypto import (
|
||||
hmac_sha256, hmac_sha512, pbkdf2_hmac, hkdf,
|
||||
hkdf_extract, hkdf_expand, scrypt, argon2id,
|
||||
)
|
||||
|
||||
from purepycrypto._ppyc_error import is_err
|
||||
|
||||
from ._vectors import load
|
||||
|
||||
|
||||
def test_hmac_matches_stdlib():
|
||||
key = os.urandom(40)
|
||||
msg = os.urandom(100)
|
||||
assert hmac_sha256(key, msg) == _hmac.new(key, msg, hashlib.sha256).digest()
|
||||
assert hmac_sha512(key, msg) == _hmac.new(key, msg, hashlib.sha512).digest()
|
||||
|
||||
|
||||
def test_hmac_long_key():
|
||||
"""Keys longer than the block size should be hashed first."""
|
||||
key = os.urandom(200)
|
||||
assert hmac_sha256(key, b"m") == _hmac.new(key, b"m", hashlib.sha256).digest()
|
||||
|
||||
|
||||
def test_pbkdf2_matches_hashlib():
|
||||
for h in ("sha256", "sha512"):
|
||||
got = pbkdf2_hmac(b"password", b"salt", 1000, 40, h)
|
||||
exp = hashlib.pbkdf2_hmac(h, b"password", b"salt", 1000, 40)
|
||||
assert got == exp
|
||||
|
||||
|
||||
def test_pbkdf2_standard_vector():
|
||||
assert pbkdf2_hmac(b"passwd", b"salt", 1, 64, "sha256").hex() == (
|
||||
"55ac046e56e3089fec1691c22544b605f94185216dde0465e68b9d57c20dacbc"
|
||||
"49ca9cccf179b645991664b39d77ef317c71b845b1e30bd509112041d3a19783")
|
||||
|
||||
|
||||
def test_pbkdf2_invalid():
|
||||
# Unified error scheme: invalid parameters return a 3-tuple instead of raising
|
||||
for args, exp_code in (
|
||||
((b"p", b"s", 0, 32), "PPYC_ERR_INVALID_KDF_PARAM"),
|
||||
((b"p", b"s", 1, 0), "PPYC_ERR_INVALID_KDF_PARAM"),
|
||||
((b"p", b"s", 1, 32, "md5"), "PPYC_ERR_INVALID_ALGO"),
|
||||
):
|
||||
r = pbkdf2_hmac(*args)
|
||||
assert is_err(r), r
|
||||
assert r[0] == exp_code
|
||||
|
||||
|
||||
def test_hkdf_rfc5869_tc1():
|
||||
ikm = bytes.fromhex("0b" * 22)
|
||||
salt = bytes.fromhex("000102030405060708090a0b0c")
|
||||
info = bytes.fromhex("f0f1f2f3f4f5f6f7f8f9")
|
||||
prk = hkdf_extract(salt, ikm, "sha256")
|
||||
assert prk.hex() == (
|
||||
"077709362c2e32df0ddc3f0dc47bba6390b6c73bb50f9c3122ec844ad7c2b3e5")
|
||||
okm = hkdf_expand(prk, info, 42, "sha256")
|
||||
assert okm.hex() == (
|
||||
"3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf"
|
||||
"34007208d5b887185865")
|
||||
|
||||
|
||||
def test_hkdf_rfc5869_tc3_empty_salt_info():
|
||||
ikm = bytes.fromhex("0b" * 22)
|
||||
prk = hkdf_extract(b"", ikm, "sha256")
|
||||
assert prk.hex() == (
|
||||
"19ef24a32c717b167f33a91d6f648bdf96596776afdb6377ac434c1c293ccb04")
|
||||
okm = hkdf_expand(prk, b"", 42, "sha256")
|
||||
assert okm.hex() == (
|
||||
"8da4e775a563c18f715f802a063c5a31b8a11f5c5ee1879ec3454e5f3c738d2d"
|
||||
"9d201395faa4b61a96c8")
|
||||
|
||||
|
||||
def test_scrypt_rfc7914():
|
||||
assert scrypt(b"", b"", N=16, r=1, p=1, dklen=64).hex() == (
|
||||
"77d6576238657b203b19ca42c18a0497f16b4844e3074ae8dfdffa3fede21442"
|
||||
"fcd0069ded0948f8326a753a0fc81f17e8d3e0fb2e0d3628cf35e20c38d18906")
|
||||
assert scrypt(b"password", b"NaCl", N=1024, r=8, p=16, dklen=64).hex() == (
|
||||
"fdbabe1c9d3472007856e7190d01e9fe7c6ad7cbc8237830e77376634b373162"
|
||||
"2eaf30d92e22a3886ff109279d9830dac727afb94a83ee6d8360cbdfa2cc0640")
|
||||
|
||||
|
||||
def test_scrypt_matches_hashlib():
|
||||
got = scrypt(b"pleaseletmein", b"SodiumChloride", N=16384, r=8, p=1, dklen=64)
|
||||
exp = hashlib.scrypt(b"pleaseletmein", salt=b"SodiumChloride",
|
||||
n=16384, r=8, p=1, dklen=64)
|
||||
assert got == exp
|
||||
|
||||
|
||||
def test_scrypt_invalid():
|
||||
r = scrypt(b"p", b"s", N=15, r=8, p=1) # not a power of two
|
||||
assert is_err(r) and r[0] == "PPYC_ERR_INVALID_KDF_PARAM"
|
||||
r = scrypt(b"p", b"s", N=16, r=0, p=1)
|
||||
assert is_err(r) and r[0] == "PPYC_ERR_INVALID_KDF_PARAM"
|
||||
|
||||
|
||||
def test_argon2id_rfc9106():
|
||||
tag = argon2id(b"\x01" * 32, b"\x02" * 16, t=3, m=32, p=4, tag_length=32,
|
||||
secret=b"\x03" * 8, ad=b"\x04" * 12)
|
||||
assert tag.hex() == (
|
||||
"0d640df58d78766c08c037a34a8b53c9d01ef0452d75b65eb52520e96b01e659")
|
||||
|
||||
|
||||
def test_argon2id_invalid():
|
||||
for kw in (dict(t=0), dict(m=4, p=4), dict(tag_length=2), dict(p=0)):
|
||||
r = argon2id(b"p", b"s", **kw)
|
||||
assert is_err(r), (kw, r)
|
||||
assert r[0] == "PPYC_ERR_INVALID_KDF_PARAM"
|
||||
|
||||
|
||||
def test_vectors_files():
|
||||
for name in ("pbkdf2", "scrypt", "hkdf_rfc5869", "argon2id_rfc9106"):
|
||||
try:
|
||||
vec = load(name)
|
||||
except FileNotFoundError:
|
||||
continue
|
||||
assert "cases" in vec or "vectors" in vec or isinstance(vec, dict)
|
||||
@@ -0,0 +1,393 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Strengthened key-derivation module tests (``purepycrypto.kdf2``).
|
||||
|
||||
Coverage:
|
||||
* Pure-Python SHA-1 / SHA-384 byte-for-byte identical to :mod:`hashlib`;
|
||||
* HMAC-SHA1/256/384/512 identical to :mod:`hmac`;
|
||||
* PBKDF2 byte-for-byte identical to :func:`hashlib.pbkdf2_hmac`
|
||||
(sha1/sha256/sha512 x iterations 1/1000/10000 x dklen 20/32/64),
|
||||
plus the RFC 6070 official vectors;
|
||||
* Argon2d / Argon2i / Argon2id pass the RFC 9106 §5 official test vectors;
|
||||
* Argon2 interoperability with ``argon2-cffi`` (raw derivation + PHC encoding parsing, if installed);
|
||||
* PHC string encode/decode and constant-time verification;
|
||||
* HKDF (RFC 5869) vectors and the multi-key convenience helper;
|
||||
* scrypt convenience wrapper (RFC 7914) matching :func:`hashlib.scrypt`;
|
||||
* all invalid parameters return an ``err(...)`` 3-tuple (instead of raising).
|
||||
|
||||
Note
|
||||
----
|
||||
PBKDF2 with 10000 iterations is heavy in **pure Python** (a single sha256/sha512 hash takes about
|
||||
1 minute). For quick feedback in constrained environments, run in batches with ``-k``, for example::
|
||||
|
||||
pytest tests/test_kdf2.py -q -k "not 10k" # all fast cases
|
||||
pytest tests/test_kdf2.py -q -k "10k and sha1" # only the sha1 10k cases
|
||||
"""
|
||||
import hashlib
|
||||
import hmac as _stdlib_hmac
|
||||
import os
|
||||
|
||||
import pytest
|
||||
|
||||
from purepycrypto import kdf2
|
||||
from purepycrypto.kdf2 import (
|
||||
pbkdf2, pbkdf2_hmac,
|
||||
sha1, sha384,
|
||||
hmac_sha1, hmac_sha256, hmac_sha384, hmac_sha512,
|
||||
argon2_hash, argon2id_hash, argon2i_hash, argon2d_hash,
|
||||
argon2_verify, argon2id_verify, argon2i_verify, argon2d_verify,
|
||||
argon2id_hash_encoded, argon2i_hash_encoded, argon2d_hash_encoded,
|
||||
argon2_verify_encoded,
|
||||
hkdf, hkdf_extract, hkdf_expand, hkdf_expand_multi,
|
||||
scrypt, scrypt_simple, SCRYPT_RECOMMENDED,
|
||||
)
|
||||
from purepycrypto._ppyc_error import is_err
|
||||
|
||||
# argon2-cffi is an optional dependency, used only for interop verification
|
||||
try:
|
||||
from argon2.low_level import (
|
||||
hash_secret_raw, verify_secret, hash_secret, Type,
|
||||
)
|
||||
_HAS_ARGON2CFFI = True
|
||||
except ImportError: # pragma: no cover
|
||||
_HAS_ARGON2CFFI = False
|
||||
|
||||
# Provide a placeholder when argon2-cffi is missing: the module-level @pytest.mark.parametrize
|
||||
# evaluates Type.ID / Type.I / Type.D at collection time, and missing attributes would break collection of the whole suite.
|
||||
class _TypeStub: # noqa: D401
|
||||
"""Placeholder for the argon2-cffi Type enum (the value is only used as a parametrization id and never actually runs)."""
|
||||
ID = "ID"
|
||||
I = "I"
|
||||
D = "D"
|
||||
|
||||
Type = _TypeStub
|
||||
|
||||
_SALT = b"0123456789abcdef" # 16-byte salt
|
||||
_PWD = b"password123"
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# 0. Pure-Python SHA-1 / SHA-384
|
||||
# ======================================================================
|
||||
|
||||
@pytest.mark.parametrize("msg", [
|
||||
b"", b"abc", b"a" * 55, b"a" * 56, b"a" * 63, b"a" * 64,
|
||||
b"a" * 111, b"a" * 112, b"a" * 128, b"a" * 1000, bytes(range(256)),
|
||||
])
|
||||
def test_sha1_sha384_match_hashlib(msg):
|
||||
assert sha1(msg) == hashlib.sha1(msg).digest()
|
||||
assert sha384(msg) == hashlib.sha384(msg).digest()
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# 1. HMAC-SHA1/256/384/512
|
||||
# ======================================================================
|
||||
|
||||
@pytest.mark.parametrize("key_len", [0, 20, 63, 64, 65, 128, 129, 200])
|
||||
def test_hmac_match_stdlib(key_len):
|
||||
key = os.urandom(key_len)
|
||||
msg = b"message-block" * 10
|
||||
assert hmac_sha1(key, msg) == _stdlib_hmac.new(key, msg, hashlib.sha1).digest()
|
||||
assert hmac_sha256(key, msg) == _stdlib_hmac.new(key, msg, hashlib.sha256).digest()
|
||||
assert hmac_sha384(key, msg) == _stdlib_hmac.new(key, msg, hashlib.sha384).digest()
|
||||
assert hmac_sha512(key, msg) == _stdlib_hmac.new(key, msg, hashlib.sha512).digest()
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# 2. PBKDF2 (RFC 8018) -- byte-for-byte identical to hashlib
|
||||
# ======================================================================
|
||||
|
||||
@pytest.mark.parametrize("hash_name", ["sha1", "sha256", "sha512"])
|
||||
@pytest.mark.parametrize("iterations", [1, 1000])
|
||||
@pytest.mark.parametrize("dklen", [20, 32, 64])
|
||||
def test_pbkdf2_matches_hashlib(hash_name, iterations, dklen):
|
||||
got = pbkdf2(b"password", _SALT, iterations, dklen, hash_name)
|
||||
exp = hashlib.pbkdf2_hmac(hash_name, b"password", _SALT, iterations, dklen)
|
||||
assert got == exp
|
||||
|
||||
|
||||
@pytest.mark.parametrize("dklen", [20, 32, 64])
|
||||
def test_pbkdf2_sha384_matches_hashlib(dklen):
|
||||
got = pbkdf2(b"password", _SALT, 100, dklen, "sha384")
|
||||
exp = hashlib.pbkdf2_hmac("sha384", b"password", _SALT, 100, dklen)
|
||||
assert got == exp
|
||||
|
||||
|
||||
# -- heavy 10000-iteration cases: parametrized by hash_name x dklen, for easy -k batching --
|
||||
@pytest.mark.parametrize("hash_name", ["sha1", "sha256", "sha512"])
|
||||
@pytest.mark.parametrize("dklen", [20, 32, 64])
|
||||
def test_pbkdf2_matches_hashlib_10k(hash_name, dklen):
|
||||
got = pbkdf2(b"password", _SALT, 10000, dklen, hash_name)
|
||||
exp = hashlib.pbkdf2_hmac(hash_name, b"password", _SALT, 10000, dklen)
|
||||
assert got == exp
|
||||
|
||||
|
||||
def test_pbkdf2_alias():
|
||||
assert pbkdf2_hmac is pbkdf2
|
||||
|
||||
|
||||
def test_pbkdf2_min_salt_len_override():
|
||||
"""Short salts can be used only after explicitly relaxing min_salt_len (for legacy systems)."""
|
||||
got = pbkdf2(b"password", b"salt", 2, 20, "sha1", min_salt_len=0)
|
||||
assert got == hashlib.pbkdf2_hmac("sha1", b"password", b"salt", 2, 20)
|
||||
|
||||
|
||||
# RFC 6070: PBKDF2-HMAC-SHA1 official vectors (short salt, requires min_salt_len=0)
|
||||
@pytest.mark.parametrize("password,salt,iters,dklen,expect", [
|
||||
(b"password", b"salt", 1, 20,
|
||||
"0c60c80f961f0e71f3a9b524af6012062fe037a6"),
|
||||
(b"password", b"salt", 2, 20,
|
||||
"ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957"),
|
||||
(b"password", b"salt", 4096, 20,
|
||||
"4b007901b765489abead49d926f721d065a429c1"),
|
||||
])
|
||||
def test_pbkdf2_rfc6070_sha1(password, salt, iters, dklen, expect):
|
||||
got = pbkdf2(password, salt, iters, dklen, "sha1", min_salt_len=0)
|
||||
assert got.hex() == expect
|
||||
|
||||
|
||||
def test_pbkdf2_invalid_params():
|
||||
# iterations < 1
|
||||
r = pbkdf2(b"p", _SALT, 0, 32)
|
||||
assert is_err(r) and r[0] == "PPYC_ERR_INVALID_KDF_PARAM"
|
||||
# dklen < 1
|
||||
r = pbkdf2(b"p", _SALT, 1, 0)
|
||||
assert is_err(r) and r[0] == "PPYC_ERR_INVALID_KDF_PARAM"
|
||||
# non-integer iterations
|
||||
r = pbkdf2(b"p", _SALT, 1.5, 32)
|
||||
assert is_err(r) and r[0] == "PPYC_ERR_INVALID_KDF_PARAM"
|
||||
# invalid algorithm
|
||||
r = pbkdf2(b"p", _SALT, 1, 32, "md5")
|
||||
assert is_err(r) and r[0] == "PPYC_ERR_INVALID_ALGO"
|
||||
r = pbkdf2(b"p", _SALT, 1, 32, None)
|
||||
assert is_err(r) and r[0] == "PPYC_ERR_INVALID_ALGO"
|
||||
# salt too short
|
||||
r = pbkdf2(b"p", b"short", 1, 32)
|
||||
assert is_err(r) and r[0] == "PPYC_ERR_INVALID_SALT"
|
||||
# invalid type
|
||||
r = pbkdf2("p", _SALT, 1, 32)
|
||||
assert is_err(r) and r[0] == "PPYC_ERR_INVALID_ARG"
|
||||
r = pbkdf2(b"p", "saltlonger9", 1, 32)
|
||||
assert is_err(r) and r[0] == "PPYC_ERR_INVALID_ARG"
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# 3. Argon2 (RFC 9106)
|
||||
# ======================================================================
|
||||
|
||||
_ARGON2_PWD = b"\x01" * 32
|
||||
_ARGON2_SALT = b"\x02" * 16
|
||||
_ARGON2_SECRET = b"\x03" * 8
|
||||
_ARGON2_AD = b"\x04" * 12
|
||||
_RFC9106_KW = dict(t=3, m=32, p=4, tag_length=32,
|
||||
secret=_ARGON2_SECRET, ad=_ARGON2_AD)
|
||||
|
||||
|
||||
def test_argon2_rfc9106_vectors():
|
||||
"""RFC 9106 §5 official test vectors (three variants)."""
|
||||
assert argon2d_hash(_ARGON2_PWD, _ARGON2_SALT, **_RFC9106_KW).hex() == (
|
||||
"512b391b6f1162975371d30919734294"
|
||||
"f868e3be3984f3c1a13a4db9fabe4acb")
|
||||
assert argon2i_hash(_ARGON2_PWD, _ARGON2_SALT, **_RFC9106_KW).hex() == (
|
||||
"c814d9d1dc7f37aa13f0d77f2494bda1"
|
||||
"c8de6b016dd388d29952a4c4672b6ce8")
|
||||
assert argon2id_hash(_ARGON2_PWD, _ARGON2_SALT, **_RFC9106_KW).hex() == (
|
||||
"0d640df58d78766c08c037a34a8b53c9"
|
||||
"d01ef0452d75b65eb52520e96b01e659")
|
||||
|
||||
|
||||
def test_argon2_hash_dispatch_matches_variants():
|
||||
a = argon2_hash(_ARGON2_PWD, _ARGON2_SALT, "argon2id", **_RFC9106_KW)
|
||||
b = argon2id_hash(_ARGON2_PWD, _ARGON2_SALT, **_RFC9106_KW)
|
||||
assert a == b
|
||||
|
||||
|
||||
@pytest.mark.skipif(not _HAS_ARGON2CFFI, reason="argon2-cffi not installed")
|
||||
@pytest.mark.parametrize("variant,ctype", [
|
||||
("argon2id", Type.ID), ("argon2i", Type.I), ("argon2d", Type.D),
|
||||
])
|
||||
def test_argon2_interop_argon2cffi(variant, ctype):
|
||||
"""Byte-for-byte identical to the argon2-cffi low-level primitives (no secret/ad)."""
|
||||
got = argon2_hash(_PWD, _SALT, variant, t=3, m=64, p=4, tag_length=32)
|
||||
exp = hash_secret_raw(_PWD, _SALT, time_cost=3, memory_cost=64,
|
||||
parallelism=4, hash_len=32, type=ctype, version=19)
|
||||
assert got == exp
|
||||
|
||||
|
||||
def test_argon2id_verify():
|
||||
tag = argon2id_hash(_PWD, _SALT, t=3, m=64, p=4)
|
||||
assert argon2id_verify(_PWD, _SALT, tag, t=3, m=64, p=4) is True
|
||||
assert is_err(argon2id_verify(b"wrong", _SALT, tag, t=3, m=64, p=4))
|
||||
|
||||
|
||||
def test_argon2i_d_verify():
|
||||
tag_i = argon2i_hash(_PWD, _SALT, t=3, m=64, p=4)
|
||||
assert argon2i_verify(_PWD, _SALT, tag_i, t=3, m=64, p=4) is True
|
||||
assert is_err(argon2i_verify(b"no", _SALT, tag_i, t=3, m=64, p=4))
|
||||
tag_d = argon2d_hash(_PWD, _SALT, t=3, m=64, p=4)
|
||||
assert argon2d_verify(_PWD, _SALT, tag_d, t=3, m=64, p=4) is True
|
||||
assert is_err(argon2d_verify(b"no", _SALT, tag_d, t=3, m=64, p=4))
|
||||
|
||||
|
||||
def test_argon2_verify_generic_and_type_error():
|
||||
tag = argon2id_hash(_PWD, _SALT, t=3, m=64, p=4)
|
||||
assert argon2_verify(_PWD, _SALT, tag, variant="argon2id",
|
||||
t=3, m=64, p=4) is True
|
||||
r = argon2_verify(_PWD, _SALT, "nottag", t=3, m=64, p=4)
|
||||
assert is_err(r) and r[0] == "PPYC_ERR_INVALID_ARG"
|
||||
r = argon2_verify(_PWD, _SALT, b"\x00\x01", t=3, m=64, p=4)
|
||||
assert is_err(r) and r[0] == "PPYC_ERR_INVALID_LENGTH"
|
||||
|
||||
|
||||
# -- PHC encoding --
|
||||
|
||||
def test_argon2id_phc_format():
|
||||
enc = argon2id_hash_encoded(_PWD, _SALT, t=3, m=64, p=4, tag_length=32)
|
||||
assert enc.startswith("$argon2id$v=19$m=64,t=3,p=4$")
|
||||
parts = enc.split("$")
|
||||
assert len(parts) == 6
|
||||
# Base64 without padding
|
||||
assert "=" not in parts[4] and "=" not in parts[5]
|
||||
|
||||
|
||||
def test_argon2_phc_roundtrip_and_verify():
|
||||
enc = argon2id_hash_encoded(_PWD, _SALT, t=3, m=64, p=4)
|
||||
assert argon2_verify_encoded(_PWD, enc) is True
|
||||
assert is_err(argon2_verify_encoded(b"wrong", enc))
|
||||
|
||||
|
||||
def test_argon2_phc_malformed():
|
||||
for bad in ("", "not-a-phc", "$argon2id$v=19$m=64,t=3$abc$def",
|
||||
"$argon2x$v=19$m=64,t=3,p=4$abc$def"):
|
||||
r = argon2_verify_encoded(_PWD, bad)
|
||||
assert is_err(r), bad
|
||||
|
||||
|
||||
@pytest.mark.skipif(not _HAS_ARGON2CFFI, reason="argon2-cffi not installed")
|
||||
def test_argon2id_phc_parsed_by_argon2cffi():
|
||||
"""The PHC strings we produce can be parsed and verified by argon2-cffi."""
|
||||
enc = argon2id_hash_encoded(_PWD, _SALT, t=3, m=64, p=4)
|
||||
assert verify_secret(enc.encode(), _PWD, Type.ID) is True
|
||||
# can also parse strings produced by argon2-cffi itself (using the same small parameters)
|
||||
cffi_enc = hash_secret(_PWD, _SALT, time_cost=3, memory_cost=64,
|
||||
parallelism=4, hash_len=32, type=Type.ID)
|
||||
assert kdf2.argon2_verify_encoded(_PWD, cffi_enc.decode()) is True
|
||||
|
||||
|
||||
def test_argon2_invalid_params():
|
||||
cases = [
|
||||
(dict(t=0), "PPYC_ERR_INVALID_KDF_PARAM"),
|
||||
(dict(p=0), "PPYC_ERR_INVALID_KDF_PARAM"),
|
||||
(dict(m=4, p=4), "PPYC_ERR_INVALID_KDF_PARAM"),
|
||||
(dict(tag_length=2), "PPYC_ERR_INVALID_KDF_PARAM"),
|
||||
(dict(version=0x12), "PPYC_ERR_INVALID_KDF_PARAM"),
|
||||
(dict(t=1.5), "PPYC_ERR_INVALID_KDF_PARAM"),
|
||||
]
|
||||
for kw, code in cases:
|
||||
r = argon2id_hash(_PWD, _SALT, **kw)
|
||||
assert is_err(r) and r[0] == code, (kw, r)
|
||||
|
||||
|
||||
def test_argon2_invalid_variant_salt_type():
|
||||
r = argon2_hash(_PWD, _SALT, variant="argon2x")
|
||||
assert is_err(r) and r[0] == "PPYC_ERR_INVALID_ALGO"
|
||||
r = argon2id_hash(_PWD, b"short", t=3, m=64, p=4)
|
||||
assert is_err(r) and r[0] == "PPYC_ERR_INVALID_SALT"
|
||||
r = argon2id_hash("pw", _SALT, t=3, m=64, p=4)
|
||||
assert is_err(r) and r[0] == "PPYC_ERR_INVALID_ARG"
|
||||
r = argon2id_hash(b"", _SALT, t=3, m=64, p=4)
|
||||
assert is_err(r) and r[0] == "PPYC_ERR_INVALID_KDF_PARAM"
|
||||
|
||||
|
||||
def test_argon2_encoded_invalid():
|
||||
r = kdf2.argon2_hash_encoded(_PWD, _SALT, variant="nope")
|
||||
assert is_err(r) and r[0] == "PPYC_ERR_INVALID_ALGO"
|
||||
r = argon2i_hash_encoded(_PWD, _SALT, t=3, m=64, p=4)
|
||||
assert r.startswith("$argon2i$v=19$")
|
||||
r = argon2d_hash_encoded(_PWD, _SALT, t=3, m=64, p=4)
|
||||
assert r.startswith("$argon2d$v=19$")
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# 4. HKDF (RFC 5869)
|
||||
# ======================================================================
|
||||
|
||||
def test_hkdf_rfc5869_tc1():
|
||||
ikm = bytes.fromhex("0b" * 22)
|
||||
salt = bytes.fromhex("000102030405060708090a0b0c")
|
||||
info = bytes.fromhex("f0f1f2f3f4f5f6f7f8f9")
|
||||
prk = hkdf_extract(salt, ikm, "sha256")
|
||||
assert prk.hex() == (
|
||||
"077709362c2e32df0ddc3f0dc47bba6390b6c73bb50f9c3122ec844ad7c2b3e5")
|
||||
assert hkdf_expand(prk, info, 42, "sha256").hex() == (
|
||||
"3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf"
|
||||
"34007208d5b887185865")
|
||||
|
||||
|
||||
def test_hkdf_convenience():
|
||||
ikm = bytes.fromhex("0b" * 22)
|
||||
salt = bytes.fromhex("000102030405060708090a0b0c")
|
||||
info = bytes.fromhex("f0f1f2f3f4f5f6f7f8f9")
|
||||
prk = hkdf_extract(salt, ikm, "sha256")
|
||||
assert hkdf(ikm, salt, info, 42, "sha256") == hkdf_expand(prk, info, 42, "sha256")
|
||||
|
||||
|
||||
def test_hkdf_expand_multi():
|
||||
prk = hkdf_extract(b"", bytes.fromhex("0b" * 22), "sha256")
|
||||
outs = hkdf_expand_multi(prk, [(b"enc", 16), (b"mac", 32)], "sha256")
|
||||
assert isinstance(outs, list) and len(outs) == 2
|
||||
assert len(outs[0]) == 16 and len(outs[1]) == 32
|
||||
assert outs[0] == hkdf_expand(prk, b"enc", 16, "sha256")
|
||||
assert outs[1] == hkdf_expand(prk, b"mac", 32, "sha256")
|
||||
# malformed structure
|
||||
assert is_err(hkdf_expand_multi(prk, "bad"))
|
||||
|
||||
|
||||
def test_hkdf_invalid():
|
||||
r = hkdf_expand(b"prk", b"", 0)
|
||||
assert is_err(r) and r[0] == "PPYC_ERR_INVALID_KDF_PARAM"
|
||||
r = hkdf_extract(b"salt", b"ikm", "md5")
|
||||
assert is_err(r) and r[0] == "PPYC_ERR_INVALID_ALGO"
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# 5. scrypt (RFC 7914)
|
||||
# ======================================================================
|
||||
|
||||
def test_scrypt_simple_rfc7914():
|
||||
assert scrypt_simple(b"", b"", n=16, r=1, p=1, dklen=64,
|
||||
min_salt_len=0).hex() == (
|
||||
"77d6576238657b203b19ca42c18a0497f16b4844e3074ae8dfdffa3fede21442"
|
||||
"fcd0069ded0948f8326a753a0fc81f17e8d3e0fb2e0d3628cf35e20c38d18906")
|
||||
|
||||
|
||||
def test_scrypt_simple_matches_hashlib():
|
||||
got = scrypt_simple(b"pleaseletmein", b"SodiumChloride",
|
||||
n=2 ** 14, r=8, p=1, dklen=64)
|
||||
exp = hashlib.scrypt(b"pleaseletmein", salt=b"SodiumChloride",
|
||||
n=2 ** 14, r=8, p=1, dklen=64)
|
||||
assert got == exp
|
||||
|
||||
|
||||
def test_scrypt_recommended_const():
|
||||
n, r, p, dklen = SCRYPT_RECOMMENDED
|
||||
assert n == 2 ** 15 and r == 8 and p == 1 and dklen == 32
|
||||
|
||||
|
||||
def test_scrypt_simple_invalid():
|
||||
# salt too short
|
||||
r = scrypt_simple(b"p", b"short")
|
||||
assert is_err(r) and r[0] == "PPYC_ERR_INVALID_SALT"
|
||||
# not a power of two
|
||||
r = scrypt_simple(b"p", _SALT, n=15)
|
||||
assert is_err(r) and r[0] == "PPYC_ERR_INVALID_KDF_PARAM"
|
||||
# invalid r / p / dklen
|
||||
for kw in (dict(r=0), dict(p=0), dict(dklen=0)):
|
||||
r = scrypt_simple(b"p", _SALT, **kw)
|
||||
assert is_err(r) and r[0] == "PPYC_ERR_INVALID_KDF_PARAM", kw
|
||||
# invalid type
|
||||
r = scrypt_simple("p", _SALT)
|
||||
assert is_err(r) and r[0] == "PPYC_ERR_INVALID_ARG"
|
||||
|
||||
|
||||
def test_scrypt_simple_reexports_scrypt():
|
||||
assert scrypt is kdf2.scrypt
|
||||
@@ -0,0 +1,299 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Independent review of purepycrypto.kdf2 (new module in v3.2.0).
|
||||
|
||||
Verification strategy (**independent of the module's own tests**):
|
||||
* PBKDF2 byte-for-byte comparison with ``hashlib.pbkdf2_hmac``
|
||||
(sha1/sha256/sha512 x iterations 1/1000/10000 x dklen 20/32/64);
|
||||
* Pure-Python SHA-1 / SHA-384 compared with hashlib (including FIPS known vectors);
|
||||
* HMAC-SHA1/256/384/512 compared with the stdlib ``hmac`` (including an oversized key);
|
||||
* RFC 9106 §5 official Argon2 vectors (argon2id / argon2i / argon2d);
|
||||
* byte-for-byte cross-check against ``argon2-cffi`` (C implementation); its PHC strings are parsed/verified;
|
||||
* argon2id_verify / argon2_verify_encoded with correct/incorrect passwords;
|
||||
* scrypt_simple compared with ``hashlib.scrypt``;
|
||||
* non-fatal errors must return a ``(PPYC_ERR_xxx, msg, suggestion)`` tuple.
|
||||
|
||||
Note: this module is a pure-Python implementation, so 10000-iteration PBKDF2 is quite slow;
|
||||
therefore the heavy PBKDF2 cases in this file should be split across multiple subprocesses (each <60s).
|
||||
"""
|
||||
import hashlib
|
||||
import hmac as _hmac
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
_HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
_PKG_PARENT = os.path.dirname(_HERE)
|
||||
if _PKG_PARENT not in sys.path:
|
||||
sys.path.insert(0, _PKG_PARENT)
|
||||
|
||||
from purepycrypto import kdf2 as K # noqa: E402
|
||||
from purepycrypto._ppyc_error import PPYC_ERR_PREFIX # noqa: E402
|
||||
|
||||
_SALT = b"0123456789abcdef" # 16 bytes >= 8
|
||||
_PW = b"correct horse battery staple"
|
||||
|
||||
|
||||
def _is_err(v):
|
||||
return (isinstance(v, tuple) and len(v) == 3
|
||||
and isinstance(v[0], str) and v[0].startswith(PPYC_ERR_PREFIX))
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# 1. PBKDF2 -- byte-for-byte comparison with hashlib
|
||||
# ======================================================================
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"hash_name,iterations,dklen",
|
||||
[(h, i, d) for h in ("sha1", "sha256", "sha512")
|
||||
for i in (1, 1000, 10000) for d in (20, 32, 64)],
|
||||
ids=lambda v: str(v),
|
||||
)
|
||||
def test_pbkdf2_matches_hashlib(hash_name, iterations, dklen):
|
||||
got = K.pbkdf2(_PW, _SALT, iterations, dklen, hash_name=hash_name)
|
||||
ref = hashlib.pbkdf2_hmac(hash_name, _PW, _SALT, iterations, dklen)
|
||||
assert not _is_err(got), got
|
||||
assert isinstance(got, bytes) and len(got) == dklen
|
||||
assert got == ref
|
||||
# the compatibility alias is equivalent
|
||||
assert K.pbkdf2_hmac(_PW, _SALT, iterations, dklen, hash_name=hash_name) == ref
|
||||
|
||||
|
||||
def test_pbkdf2_matches_hashlib_edge_inputs():
|
||||
# empty password, short salt (min_salt_len relaxed), various dklen boundaries
|
||||
cases = [
|
||||
(b"", b"12345678", 1, 1, "sha256"),
|
||||
(b"p", b"12345678", 2, 7, "sha256"),
|
||||
(os.urandom(100), os.urandom(9), 3, 100, "sha256"),
|
||||
(b"xf", b"abcdefgh", 5, 20, "sha256"),
|
||||
]
|
||||
for pw, salt, it, dk, hn in cases:
|
||||
got = K.pbkdf2(pw, salt, it, dk, hash_name=hn)
|
||||
assert got == hashlib.pbkdf2_hmac(hn, pw, salt, it, dk)
|
||||
|
||||
|
||||
def test_pbkdf2_salt_too_short_returns_err():
|
||||
r = K.pbkdf2(_PW, b"short", 1000, 32) # 5 bytes < 8
|
||||
assert _is_err(r) and r[0] == "PPYC_ERR_INVALID_SALT"
|
||||
# usable after explicitly relaxing min_salt_len, and matches hashlib
|
||||
ok = K.pbkdf2(_PW, b"short", 5, 32, min_salt_len=1)
|
||||
assert ok == hashlib.pbkdf2_hmac("sha256", _PW, b"short", 5, 32)
|
||||
|
||||
|
||||
def test_pbkdf2_param_errors():
|
||||
assert _is_err(K.pbkdf2(_PW, _SALT, 0, 32)) # iterations < 1
|
||||
assert _is_err(K.pbkdf2(_PW, _SALT, 1000, 0)) # dklen < 1
|
||||
assert _is_err(K.pbkdf2(_PW, _SALT, True, 32)) # bool iterations
|
||||
assert _is_err(K.pbkdf2("pw", _SALT, 1000, 32)) # password is not bytes
|
||||
assert _is_err(K.pbkdf2(_PW, "salt", 1000, 32)) # salt is not bytes
|
||||
r = K.pbkdf2(_PW, _SALT, 1000, 32, hash_name="md5")
|
||||
assert _is_err(r) and r[0] == "PPYC_ERR_INVALID_ALGO"
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# 2. Pure-Python SHA-1 / SHA-384 compared with hashlib
|
||||
# ======================================================================
|
||||
|
||||
def test_sha1_known_vector_and_hashlib():
|
||||
assert K.sha1(b"abc").hex() == "a9993e364706816aba3e25717850c26c9cd0d89d"
|
||||
for msg in [b"", b"a", b"abc", os.urandom(55), os.urandom(56),
|
||||
os.urandom(64), os.urandom(1000)]:
|
||||
assert K.sha1(msg) == hashlib.sha1(msg).digest()
|
||||
|
||||
|
||||
def test_sha384_known_vector_and_hashlib():
|
||||
assert K.sha384(b"abc").hex() == (
|
||||
"cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed"
|
||||
"8086072ba1e7cc2358baeca134c825a7")
|
||||
for msg in [b"", b"abc", os.urandom(111), os.urandom(112),
|
||||
os.urandom(128), os.urandom(2000)]:
|
||||
assert K.sha384(msg) == hashlib.sha384(msg).digest()
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# 3. HMAC compared with the stdlib hmac
|
||||
# ======================================================================
|
||||
|
||||
def test_hmac_matches_stdlib():
|
||||
msg = os.urandom(200)
|
||||
key = os.urandom(40)
|
||||
assert K.hmac_sha1(key, msg) == _hmac.new(key, msg, hashlib.sha1).digest()
|
||||
assert K.hmac_sha256(key, msg) == _hmac.new(key, msg, hashlib.sha256).digest()
|
||||
assert K.hmac_sha384(key, msg) == _hmac.new(key, msg, hashlib.sha384).digest()
|
||||
assert K.hmac_sha512(key, msg) == _hmac.new(key, msg, hashlib.sha512).digest()
|
||||
# oversized key (>block_size, must be hashed first)
|
||||
lk = os.urandom(300)
|
||||
assert K.hmac_sha256(lk, msg) == _hmac.new(lk, msg, hashlib.sha256).digest()
|
||||
assert K.hmac_sha1(lk, msg) == _hmac.new(lk, msg, hashlib.sha1).digest()
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# 4. RFC 9106 §5 official Argon2 vectors
|
||||
# ======================================================================
|
||||
|
||||
#: RFC 9106 §5.1-5.3 -- password=32*0x01, salt=16*0x02, secret=8*0x03,
|
||||
#: ad=12*0x04, t=3, m=32, p=4, taglen=32
|
||||
RFC9106 = {
|
||||
"argon2d": "512b391b6f1162975371d30919734294f868e3be3984f3c1a13a4db9fabe4acb",
|
||||
"argon2i": "c814d9d1dc7f37aa13f0d77f2494bda1c8de6b016dd388d29952a4c4672b6ce8",
|
||||
"argon2id": "0d640df58d78766c08c037a34a8b53c9d01ef0452d75b65eb52520e96b01e659",
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("variant,expected", list(RFC9106.items()))
|
||||
def test_argon2_rfc9106_vector(variant, expected):
|
||||
pwd, salt = b"\x01" * 32, b"\x02" * 16
|
||||
sec, ad = b"\x03" * 8, b"\x04" * 12
|
||||
got = K.argon2_hash(pwd, salt, variant=variant, t=3, m=32, p=4,
|
||||
tag_length=32, secret=sec, ad=ad)
|
||||
assert not _is_err(got), got
|
||||
assert got.hex() == expected
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# 5. Byte-for-byte cross-check against argon2-cffi (C implementation)
|
||||
# ======================================================================
|
||||
|
||||
def _cffi():
|
||||
argon2 = pytest.importorskip("argon2")
|
||||
from argon2.low_level import hash_secret_raw, verify_secret, Type # noqa
|
||||
return argon2, hash_secret_raw, verify_secret, Type
|
||||
|
||||
|
||||
@pytest.mark.parametrize("variant", ["argon2id", "argon2i", "argon2d"])
|
||||
def test_argon2_crosscheck_cffi_raw(variant):
|
||||
_, hash_secret_raw, _, Type = _cffi()
|
||||
T = {"argon2id": Type.ID, "argon2i": Type.I, "argon2d": Type.D}[variant]
|
||||
salt = os.urandom(16)
|
||||
for t, m, p, tag in [(2, 64, 1, 32), (3, 32, 4, 32), (1, 256, 2, 16), (2, 64, 1, 64)]:
|
||||
got = K.argon2_hash(b"password", salt, variant=variant, t=t, m=m, p=p, tag_length=tag)
|
||||
ref = hash_secret_raw(secret=b"password", salt=salt, time_cost=t,
|
||||
memory_cost=m, parallelism=p, hash_len=tag, type=T)
|
||||
assert got == ref, (variant, t, m, p, tag)
|
||||
|
||||
|
||||
def test_argon2id_hash_encoded_phc_parsed_by_cffi():
|
||||
argon2, _, verify_secret, Type = _cffi()
|
||||
salt = os.urandom(16)
|
||||
s = K.argon2id_hash_encoded(b"pw", salt, t=2, m=64, p=1)
|
||||
assert not _is_err(s)
|
||||
assert re.fullmatch(r"\$argon2id\$v=19\$m=64,t=2,p=1\$[A-Za-z0-9+/]+\$[A-Za-z0-9+/]+", s)
|
||||
# argon2-cffi can parse the parameters
|
||||
try:
|
||||
from argon2.low_level import extract_parameters
|
||||
params = extract_parameters(s)
|
||||
assert params.type == Type.ID
|
||||
assert params.time_cost == 2
|
||||
assert params.memory_cost == 64
|
||||
assert params.parallelism == 1
|
||||
except ImportError:
|
||||
pass
|
||||
# verify: correct password True; wrong password -> argon2-cffi raises VerifyMismatchError
|
||||
assert verify_secret(s.encode("ascii"), b"pw", Type.ID) is True
|
||||
from argon2.exceptions import VerifyMismatchError
|
||||
try:
|
||||
ok = verify_secret(s.encode("ascii"), b"wrong", Type.ID)
|
||||
assert ok is False
|
||||
except VerifyMismatchError:
|
||||
pass
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# 6. argon2 verification API
|
||||
# ======================================================================
|
||||
|
||||
def test_argon2id_verify_raw():
|
||||
salt = os.urandom(16)
|
||||
tag = K.argon2id_hash(b"pw", salt, t=1, m=32, p=1, tag_length=32)
|
||||
assert not _is_err(tag)
|
||||
assert K.argon2id_verify(b"pw", salt, tag, t=1, m=32, p=1) is True
|
||||
r = K.argon2id_verify(b"wrong", salt, tag, t=1, m=32, p=1)
|
||||
assert _is_err(r) and r[0] == "PPYC_ERR_AUTH_FAILED"
|
||||
# tag is not bytes
|
||||
assert _is_err(K.argon2id_verify(b"pw", salt, "notbytes"))
|
||||
# parameter mismatch (different iterations) -> different derivation -> authentication failure
|
||||
assert _is_err(K.argon2id_verify(b"pw", salt, tag, t=2, m=32, p=1))
|
||||
|
||||
|
||||
def test_argon2_verify_encoded():
|
||||
salt = os.urandom(16)
|
||||
s = K.argon2id_hash_encoded(b"pw", salt, t=1, m=32, p=1)
|
||||
assert K.argon2_verify_encoded(b"pw", s) is True
|
||||
r = K.argon2_verify_encoded(b"bad", s)
|
||||
assert _is_err(r) and r[0] == "PPYC_ERR_AUTH_FAILED"
|
||||
# malformed structure -> PARSE_FAILED
|
||||
for bad in ["not-a-phc", "$argon2id$v=19$m=32$AAAA$BBBB", "$argon2xx$v=19$m=1,t=1,p=1$AA$BB"]:
|
||||
rr = K.argon2_verify_encoded(b"pw", bad)
|
||||
assert _is_err(rr)
|
||||
assert _is_err(K.argon2_verify_encoded(b"pw", 123))
|
||||
|
||||
|
||||
def test_argon2_param_errors():
|
||||
salt = b"\x02" * 16
|
||||
assert _is_err(K.argon2id_hash(b"pw", b"short", t=1, m=32, p=1)) # salt<8
|
||||
r = K.argon2_hash(b"pw", salt, variant="argon2x", t=1, m=32, p=1)
|
||||
assert _is_err(r) and r[0] == "PPYC_ERR_INVALID_ALGO"
|
||||
assert _is_err(K.argon2id_hash(b"pw", salt, t=0, m=32, p=1)) # t<1
|
||||
assert _is_err(K.argon2id_hash(b"pw", salt, t=1, m=4, p=1)) # m<8p
|
||||
assert _is_err(K.argon2id_hash(b"pw", salt, t=1, m=32, p=0)) # p<1
|
||||
assert _is_err(K.argon2id_hash(b"pw", salt, t=1, m=32, p=1, tag_length=2)) # taglen<4
|
||||
assert _is_err(K.argon2id_hash(b"", salt, t=1, m=32, p=1)) # empty password
|
||||
assert _is_err(K.argon2id_hash("pw", salt, t=1, m=32, p=1)) # password is not bytes
|
||||
assert _is_err(K.argon2id_hash(b"pw", salt, t=1, m=32, p=1, version=99)) # invalid version
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# 7. scrypt_simple compared with hashlib.scrypt
|
||||
# ======================================================================
|
||||
|
||||
@pytest.mark.parametrize("n,r,p,dklen", [
|
||||
(256, 8, 1, 32), (256, 8, 1, 64), (256, 8, 1, 16),
|
||||
(1024, 8, 1, 32), (1024, 4, 2, 64), (512, 16, 1, 48),
|
||||
])
|
||||
def test_scrypt_simple_matches_hashlib(n, r, p, dklen):
|
||||
got = K.scrypt_simple(_PW, _SALT, n=n, r=r, p=p, dklen=dklen)
|
||||
ref = hashlib.scrypt(_PW, salt=_SALT, n=n, r=r, p=p, dklen=dklen)
|
||||
assert not _is_err(got), got
|
||||
assert got == ref and len(got) == dklen
|
||||
|
||||
|
||||
def test_scrypt_simple_errors():
|
||||
assert _is_err(K.scrypt_simple(_PW, b"short", n=256)) # salt too short
|
||||
assert _is_err(K.scrypt_simple(_PW, _SALT, n=100)) # not a power of two
|
||||
assert _is_err(K.scrypt_simple(_PW, _SALT, n=1)) # n<=1
|
||||
assert _is_err(K.scrypt_simple(_PW, _SALT, n=256, r=0))
|
||||
assert _is_err(K.scrypt_simple(_PW, _SALT, n=256, p=0))
|
||||
assert _is_err(K.scrypt_simple(_PW, _SALT, n=256, dklen=0))
|
||||
assert _is_err(K.scrypt_simple(_PW, _SALT, n=256, r=True)) # bool
|
||||
assert _is_err(K.scrypt_simple("pw", _SALT, n=256)) # password is not bytes
|
||||
|
||||
|
||||
def test_scrypt_recommended_constant_exists():
|
||||
assert K.SCRYPT_RECOMMENDED == (2 ** 15, 8, 1, 32)
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# 8. HKDF convenience wrapper
|
||||
# ======================================================================
|
||||
|
||||
def test_hkdf_expand_multi_matches_expand():
|
||||
prk = os.urandom(32)
|
||||
specs = [(b"enc", 16), (b"mac", 32), (b"iv", 12)]
|
||||
outs = K.hkdf_expand_multi(prk, specs, hash_name="sha256")
|
||||
assert not _is_err(outs) and isinstance(outs, list) and len(outs) == 3
|
||||
for (info, length), got in zip(specs, outs):
|
||||
assert len(got) == length
|
||||
assert got == K.hkdf_expand(prk, info, length, "sha256")
|
||||
# malformed structure
|
||||
assert _is_err(K.hkdf_expand_multi(prk, "notalist"))
|
||||
assert _is_err(K.hkdf_expand_multi(prk, [b"bad"]))
|
||||
|
||||
|
||||
def test_hkdf_matches_rfc5869_extract_expand_smoke():
|
||||
ikm = os.urandom(22)
|
||||
salt = os.urandom(13)
|
||||
prk = K.hkdf_extract(salt, ikm, "sha256")
|
||||
assert len(prk) == 32
|
||||
okm = K.hkdf_expand(prk, b"info", 42, "sha256")
|
||||
assert len(okm) == 42
|
||||
@@ -0,0 +1,160 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Multiprocess / spawn scenario tests (v3.1.4).
|
||||
|
||||
Coverage:
|
||||
- `sha3_batch` multiprocess matches the serial result (Windows spawn)
|
||||
- fallback when `sha3_batch` is called without a `__main__` guard (degrades to serial, no crash)
|
||||
- AES-GCM-SIV `n_workers` multiprocess matches serial
|
||||
- graceful degradation when `_get_pool` is unavailable
|
||||
- no WinError 87 / child-process re-entry on Windows
|
||||
"""
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
_PROJ = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# 1. sha3_batch multiprocess consistency
|
||||
# ----------------------------------------------------------------------
|
||||
|
||||
def test_sha3_batch_serial_vs_mp_consistency():
|
||||
"""Batch-parallel results must be byte-for-byte identical to the serial ones."""
|
||||
from purepycrypto import sha3_batch
|
||||
messages = [os.urandom(500) for _ in range(80)]
|
||||
r1 = sha3_batch(messages, "sha3_256", n_workers=1)
|
||||
r4 = sha3_batch(messages, "sha3_256", n_workers=4)
|
||||
assert r1 == r4
|
||||
assert len(r1) == len(messages)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("algo", ["sha3_224", "sha3_256", "sha3_384", "sha3_512"])
|
||||
def test_sha3_batch_all_algos(algo):
|
||||
from purepycrypto import sha3_batch
|
||||
messages = [os.urandom(200) for _ in range(40)]
|
||||
r1 = sha3_batch(messages, algo, n_workers=1)
|
||||
r2 = sha3_batch(messages, algo, n_workers=3)
|
||||
assert r1 == r2
|
||||
|
||||
|
||||
def test_sha3_batch_order_preserved():
|
||||
"""Order must correspond strictly to the input (it was once scrambled by a wrong sharding scheme)."""
|
||||
from purepycrypto import sha3_batch, sha3_256
|
||||
messages = [bytes([i]) * 100 for i in range(50)]
|
||||
r = sha3_batch(messages, "sha3_256", n_workers=4)
|
||||
expect = [sha3_256(m) for m in messages]
|
||||
assert r == expect
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# 2. sha3_batch should degrade gracefully (not crash) without a __main__ guard
|
||||
# ----------------------------------------------------------------------
|
||||
|
||||
_NO_GUARD_SCRIPT = r'''
|
||||
import sys, os
|
||||
sys.path.insert(0, r"{proj}")
|
||||
from purepycrypto import sha3_batch, sha3_256
|
||||
|
||||
# deliberately call multiprocessing at module top level (without the if __name__ == "__main__" guard)
|
||||
msgs = [bytes([i]) * 50 for i in range(40)]
|
||||
try:
|
||||
r = sha3_batch(msgs, "sha3_256", n_workers=4)
|
||||
if isinstance(r, tuple) and r and isinstance(r[0], str) and r[0].startswith("PPYC_ERR_"):
|
||||
print("ERRTUPLE", r[0])
|
||||
else:
|
||||
expect = [sha3_256(m) for m in msgs]
|
||||
print("OK" if r == expect else "MISMATCH")
|
||||
except Exception as e:
|
||||
print("RAISED", type(e).__name__, str(e)[:80])
|
||||
'''
|
||||
|
||||
|
||||
def test_sha3_batch_no_main_guard_degrades_gracefully(tmp_path):
|
||||
"""Without the __main__ guard it should degrade to serial and return correct results rather than crash."""
|
||||
script = tmp_path / "no_guard.py"
|
||||
script.write_text(_NO_GUARD_SCRIPT.format(proj=_PROJ), encoding="utf-8")
|
||||
r = subprocess.run([sys.executable, "-u", str(script)],
|
||||
capture_output=True, text=True, cwd=str(tmp_path), timeout=90)
|
||||
out = (r.stdout + r.stderr).strip()
|
||||
# two acceptable outcomes: a normal serial fallback (OK) or an explicit error tuple (ERRTUPLE)
|
||||
assert "OK" in out or "ERRTUPLE" in out, f"not handled gracefully: {out[-300:]}"
|
||||
assert "Traceback" not in out, f"should not crash: {out[-300:]}"
|
||||
assert "WinError 87" not in out
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# 3. AES-GCM-SIV multiprocess consistency
|
||||
# ----------------------------------------------------------------------
|
||||
|
||||
def test_gcm_siv_mp_consistency_128():
|
||||
from purepycrypto import aes128_gcm_siv_encrypt, aes128_gcm_siv_decrypt
|
||||
key = os.urandom(16)
|
||||
nonce = os.urandom(12)
|
||||
data = os.urandom(300 * 1024) # > 128KB, triggers multiprocessing
|
||||
c1, t1 = aes128_gcm_siv_encrypt(key, nonce, data, n_workers=1)
|
||||
c2, t2 = aes128_gcm_siv_encrypt(key, nonce, data, n_workers=4)
|
||||
assert c1 == c2 and t1 == t2
|
||||
assert aes128_gcm_siv_decrypt(key, nonce, c2, t2, n_workers=4) == data
|
||||
|
||||
|
||||
def test_gcm_siv_mp_consistency_256():
|
||||
from purepycrypto import aes256_gcm_siv_encrypt, aes256_gcm_siv_decrypt
|
||||
key = os.urandom(32)
|
||||
nonce = os.urandom(12)
|
||||
data = os.urandom(300 * 1024)
|
||||
c1, t1 = aes256_gcm_siv_encrypt(key, nonce, data, n_workers=1)
|
||||
c2, t2 = aes256_gcm_siv_encrypt(key, nonce, data, n_workers=4)
|
||||
assert c1 == c2 and t1 == t2
|
||||
assert aes256_gcm_siv_decrypt(key, nonce, c2, t2, n_workers=4) == data
|
||||
|
||||
|
||||
def test_gcm_siv_auto_workers_matches_serial():
|
||||
"""The default (n_workers=None, automatic) should match an explicit serial run."""
|
||||
from purepycrypto import aes128_gcm_siv_encrypt
|
||||
key = os.urandom(16)
|
||||
nonce = os.urandom(12)
|
||||
data = os.urandom(200 * 1024)
|
||||
c_serial, t_serial = aes128_gcm_siv_encrypt(key, nonce, data, n_workers=1)
|
||||
c_auto, t_auto = aes128_gcm_siv_encrypt(key, nonce, data)
|
||||
assert c_serial == c_auto and t_serial == t_auto
|
||||
|
||||
|
||||
def test_gcm_siv_mp_spawn_no_winerror(tmp_path):
|
||||
"""Invoking via a child process (simulating spawn) should not produce WinError 87."""
|
||||
script = tmp_path / "mp_gcm.py"
|
||||
script.write_text(
|
||||
"# -*- coding: utf-8 -*-\n"
|
||||
"import sys, os\n"
|
||||
f"sys.path.insert(0, r'{_PROJ}')\n"
|
||||
"from purepycrypto import aes128_gcm_siv_encrypt, aes128_gcm_siv_decrypt\n"
|
||||
"def main():\n"
|
||||
" key, nonce = os.urandom(16), os.urandom(12)\n"
|
||||
" data = os.urandom(200 * 1024)\n"
|
||||
" ct, tag = aes128_gcm_siv_encrypt(key, nonce, data)\n"
|
||||
" assert aes128_gcm_siv_decrypt(key, nonce, ct, tag) == data\n"
|
||||
" print('MP_OK')\n"
|
||||
"if __name__ == '__main__':\n"
|
||||
" main()\n",
|
||||
encoding="utf-8")
|
||||
r = subprocess.run([sys.executable, "-u", str(script)],
|
||||
capture_output=True, text=True, cwd=str(tmp_path), timeout=120)
|
||||
out = (r.stdout + r.stderr)
|
||||
assert "MP_OK" in out, f"multiprocessing failed: {out[-400:]}"
|
||||
assert "WinError 87" not in out
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# 4. Graceful degradation when multiprocessing is unavailable
|
||||
# ----------------------------------------------------------------------
|
||||
|
||||
def test_sha3_batch_falls_back_when_no_mp(monkeypatch):
|
||||
"""Simulate multiprocessing being unavailable: sha3_batch should degrade to serial and return correct results."""
|
||||
import purepycrypto.sha3 as S
|
||||
monkeypatch.setattr(S, "_HAS_MP", False, raising=False)
|
||||
messages = [os.urandom(100) for _ in range(20)]
|
||||
r = S.sha3_batch(messages, "sha3_256", n_workers=4)
|
||||
from purepycrypto import sha3_256
|
||||
assert r == [sha3_256(m) for m in messages]
|
||||
@@ -0,0 +1,339 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""purepycrypto.rand tests.
|
||||
|
||||
Coverage:
|
||||
- uniformity / unbiasedness statistical tests (chi-square + tolerance)
|
||||
- range correctness
|
||||
- boundary conditions (n=0 / n=1 / a==b / length-1 sequence)
|
||||
- error returns (negative length / a>b / empty alphabet / empty seq ...)
|
||||
- uniqueness (uuid4 / token_hex)
|
||||
- token format and password strength
|
||||
- security constraint: must not use the random module
|
||||
"""
|
||||
import math
|
||||
import os
|
||||
import uuid
|
||||
|
||||
import pytest
|
||||
|
||||
from purepycrypto.rand import (
|
||||
random_bytes, random_int, random_below, random_bit, random_bits,
|
||||
token_bytes, token_hex, token_urlsafe,
|
||||
random_string, random_password,
|
||||
random_uuid4, random_choice, random_sample,
|
||||
randbytes_alias,
|
||||
)
|
||||
from purepycrypto._ppyc_error import (
|
||||
is_err,
|
||||
PPYC_ERR_INVALID_ARG,
|
||||
PPYC_ERR_OUT_OF_RANGE,
|
||||
PPYC_ERR_INVALID_LENGTH,
|
||||
PPYC_ERR_INVALID_TYPE,
|
||||
)
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# Statistical test helpers
|
||||
# ----------------------------------------------------------------------
|
||||
|
||||
def _counts(samples, nbins):
|
||||
c = [0] * nbins
|
||||
for s in samples:
|
||||
c[s] += 1
|
||||
return c
|
||||
|
||||
|
||||
def _chi2(counts, n):
|
||||
nbins = len(counts)
|
||||
exp = n / nbins
|
||||
return sum((c - exp) ** 2 / exp for c in counts)
|
||||
|
||||
|
||||
def _chi2_bound(df, sigmas=6.0):
|
||||
"""Chi-square upper bound: mean df, standard deviation sqrt(2*df), take 6 sigma (false-positive probability about 1e-9)."""
|
||||
return df + sigmas * math.sqrt(2.0 * df)
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# 1. Uniformity / unbiasedness
|
||||
# ----------------------------------------------------------------------
|
||||
|
||||
def test_random_int_uniform_0_9():
|
||||
"""random_int(0,9) sampled 100000 times: +/-5% tolerance + chi-square test."""
|
||||
N = 100000
|
||||
samples = [random_int(0, 9) for _ in range(N)]
|
||||
assert all(isinstance(v, int) and 0 <= v <= 9 for v in samples)
|
||||
counts = _counts(samples, 10)
|
||||
# expected 10000, +/-5% => [9500, 10500]
|
||||
assert all(9500 <= c <= 10500 for c in counts), counts
|
||||
chi2 = _chi2(counts, N)
|
||||
assert chi2 < _chi2_bound(9), chi2
|
||||
|
||||
|
||||
@pytest.mark.parametrize("n", [3, 7, 10])
|
||||
def test_random_below_uniform_small(n):
|
||||
"""random_below(n) uniformity test for small n (+/-5% + chi-square)."""
|
||||
N = 100000
|
||||
samples = [random_below(n) for _ in range(N)]
|
||||
assert all(0 <= v < n for v in samples)
|
||||
counts = _counts(samples, n)
|
||||
exp = N / n
|
||||
assert all(abs(c - exp) <= 0.05 * exp for c in counts), (n, counts)
|
||||
chi2 = _chi2(counts, N)
|
||||
assert chi2 < _chi2_bound(n - 1), (n, chi2)
|
||||
|
||||
|
||||
def test_random_below_uniform_256():
|
||||
"""random_below(256) sampled 100000 times: chi-square test (df=255)."""
|
||||
N = 100000
|
||||
samples = [random_below(256) for _ in range(N)]
|
||||
assert min(samples) >= 0 and max(samples) <= 255
|
||||
counts = _counts(samples, 256)
|
||||
chi2 = _chi2(counts, N)
|
||||
assert chi2 < _chi2_bound(255), chi2
|
||||
|
||||
|
||||
def test_random_bytes_byte_distribution():
|
||||
"""The 256 byte values from random_bytes are uniformly distributed (chi-square, df=255)."""
|
||||
data = random_bytes(25600)
|
||||
assert isinstance(data, bytes) and len(data) == 25600
|
||||
counts = _counts(data, 256) # iterating bytes yields ints 0..255
|
||||
chi2 = _chi2(counts, 25600)
|
||||
assert chi2 < _chi2_bound(255), chi2
|
||||
|
||||
|
||||
def test_os_urandom_byte_distribution():
|
||||
"""os.urandom byte distribution is uniform (control, proving the quality of the underlying entropy source)."""
|
||||
data = os.urandom(25600)
|
||||
counts = _counts(data, 256)
|
||||
chi2 = _chi2(counts, 25600)
|
||||
assert chi2 < _chi2_bound(255), chi2
|
||||
|
||||
|
||||
def test_random_bits_distribution():
|
||||
"""The 8 values of random_bits(3) are approximately uniform."""
|
||||
N = 80000
|
||||
samples = [random_bits(3) for _ in range(N)]
|
||||
assert all(0 <= v < 8 for v in samples)
|
||||
counts = _counts(samples, 8)
|
||||
exp = N / 8
|
||||
assert all(abs(c - exp) <= 0.05 * exp for c in counts), counts
|
||||
chi2 = _chi2(counts, N)
|
||||
assert chi2 < _chi2_bound(7), chi2
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# 2. Range correctness
|
||||
# ----------------------------------------------------------------------
|
||||
|
||||
@pytest.mark.parametrize("a,b", [
|
||||
(0, 0), (0, 1), (-5, 5), (10, 20), (1, 100),
|
||||
(-100, -1), (123456, 123460),
|
||||
])
|
||||
def test_random_int_in_range(a, b):
|
||||
for _ in range(2000):
|
||||
v = random_int(a, b)
|
||||
assert isinstance(v, int) and a <= v <= b
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# 3. Boundary conditions
|
||||
# ----------------------------------------------------------------------
|
||||
|
||||
def test_random_bytes_boundary():
|
||||
assert random_bytes(0) == b""
|
||||
one = random_bytes(1)
|
||||
assert isinstance(one, bytes) and len(one) == 1
|
||||
|
||||
|
||||
def test_random_int_equal_bounds():
|
||||
assert random_int(7, 7) == 7
|
||||
assert random_int(-3, -3) == -3
|
||||
assert random_int(0, 0) == 0
|
||||
|
||||
|
||||
def test_random_below_one():
|
||||
assert random_below(1) == 0
|
||||
|
||||
|
||||
def test_random_bits_boundary():
|
||||
assert random_bits(0) == 0
|
||||
for k in (1, 7, 8, 31, 64):
|
||||
v = random_bits(k)
|
||||
assert isinstance(v, int) and 0 <= v < (1 << k)
|
||||
|
||||
|
||||
def test_random_bit_values():
|
||||
for _ in range(2000):
|
||||
assert random_bit() in (0, 1)
|
||||
|
||||
|
||||
def test_random_string_boundary():
|
||||
assert random_string(0, "abc") == ""
|
||||
assert random_string(20, "x") == "x" * 20
|
||||
s = random_string(1, "abc")
|
||||
assert s in "abc"
|
||||
|
||||
|
||||
def test_random_choice_single_element():
|
||||
assert random_choice([42]) == 42
|
||||
assert random_choice("z") == "z"
|
||||
assert random_choice((7,)) == 7
|
||||
|
||||
|
||||
def test_random_sample_boundary():
|
||||
assert random_sample([42], 1) == [42]
|
||||
assert random_sample([1, 2, 3], 0) == []
|
||||
full = random_sample([1, 2, 3], 3)
|
||||
assert sorted(full) == [1, 2, 3]
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# 4. Error returns
|
||||
# ----------------------------------------------------------------------
|
||||
|
||||
def test_error_negative_lengths():
|
||||
for r in (random_bytes(-1), token_bytes(-1), token_hex(-1),
|
||||
token_urlsafe(-1), random_bits(-1)):
|
||||
assert is_err(r), r
|
||||
assert is_err(random_string(-1, "abc"))
|
||||
|
||||
|
||||
def test_error_negative_lengths_code():
|
||||
assert random_bytes(-1)[0] == PPYC_ERR_INVALID_LENGTH
|
||||
assert token_hex(-1)[0] == PPYC_ERR_INVALID_LENGTH
|
||||
assert random_bits(-1)[0] == PPYC_ERR_INVALID_LENGTH
|
||||
|
||||
|
||||
def test_error_bad_range():
|
||||
r = random_int(5, 3)
|
||||
assert is_err(r) and r[0] == PPYC_ERR_INVALID_ARG
|
||||
assert is_err(random_below(0))
|
||||
assert is_err(random_below(-3))
|
||||
assert random_below(0)[0] == PPYC_ERR_OUT_OF_RANGE
|
||||
|
||||
|
||||
def test_error_empty_alphabet():
|
||||
r = random_string(4, "")
|
||||
assert is_err(r) and r[0] == PPYC_ERR_INVALID_ARG
|
||||
|
||||
|
||||
def test_error_empty_seq():
|
||||
r = random_choice([])
|
||||
assert is_err(r) and r[0] == PPYC_ERR_INVALID_ARG
|
||||
assert is_err(random_sample([], 1))
|
||||
|
||||
|
||||
def test_error_sample_k_out_of_range():
|
||||
r = random_sample([1, 2, 3], 5)
|
||||
assert is_err(r) and r[0] == PPYC_ERR_OUT_OF_RANGE
|
||||
assert is_err(random_sample([1, 2, 3], -1))
|
||||
|
||||
|
||||
def test_error_password_invalid():
|
||||
# no category enabled
|
||||
assert is_err(random_password(8, upper=False, lower=False,
|
||||
digits=False, special=False))
|
||||
# invalid length
|
||||
assert is_err(random_password(0))
|
||||
assert random_password(0)[0] == PPYC_ERR_OUT_OF_RANGE
|
||||
# exclude drains one enabled category
|
||||
r = random_password(8, upper=True, lower=False, digits=False,
|
||||
exclude="ABCDEFGHIJKLMNOPQRSTUVWXYZ")
|
||||
assert is_err(r) and r[0] == PPYC_ERR_INVALID_ARG
|
||||
|
||||
|
||||
def test_error_types():
|
||||
assert random_bytes("4")[0] == PPYC_ERR_INVALID_TYPE
|
||||
assert is_err(random_below(2.5))
|
||||
assert is_err(random_int(1, "2"))
|
||||
assert is_err(random_string(3, 123))
|
||||
assert is_err(random_sample([1, 2], 1.5))
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# 5. Uniqueness
|
||||
# ----------------------------------------------------------------------
|
||||
|
||||
def test_uuid4_unique_and_format():
|
||||
us = [random_uuid4() for _ in range(1000)]
|
||||
assert len(set(us)) == 1000
|
||||
for u in us[:100]:
|
||||
assert isinstance(u, str) and len(u) == 36
|
||||
obj = uuid.UUID(u)
|
||||
assert obj.version == 4
|
||||
assert obj.variant == uuid.RFC_4122
|
||||
|
||||
|
||||
def test_token_hex_unique():
|
||||
ts = set(token_hex(16) for _ in range(1000))
|
||||
assert len(ts) == 1000
|
||||
s = token_hex(16)
|
||||
assert len(s) == 32 and all(c in "0123456789abcdef" for c in s)
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# 6. Token format / password strength / aliases
|
||||
# ----------------------------------------------------------------------
|
||||
|
||||
def test_token_bytes_defaults():
|
||||
assert isinstance(token_bytes(), bytes) and len(token_bytes()) == 32
|
||||
assert len(token_bytes(16)) == 16
|
||||
|
||||
|
||||
def test_token_hex_default_len():
|
||||
assert len(token_hex()) == 64
|
||||
|
||||
|
||||
def test_token_urlsafe_format():
|
||||
s = token_urlsafe(16)
|
||||
assert isinstance(s, str)
|
||||
assert "=" not in s and "+" not in s and "/" not in s
|
||||
allowed = set("ABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
||||
"abcdefghijklmnopqrstuvwxyz0123456789-_")
|
||||
assert set(s) <= allowed
|
||||
assert len(set(token_urlsafe(16) for _ in range(1000))) == 1000
|
||||
|
||||
|
||||
def test_password_default_strength():
|
||||
p = random_password()
|
||||
assert len(p) == 16
|
||||
assert any(c.isupper() for c in p)
|
||||
assert any(c.islower() for c in p)
|
||||
assert any(c.isdigit() for c in p)
|
||||
|
||||
|
||||
def test_password_special_class():
|
||||
p = random_password(24, special=True)
|
||||
assert len(p) == 24
|
||||
assert any(c in "!@#$%^&*()-_=+[]{};:,.?/" for c in p)
|
||||
|
||||
|
||||
def test_password_single_class():
|
||||
p = random_password(10, upper=False, lower=False, digits=True)
|
||||
assert len(p) == 10 and p.isdigit()
|
||||
|
||||
|
||||
def test_password_exclude():
|
||||
p = random_password(40, exclude="abcABC")
|
||||
for ch in "abcABC":
|
||||
assert ch not in p
|
||||
|
||||
|
||||
def test_random_sample_subset_and_distinct():
|
||||
seq = list(range(20))
|
||||
s = random_sample(seq, 5)
|
||||
assert len(s) == 5 and len(set(s)) == 5
|
||||
assert all(x in seq for x in s)
|
||||
|
||||
|
||||
def test_randbytes_alias():
|
||||
b = randbytes_alias(8)
|
||||
assert isinstance(b, bytes) and len(b) == 8
|
||||
assert randbytes_alias is random_bytes
|
||||
|
||||
|
||||
def test_no_insecure_random_import():
|
||||
"""Security constraint: the module must not import the stdlib random (Mersenne Twister)."""
|
||||
import purepycrypto.rand as r
|
||||
assert "random" not in vars(r), "the rand module should not import random"
|
||||
@@ -0,0 +1,293 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Independent review of purepycrypto.rand (new module in v3.2.0).
|
||||
|
||||
Verification strategy (**independent of the module's own tests**):
|
||||
* uniformity: ``random_int(0,9)`` / ``random_below(n)`` each sampled 100k times,
|
||||
frequency deviation +/-5% (small n) and chi-square statistic < critical value;
|
||||
* range correctness / boundaries (n=0/1, a==b, seq length 1, k=0);
|
||||
* error returns (negative length, a>b, empty alphabet, empty seq ...) are err tuples;
|
||||
* uniqueness: 1000 uuid4 / token_hex(16) / random_bytes(16) with no duplicates;
|
||||
* basic randomness comparison against os.urandom;
|
||||
* static check: this module must not use the non-cryptographic ``random`` module.
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
_HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
_PKG_PARENT = os.path.dirname(_HERE)
|
||||
if _PKG_PARENT not in sys.path:
|
||||
sys.path.insert(0, _PKG_PARENT)
|
||||
|
||||
from purepycrypto import rand as R # noqa: E402
|
||||
from purepycrypto._ppyc_error import PPYC_ERR_PREFIX # noqa: E402
|
||||
|
||||
|
||||
def _is_err(v):
|
||||
return (isinstance(v, tuple) and len(v) == 3
|
||||
and isinstance(v[0], str) and v[0].startswith(PPYC_ERR_PREFIX))
|
||||
|
||||
|
||||
def _chi2(counts, expected):
|
||||
return sum((c - expected) ** 2 / expected for c in counts)
|
||||
|
||||
|
||||
#: chi-square critical value at 0.001 significance (df -> critical value)
|
||||
_CHI2_CRIT = {2: 13.82, 6: 22.46, 9: 27.88, 255: 330.6}
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# 1. Uniformity statistics
|
||||
# ======================================================================
|
||||
|
||||
def test_random_int_0_9_uniform():
|
||||
N = 100_000
|
||||
counts = [0] * 10
|
||||
for _ in range(N):
|
||||
v = R.random_int(0, 9)
|
||||
assert isinstance(v, int) and 0 <= v <= 9
|
||||
counts[v] += 1
|
||||
exp = N / 10
|
||||
# each value frequency within +/-5%
|
||||
for c in counts:
|
||||
assert abs(c - exp) <= 0.05 * exp, counts
|
||||
# chi-square test (df=9, p=0.001 critical value 27.88)
|
||||
assert _chi2(counts, exp) < _CHI2_CRIT[9], counts
|
||||
|
||||
|
||||
@pytest.mark.parametrize("n,N", [(3, 100_000), (7, 100_000), (10, 100_000), (256, 200_000)])
|
||||
def test_random_below_uniform(n, N):
|
||||
counts = [0] * n
|
||||
for _ in range(N):
|
||||
v = R.random_below(n)
|
||||
assert isinstance(v, int) and 0 <= v < n
|
||||
counts[v] += 1
|
||||
exp = N / n
|
||||
# per-value +/-5% for small n (single bins have too few samples for large n, so use chi-square only)
|
||||
if n <= 10:
|
||||
for c in counts:
|
||||
assert abs(c - exp) <= 0.05 * exp, (n, counts)
|
||||
assert _chi2(counts, exp) < _CHI2_CRIT[n - 1], (n, counts)
|
||||
|
||||
|
||||
def test_random_int_range_and_mean():
|
||||
vals = [R.random_int(-5, 5) for _ in range(20000)]
|
||||
assert all(-5 <= v <= 5 for v in vals)
|
||||
mean = sum(vals) / len(vals)
|
||||
assert abs(mean - 0.0) < 0.25, mean # expected mean 0
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# 2. Range / boundaries
|
||||
# ======================================================================
|
||||
|
||||
def test_boundaries():
|
||||
assert R.random_below(1) == 0
|
||||
assert all(R.random_below(1) == 0 for _ in range(100))
|
||||
assert R.random_int(7, 7) == 7
|
||||
assert R.random_int(0, 0) == 0
|
||||
assert R.random_bits(0) == 0
|
||||
assert R.random_string(0, "abc") == ""
|
||||
assert R.random_bytes(0) == b""
|
||||
assert R.random_bit() in (0, 1)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("k", [1, 7, 8, 9, 16, 64, 128, 256])
|
||||
def test_random_bits_range(k):
|
||||
for _ in range(500):
|
||||
v = R.random_bits(k)
|
||||
assert isinstance(v, int) and 0 <= v < (1 << k)
|
||||
|
||||
|
||||
def test_random_bytes_length_and_type():
|
||||
for n in [0, 1, 16, 32, 1024]:
|
||||
b = R.random_bytes(n)
|
||||
assert isinstance(b, bytes) and len(b) == n
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# 3. Error returns (err tuple, never raises)
|
||||
# ======================================================================
|
||||
|
||||
def test_error_returns():
|
||||
# negative / non-integer length
|
||||
assert _is_err(R.random_bytes(-1))
|
||||
assert _is_err(R.random_bytes("x"))
|
||||
assert _is_err(R.random_bytes(1.5))
|
||||
assert _is_err(R.random_bytes(True)) # bool does not count as int
|
||||
# n < 1
|
||||
assert _is_err(R.random_below(0))
|
||||
assert _is_err(R.random_below(-5))
|
||||
assert _is_err(R.random_below(2.0))
|
||||
# a > b
|
||||
assert _is_err(R.random_int(5, 1))
|
||||
assert _is_err(R.random_int("a", 3))
|
||||
# random_bits negative
|
||||
assert _is_err(R.random_bits(-1))
|
||||
# random_string
|
||||
assert _is_err(R.random_string(-1, "ab"))
|
||||
assert _is_err(R.random_string(5, ""))
|
||||
assert _is_err(R.random_string(5, 123))
|
||||
assert _is_err(R.random_string("x", "ab"))
|
||||
# random_password
|
||||
assert _is_err(R.random_password(0))
|
||||
assert _is_err(R.random_password(-3))
|
||||
assert _is_err(R.random_password("x"))
|
||||
assert _is_err(R.random_password(8, upper=False, lower=False, digits=False, special=False))
|
||||
assert _is_err(R.random_password(8, exclude=123))
|
||||
assert _is_err(R.random_password(8, lower=True, upper=False, digits=False,
|
||||
exclude="abcdefghijklmnopqrstuvwxyz"))
|
||||
# token_*
|
||||
assert _is_err(R.token_hex(-1))
|
||||
assert _is_err(R.token_bytes(-1))
|
||||
assert _is_err(R.token_urlsafe("x"))
|
||||
# choice / sample
|
||||
assert _is_err(R.random_choice([]))
|
||||
assert _is_err(R.random_choice(123))
|
||||
assert _is_err(R.random_sample([], 1))
|
||||
assert _is_err(R.random_sample([1, 2], 5))
|
||||
assert _is_err(R.random_sample([1, 2], -1))
|
||||
assert _is_err(R.random_sample([1, 2], "x"))
|
||||
|
||||
|
||||
def test_err_tuple_shape():
|
||||
r = R.random_bytes(-1)
|
||||
assert isinstance(r, tuple) and len(r) == 3
|
||||
assert all(isinstance(x, str) for x in r)
|
||||
assert r[0].startswith("PPYC_ERR_")
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# 4. Token / string / password
|
||||
# ======================================================================
|
||||
|
||||
def test_token_hex():
|
||||
t = R.token_hex(16)
|
||||
assert isinstance(t, str) and len(t) == 32
|
||||
assert re.fullmatch(r"[0-9a-f]{32}", t)
|
||||
assert len(R.token_hex()) == 64 # 32 bytes by default
|
||||
assert R.token_hex(0) == ""
|
||||
|
||||
|
||||
def test_token_bytes_and_urlsafe():
|
||||
assert len(R.token_bytes()) == 32
|
||||
assert len(R.token_bytes(8)) == 8 and isinstance(R.token_bytes(8), bytes)
|
||||
u = R.token_urlsafe(16)
|
||||
assert isinstance(u, str)
|
||||
assert re.fullmatch(r"[A-Za-z0-9\-_]+", u)
|
||||
assert "=" not in u
|
||||
|
||||
|
||||
def test_random_string():
|
||||
s = R.random_string(200, "abc")
|
||||
assert len(s) == 200 and set(s) <= set("abc")
|
||||
s2 = R.random_string(50, "0123456789")
|
||||
assert set(s2) <= set("0123456789")
|
||||
|
||||
|
||||
def test_random_password_strength():
|
||||
pw = R.random_password(20, upper=True, lower=True, digits=True, special=True)
|
||||
assert len(pw) == 20
|
||||
assert any(c.isupper() for c in pw)
|
||||
assert any(c.islower() for c in pw)
|
||||
assert any(c.isdigit() for c in pw)
|
||||
assert any(not c.isalnum() for c in pw)
|
||||
# symbols-only category
|
||||
pw2 = R.random_password(10, upper=False, lower=False, digits=False, special=True)
|
||||
assert len(pw2) == 10 and all(not c.isalnum() for c in pw2)
|
||||
# exclude takes effect
|
||||
pw3 = R.random_password(50, exclude="abcABC")
|
||||
assert not (set(pw3) & set("abcABC"))
|
||||
# short length (pin style, digits only)
|
||||
pw4 = R.random_password(6, upper=False, lower=False, digits=True)
|
||||
assert len(pw4) == 6 and pw4.isdigit()
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# 5. Uniqueness
|
||||
# ======================================================================
|
||||
|
||||
def test_uniqueness_uuid4():
|
||||
us = [R.random_uuid4() for _ in range(1000)]
|
||||
assert len(set(us)) == 1000
|
||||
|
||||
|
||||
def test_uniqueness_token_hex():
|
||||
ts = [R.token_hex(16) for _ in range(1000)]
|
||||
assert len(set(ts)) == 1000
|
||||
|
||||
|
||||
def test_uniqueness_random_bytes():
|
||||
bs = [R.random_bytes(16) for _ in range(1000)]
|
||||
assert len(set(bs)) == 1000
|
||||
|
||||
|
||||
def test_uuid4_format():
|
||||
for _ in range(200):
|
||||
u = R.random_uuid4()
|
||||
m = re.fullmatch(
|
||||
r"([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})",
|
||||
u)
|
||||
assert m, u
|
||||
# version nibble = 4
|
||||
assert u[14] == "4"
|
||||
# variant nibble in 8,9,a,b
|
||||
assert u[19] in "89ab"
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# 6. Randomness comparison against os.urandom
|
||||
# ======================================================================
|
||||
|
||||
def test_differs_from_os_urandom():
|
||||
assert R.random_bytes(32) != os.urandom(32)
|
||||
assert R.random_bytes(32) != R.random_bytes(32)
|
||||
a = R.random_bytes(64)
|
||||
b = R.random_bytes(64)
|
||||
assert a != b and os.urandom(64) != a
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# 7. choice / sample
|
||||
# ======================================================================
|
||||
|
||||
def test_random_choice():
|
||||
seq = [10, 20, 30, 40]
|
||||
vals = {R.random_choice(seq) for _ in range(500)}
|
||||
assert vals <= set(seq)
|
||||
assert R.random_choice("abc") in "abc"
|
||||
assert R.random_choice(range(5)) in range(5)
|
||||
assert R.random_choice((1,)) == 1
|
||||
|
||||
|
||||
def test_random_sample():
|
||||
seq = list(range(20))
|
||||
out = R.random_sample(seq, 5)
|
||||
assert len(out) == 5
|
||||
assert len(set(out)) == 5
|
||||
assert set(out) <= set(seq)
|
||||
assert R.random_sample(seq, 0) == []
|
||||
assert sorted(R.random_sample(seq, 20)) == seq # k == n is a full permutation
|
||||
# coverage: repeated sampling should cover different elements
|
||||
seen = set()
|
||||
for _ in range(50):
|
||||
seen |= set(R.random_sample(seq, 3))
|
||||
assert len(seen) > 10
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# 8. Static check: must not use the non-cryptographic random module
|
||||
# ======================================================================
|
||||
|
||||
def test_no_insecure_random_import():
|
||||
text = open(R.__file__, encoding="utf-8").read()
|
||||
assert not re.search(r"(?m)^\s*import\s+random\b", text)
|
||||
assert not re.search(r"(?m)^\s*from\s+random\s+import\b", text)
|
||||
assert not re.search(r"\brandom\.(random|randint|randrange|choice|shuffle|sample|getrandbits)\b", text)
|
||||
|
||||
|
||||
def test_uses_os_urandom():
|
||||
text = open(R.__file__, encoding="utf-8").read()
|
||||
assert "os.urandom" in text
|
||||
@@ -0,0 +1,125 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""RSA tests (keygen / OAEP / PSS / PEM / DER)."""
|
||||
import os
|
||||
|
||||
import pytest
|
||||
|
||||
from purepycrypto import (
|
||||
PPYC_ERR, is_err, PPYC_ERR_INVALID_RSA_BITS, PPYC_ERR_DECRYPT_FAILED,
|
||||
PPYC_ERR_MESSAGE_TOO_LONG, PPYC_ERR_INVALID_KEY_MATERIAL,
|
||||
)
|
||||
|
||||
from purepycrypto import (
|
||||
rsa_keygen, rsa_oaep_encrypt, rsa_oaep_decrypt,
|
||||
rsa_pss_sign, rsa_pss_verify,
|
||||
RSAPublicKey, RSAPrivateKey,
|
||||
private_key_to_pem, public_key_to_pem, parse_private_pem,
|
||||
private_key_to_pkcs1_der, public_key_to_pkcs1_der,
|
||||
private_key_to_pkcs8_der, public_key_to_spki_der,
|
||||
DecryptionError,
|
||||
)
|
||||
|
||||
BITS = 1024
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def keypair():
|
||||
return rsa_keygen(bits=BITS, parallel=False)
|
||||
|
||||
|
||||
def test_keygen_basic(keypair):
|
||||
pub, priv = keypair
|
||||
assert priv.n.bit_length() == BITS
|
||||
assert priv.p * priv.q == priv.n
|
||||
assert (priv.e * priv.d) % ((priv.p - 1) * (priv.q - 1)) == 1
|
||||
|
||||
|
||||
def test_keygen_min_bits():
|
||||
# bit count too small: fatal error -> raises PPYC_ERR
|
||||
with pytest.raises(PPYC_ERR) as ei:
|
||||
rsa_keygen(bits=256, parallel=False)
|
||||
assert ei.value.code == PPYC_ERR_INVALID_RSA_BITS
|
||||
|
||||
|
||||
def test_oaep_roundtrip(keypair):
|
||||
pub, priv = keypair
|
||||
for msg in (b"", b"x", b"hello world", os.urandom(30)):
|
||||
assert rsa_oaep_decrypt(rsa_oaep_encrypt(msg, pub), priv) == msg
|
||||
|
||||
|
||||
def test_oaep_label(keypair):
|
||||
pub, priv = keypair
|
||||
msg = b"with label"
|
||||
ct = rsa_oaep_encrypt(msg, pub, b"label")
|
||||
assert rsa_oaep_decrypt(ct, priv, b"label") == msg
|
||||
# a label mismatch should fail decryption (non-fatal -> returns a tuple)
|
||||
r = rsa_oaep_decrypt(ct, priv, b"wrong")
|
||||
assert is_err(r) and r[0] == PPYC_ERR_DECRYPT_FAILED
|
||||
|
||||
|
||||
def test_oaep_too_long(keypair):
|
||||
pub, priv = keypair
|
||||
r = rsa_oaep_encrypt(b"x" * 500, pub)
|
||||
assert is_err(r) and r[0] == PPYC_ERR_MESSAGE_TOO_LONG
|
||||
|
||||
|
||||
def test_oaep_corrupt_ciphertext(keypair):
|
||||
pub, priv = keypair
|
||||
ct = rsa_oaep_encrypt(b"msg", pub)
|
||||
bad = ct[:-1] + bytes([ct[-1] ^ 0xFF])
|
||||
r = rsa_oaep_decrypt(bad, priv)
|
||||
assert is_err(r) and r[0] == PPYC_ERR_DECRYPT_FAILED
|
||||
|
||||
|
||||
def test_pss_sign_verify(keypair):
|
||||
pub, priv = keypair
|
||||
for msg in (b"", b"x", b"sign me", os.urandom(100)):
|
||||
sig = rsa_pss_sign(msg, priv)
|
||||
assert rsa_pss_verify(msg, sig, pub)
|
||||
assert not rsa_pss_verify(msg + b"!", sig, pub)
|
||||
|
||||
|
||||
def test_pss_bad_signature(keypair):
|
||||
pub, priv = keypair
|
||||
sig = rsa_pss_sign(b"msg", priv)
|
||||
assert not rsa_pss_verify(b"msg", sig[:-1] + bytes([sig[-1] ^ 1]), pub)
|
||||
assert not rsa_pss_verify(b"msg", b"short", pub)
|
||||
|
||||
|
||||
def test_pem_roundtrip(keypair):
|
||||
pub, priv = keypair
|
||||
pem = private_key_to_pem(priv)
|
||||
assert "BEGIN PRIVATE KEY" in pem and "END PRIVATE KEY" in pem
|
||||
priv2 = parse_private_pem(pem)
|
||||
assert priv2.n == priv.n and priv2.e == priv.e
|
||||
assert priv2.p == priv.p and priv2.q == priv.q
|
||||
pub_pem = public_key_to_pem(pub)
|
||||
assert "BEGIN PUBLIC KEY" in pub_pem
|
||||
|
||||
|
||||
def test_der_encoding(keypair):
|
||||
pub, priv = keypair
|
||||
assert private_key_to_pkcs1_der(priv)[0] == 0x30
|
||||
assert public_key_to_pkcs1_der(pub)[0] == 0x30
|
||||
assert private_key_to_pkcs8_der(priv)[0] == 0x30
|
||||
assert public_key_to_spki_der(pub)[0] == 0x30
|
||||
|
||||
|
||||
def test_key_validation():
|
||||
# the constructor cannot return a tuple -> raises PPYC_ERR (fatal)
|
||||
# n is even (and the bit count is too small, choose_hash intercepts first -> INVALID_RSA_BITS)
|
||||
with pytest.raises(PPYC_ERR) as ei:
|
||||
RSAPublicKey(15, 3)
|
||||
assert ei.value.code in (PPYC_ERR_INVALID_KEY_MATERIAL, PPYC_ERR_INVALID_RSA_BITS)
|
||||
# e is even
|
||||
with pytest.raises(PPYC_ERR) as ei:
|
||||
RSAPublicKey(33, 2)
|
||||
assert ei.value.code in (PPYC_ERR_INVALID_KEY_MATERIAL, PPYC_ERR_INVALID_RSA_BITS)
|
||||
|
||||
|
||||
def test_parse_pem_cross_check(keypair):
|
||||
"""Re-parse the PEM and decrypt with it to confirm the key is usable."""
|
||||
pub, priv = keypair
|
||||
priv2 = parse_private_pem(private_key_to_pem(priv))
|
||||
ct = rsa_oaep_encrypt(b"cross check", pub)
|
||||
assert rsa_oaep_decrypt(ct, priv2) == b"cross check"
|
||||
@@ -0,0 +1,78 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""SHA-3 / Keccak / SHAKE / HMAC-SHA3 tests (FIPS 202)."""
|
||||
import hashlib
|
||||
import hmac as _hmac
|
||||
import os
|
||||
|
||||
import pytest
|
||||
|
||||
from purepycrypto import (
|
||||
sha3_224, sha3_256, sha3_384, sha3_512,
|
||||
shake128, shake256,
|
||||
hmac_sha3_256, hmac_sha3_512,
|
||||
)
|
||||
|
||||
from ._vectors import load
|
||||
|
||||
|
||||
def test_fips202_known_answers():
|
||||
assert sha3_256(b"").hex() == (
|
||||
"a7ffc6f8bf1ed76651c14756a061d662f580ff4de43b49fa82d80a4b80f8434a")
|
||||
assert sha3_256(b"abc").hex() == (
|
||||
"3a985da74fe225b2045c172d6bd390bd855f086e3e9d525b46bfe24511431532")
|
||||
assert sha3_512(b"").hex() == (
|
||||
"a69f73cca23a9ac5c8b567dc185a756e97c982164fe25859e0d1dcc1475c80a6"
|
||||
"15b2123af1f5f94c11e3e9402c3ac558f500199d95b6d3e301758586281dcd26")
|
||||
assert sha3_512(b"abc").hex() == (
|
||||
"b751850b1a57168a5693cd924b6b096e08f621827444f70d884f5d0240d2712e"
|
||||
"10e116e9192af3c91a7ec57647e3934057340b4cf408d5a56592f8274eec53f0")
|
||||
assert sha3_224(b"abc").hex() == (
|
||||
"e642824c3f8cf24ad09234ee7d3c766fc9a3a5168d0c94ad73b46fdf")
|
||||
assert sha3_384(b"abc").hex().startswith("ec01498288516fc926459f58e2c6ad8d")
|
||||
assert shake128(b"", 32).hex() == (
|
||||
"7f9c2ba4e88f827d616045507605853ed73b8093f6efbc88eb1a6eacfa66ef26")
|
||||
assert shake256(b"", 32).hex() == (
|
||||
"46b9dd2b0ba88d13233b3feb743eeb243fcd52ea62b81b82b50c27646ed5762f")
|
||||
|
||||
|
||||
def test_length_sweep_matches_hashlib():
|
||||
"""Cross-block boundary length sweep, exactly matching hashlib."""
|
||||
for length in (0, 1, 63, 64, 71, 72, 73, 103, 104, 105, 135, 136, 137,
|
||||
167, 168, 169, 500):
|
||||
data = os.urandom(length)
|
||||
assert sha3_224(data) == hashlib.sha3_224(data).digest()
|
||||
assert sha3_256(data) == hashlib.sha3_256(data).digest()
|
||||
assert sha3_384(data) == hashlib.sha3_384(data).digest()
|
||||
assert sha3_512(data) == hashlib.sha3_512(data).digest()
|
||||
assert shake128(data, 64) == hashlib.shake_128(data).digest(64)
|
||||
assert shake256(data, 64) == hashlib.shake_256(data).digest(64)
|
||||
|
||||
|
||||
def test_shake_variable_output_length():
|
||||
data = b"variable length test"
|
||||
for outlen in (16, 32, 64, 100, 200):
|
||||
assert len(shake128(data, outlen)) == outlen
|
||||
assert len(shake256(data, outlen)) == outlen
|
||||
assert shake128(data, outlen) == hashlib.shake_128(data).digest(outlen)
|
||||
assert shake256(data, outlen) == hashlib.shake_256(data).digest(outlen)
|
||||
|
||||
|
||||
def test_hmac_sha3_matches_stdlib():
|
||||
for key_len in (0, 16, 32, 100, 200):
|
||||
key = os.urandom(key_len)
|
||||
msg = os.urandom(80)
|
||||
assert hmac_sha3_256(key, msg) == _hmac.new(key, msg, hashlib.sha3_256).digest()
|
||||
assert hmac_sha3_512(key, msg) == _hmac.new(key, msg, hashlib.sha3_512).digest()
|
||||
|
||||
|
||||
def test_vectors_file():
|
||||
try:
|
||||
vec = load("sha3_fips202")
|
||||
except FileNotFoundError:
|
||||
pytest.skip("vectors/sha3_fips202.json missing")
|
||||
for case in vec.get("cases", []):
|
||||
msg = case["msg_utf8"].encode()
|
||||
assert sha3_224(msg).hex() == case["sha3_224"], case.get("id")
|
||||
assert sha3_256(msg).hex() == case["sha3_256"], case.get("id")
|
||||
assert sha3_384(msg).hex() == case["sha3_384"], case.get("id")
|
||||
assert sha3_512(msg).hex() == case["sha3_512"], case.get("id")
|
||||
@@ -0,0 +1,468 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Strict cryptographic standard-vector tests (v3.1.4).
|
||||
|
||||
All vectors come from public standards (FIPS / RFC / NIST), cross-verified with trusted implementations.
|
||||
References:
|
||||
- FIPS 180-4 (SHA-2) / FIPS 202 (SHA-3) / RFC 7693 (BLAKE2)
|
||||
- RFC 4231 (HMAC-SHA2) / RFC 6070 (PBKDF2) / RFC 5869 (HKDF)
|
||||
- RFC 7914 (scrypt) / RFC 9106 (Argon2)
|
||||
- FIPS 197 (AES) / NIST GCM
|
||||
- RFC 8439 (ChaCha20-Poly1305) / RFC 8452 (AES-GCM-SIV)
|
||||
- RFC 7748 (X25519) / RFC 8032 (Ed25519) / RFC 8017 (RSA)
|
||||
"""
|
||||
import hashlib
|
||||
import hmac
|
||||
import os
|
||||
|
||||
import pytest
|
||||
|
||||
import purepycrypto as ppc
|
||||
|
||||
H = bytes.fromhex
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# 1. SHA-2 (FIPS 180-4)
|
||||
# ======================================================================
|
||||
|
||||
SHA2_CASES = [
|
||||
("sha256", b"", "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"),
|
||||
("sha256", b"abc", "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"),
|
||||
("sha256", b"message digest",
|
||||
"f7846f55cf23e14eebeab5b4e1550cad5b509e3348fbc4efa3a1413d393cb650"),
|
||||
("sha256", b"abcdefghijklmnopqrstuvwxyz",
|
||||
"71c480df93d6ae2f1efad1447c66c9525e316218cf51fc8d9ed832f2daf18b73"),
|
||||
("sha512", b"",
|
||||
"cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce"
|
||||
"47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e"),
|
||||
("sha512", b"abc",
|
||||
"ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a"
|
||||
"2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f"),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("algo,msg,expect", SHA2_CASES)
|
||||
def test_sha2_official(algo, msg, expect):
|
||||
assert getattr(ppc, algo)(msg).hex() == expect
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# 2. SHA-3 / SHAKE (FIPS 202)
|
||||
# ======================================================================
|
||||
|
||||
SHA3_CASES = [
|
||||
("sha3_224", b"abc", "e642824c3f8cf24ad09234ee7d3c766fc9a3a5168d0c94ad73b46fdf"),
|
||||
("sha3_256", b"", "a7ffc6f8bf1ed76651c14756a061d662f580ff4de43b49fa82d80a4b80f8434a"),
|
||||
("sha3_256", b"abc", "3a985da74fe225b2045c172d6bd390bd855f086e3e9d525b46bfe24511431532"),
|
||||
("sha3_384", b"abc", "ec01498288516fc926459f58e2c6ad8df9b473cb0fc08c2596da7cf0e49be4b2"
|
||||
"98d88cea927ac7f539f1edf228376d25"),
|
||||
("sha3_512", b"",
|
||||
"a69f73cca23a9ac5c8b567dc185a756e97c982164fe25859e0d1dcc1475c80a6"
|
||||
"15b2123af1f5f94c11e3e9402c3ac558f500199d95b6d3e301758586281dcd26"),
|
||||
("sha3_512", b"abc",
|
||||
"b751850b1a57168a5693cd924b6b096e08f621827444f70d884f5d0240d2712e"
|
||||
"10e116e9192af3c91a7ec57647e3934057340b4cf408d5a56592f8274eec53f0"),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("fn,msg,expect", SHA3_CASES)
|
||||
def test_sha3_official(fn, msg, expect):
|
||||
assert getattr(ppc, fn)(msg).hex() == expect
|
||||
|
||||
|
||||
def test_shake_official():
|
||||
assert ppc.shake128(b"", 32).hex() == \
|
||||
"7f9c2ba4e88f827d616045507605853ed73b8093f6efbc88eb1a6eacfa66ef26"
|
||||
assert ppc.shake256(b"", 32).hex() == \
|
||||
"46b9dd2b0ba88d13233b3feb743eeb243fcd52ea62b81b82b50c27646ed5762f"
|
||||
|
||||
|
||||
def test_sha3_matches_hashlib_boundaries():
|
||||
"""Cross-block boundaries strictly compared with hashlib (SHA-3 rates: 72/104/136/144/168)."""
|
||||
for L in (0, 1, 71, 72, 73, 103, 104, 105, 135, 136, 137, 143, 144, 145,
|
||||
167, 168, 169, 1000, 4096):
|
||||
d = os.urandom(L)
|
||||
assert ppc.sha3_224(d) == hashlib.sha3_224(d).digest()
|
||||
assert ppc.sha3_256(d) == hashlib.sha3_256(d).digest()
|
||||
assert ppc.sha3_384(d) == hashlib.sha3_384(d).digest()
|
||||
assert ppc.sha3_512(d) == hashlib.sha3_512(d).digest()
|
||||
assert ppc.shake128(d, 64) == hashlib.shake_128(d).digest(64)
|
||||
assert ppc.shake256(d, 64) == hashlib.shake_256(d).digest(64)
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# 3. BLAKE2b (RFC 7693)
|
||||
# ======================================================================
|
||||
|
||||
def test_blake2b_official():
|
||||
assert ppc.blake2b(b"abc", 64).hex() == (
|
||||
"ba80a53f981c4d0d6a2797b69f12f6e94c212f14685ac4b74b12bb6fdbffa2d1"
|
||||
"7d87c5392aab792dc252d5de4533cc9518d38aa8dbf1925ab92386edd4009923")
|
||||
assert ppc.blake2b(b"", 64).hex() == (
|
||||
"786a02f742015903c6c6fd852552d272912f4740e15847618a86e217f71f5419"
|
||||
"d25e1031afee585313896444934eb04b903a685b1448b755d56f701afe9be2ce")
|
||||
|
||||
|
||||
def test_blake2b_matches_hashlib_boundaries():
|
||||
"""BLAKE2b cross-block (128-byte) boundaries + variable-length digest (including the old multiple-of-128 defect)."""
|
||||
for L in (0, 1, 127, 128, 129, 255, 256, 257, 384, 1000):
|
||||
d = os.urandom(L)
|
||||
for ds in (16, 32, 64):
|
||||
assert ppc.blake2b(d, ds) == hashlib.blake2b(d, digest_size=ds).digest()
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# 4. HMAC-SHA2 (RFC 4231)
|
||||
# ======================================================================
|
||||
|
||||
RFC4231 = [
|
||||
(1, b"\x0b" * 20, b"Hi There",
|
||||
"b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7",
|
||||
"87aa7cdea5ef619d4ff0b4241a1d6cb02379f4e2ce4ec2787ad0b30545e17cde"
|
||||
"daa833b7d6b8a702038b274eaea3f4e4be9d914eeb61f1702e696c203a126854"),
|
||||
(2, b"Jefe", b"what do ya want for nothing?",
|
||||
"5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843",
|
||||
"164b7a7bfcf819e2e395fbe73b56e0a387bd64222e831fd610270cd7ea250554"
|
||||
"9758bf75c05a994a6d034f65f8f0e6fdcaeab1a34d4a6b4b636e070a38bce737"),
|
||||
(4, b"\x01" * 25, b"\xcd" * 50,
|
||||
"cd9ff198fcd488ca2385a0242dd9b33de3171bed743d8407d8a8c100754a61a7",
|
||||
"f48812fede955842467a5bd0118fb6fd9a59881bdfba7217bd1a9bf5353f07b6"
|
||||
"acf5184cc58fd3a60288dc7d34de2db83737102a78e26d0286610a57fc2cf6b4"),
|
||||
(6, b"\xaa" * 131, b"Test Using Larger Than Block-Size Key - Hash Key First",
|
||||
"60e431591ee0b67f0d8a26aacbf5b77f8e0bc6213728c5140546040f0ee37f54",
|
||||
"80b24263c7c1a3ebb71493c1dd7be8b49b46d1f41b4aeec1121b013783f8f352"
|
||||
"6b56d037e05f2598bd0fd2215d6a1e5295e64f73f63f0aec8b915a985d786598"),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("cid,key,msg,h256,h512", RFC4231)
|
||||
def test_hmac_sha256_rfc4231(cid, key, msg, h256, h512):
|
||||
assert ppc.hmac_sha256(key, msg).hex() == h256
|
||||
|
||||
|
||||
@pytest.mark.parametrize("cid,key,msg,h256,h512", RFC4231)
|
||||
def test_hmac_sha512_rfc4231(cid, key, msg, h256, h512):
|
||||
assert ppc.hmac_sha512(key, msg).hex() == h512
|
||||
|
||||
|
||||
def test_hmac_matches_stdlib_random():
|
||||
for klen in (0, 16, 64, 65, 128, 200):
|
||||
for mlen in (0, 1, 100, 1000):
|
||||
k, m = os.urandom(klen), os.urandom(mlen)
|
||||
assert ppc.hmac_sha256(k, m) == hmac.new(k, m, hashlib.sha256).digest()
|
||||
assert ppc.hmac_sha512(k, m) == hmac.new(k, m, hashlib.sha512).digest()
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# 5. PBKDF2 (RFC 6070 style)
|
||||
# ======================================================================
|
||||
|
||||
def test_pbkdf2_matches_hashlib():
|
||||
for it in (1, 2, 4096):
|
||||
for dklen in (20, 32, 64):
|
||||
got = ppc.pbkdf2_hmac(b"password", b"salt", it, dklen, "sha256")
|
||||
exp = hashlib.pbkdf2_hmac("sha256", b"password", b"salt", it, dklen)
|
||||
assert got == exp, f"iter={it} dklen={dklen}"
|
||||
|
||||
|
||||
def test_pbkdf2_sha256_known():
|
||||
assert ppc.pbkdf2_hmac(b"passwd", b"salt", 1, 64, "sha256").hex() == \
|
||||
("55ac046e56e3089fec1691c22544b605f94185216dde0465e68b9d57c20dacbc"
|
||||
"49ca9cccf179b645991664b39d77ef317c71b845b1e30bd509112041d3a19783")
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# 6. HKDF (RFC 5869 TC1/TC2/TC3)
|
||||
# ======================================================================
|
||||
|
||||
RFC5869 = [
|
||||
(1, H("0b" * 22), H("000102030405060708090a0b0c"), H("f0f1f2f3f4f5f6f7f8f9"), 42,
|
||||
"077709362c2e32df0ddc3f0dc47bba6390b6c73bb50f9c3122ec844ad7c2b3e5",
|
||||
"3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf"
|
||||
"34007208d5b887185865"),
|
||||
(2,
|
||||
H("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f"
|
||||
"202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f"
|
||||
"404142434445464748494a4b4c4d4e4f"),
|
||||
H("606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f"
|
||||
"808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9f"
|
||||
"a0a1a2a3a4a5a6a7a8a9aaabacadaeaf"),
|
||||
H("b0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecf"
|
||||
"d0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeef"
|
||||
"f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff"),
|
||||
82,
|
||||
"06a6b88c5853361a06104c9ceb35b45cef760014904671014a193f40c15fc244",
|
||||
"b11e398dc80327a1c8e7f78c596a49344f012eda2d4efad8a050cc4c19afa97c"
|
||||
"59045a99cac7827271cb41c65e590e09da3275600c2f09b8367793a9aca3db71"
|
||||
"cc30c58179ec3e87c14c01d5c1f3434f1d87"),
|
||||
(3, H("0b" * 22), b"", b"", 42,
|
||||
"19ef24a32c717b167f33a91d6f648bdf96596776afdb6377ac434c1c293ccb04",
|
||||
"8da4e775a563c18f715f802a063c5a31b8a11f5c5ee1879ec3454e5f3c738d2d"
|
||||
"9d201395faa4b61a96c8"),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("cid,ikm,salt,info,L,prk,okm", RFC5869)
|
||||
def test_hkdf_rfc5869(cid, ikm, salt, info, L, prk, okm):
|
||||
assert ppc.hkdf_extract(salt, ikm).hex() == prk
|
||||
assert ppc.hkdf_expand(H(prk), info, L).hex() == okm
|
||||
assert ppc.hkdf(ikm, salt, info, L).hex() == okm
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# 7. scrypt (RFC 7914)
|
||||
# ======================================================================
|
||||
|
||||
def test_scrypt_rfc7914_small():
|
||||
assert ppc.scrypt(b"", b"", N=16, r=1, p=1, dklen=64).hex() == \
|
||||
("77d6576238657b203b19ca42c18a0497f16b4844e3074ae8dfdffa3fede21442"
|
||||
"fcd0069ded0948f8326a753a0fc81f17e8d3e0fb2e0d3628cf35e20c38d18906")
|
||||
|
||||
|
||||
def test_scrypt_rfc7914_medium():
|
||||
assert ppc.scrypt(b"password", b"NaCl", N=1024, r=8, p=16, dklen=64).hex() == \
|
||||
("fdbabe1c9d3472007856e7190d01e9fe7c6ad7cbc8237830e77376634b373162"
|
||||
"2eaf30d92e22a3886ff109279d9830dac727afb94a83ee6d8360cbdfa2cc0640")
|
||||
|
||||
|
||||
def test_scrypt_matches_hashlib():
|
||||
got = ppc.scrypt(b"pleaseletmein", b"SodiumChloride", N=16384, r=8, p=1, dklen=64)
|
||||
exp = hashlib.scrypt(b"pleaseletmein", salt=b"SodiumChloride",
|
||||
n=16384, r=8, p=1, dklen=64)
|
||||
assert got == exp
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# 8. Argon2id (RFC 9106)
|
||||
# ======================================================================
|
||||
|
||||
def test_argon2id_rfc9106():
|
||||
tag = ppc.argon2id(b"\x01" * 32, b"\x02" * 16, t=3, m=32, p=4,
|
||||
tag_length=32, secret=b"\x03" * 8, ad=b"\x04" * 12)
|
||||
assert tag.hex() == "0d640df58d78766c08c037a34a8b53c9d01ef0452d75b65eb52520e96b01e659"
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# 9. AES (FIPS 197 + all-mode round-trip + GCM)
|
||||
# ======================================================================
|
||||
|
||||
KEY128 = H("000102030405060708090a0b0c0d0e0f")
|
||||
KEY192 = H("000102030405060708090a0b0c0d0e0f1011121314151617")
|
||||
KEY256 = H("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f")
|
||||
PT = H("00112233445566778899aabbccddeeff")
|
||||
|
||||
|
||||
def test_aes_fips197_block():
|
||||
assert ppc.AES(KEY128).encrypt_block(PT).hex() == "69c4e0d86a7b0430d8cdb78070b4c55a"
|
||||
assert ppc.AES(KEY192).encrypt_block(PT).hex() == "dda97ca4864cdfe06eaf70a0ec0d7191"
|
||||
assert ppc.AES(KEY256).encrypt_block(PT).hex() == "8ea2b7ca516745bfeafc49904b496089"
|
||||
|
||||
|
||||
def test_aes_roundtrip_all_modes():
|
||||
iv16 = os.urandom(16)
|
||||
nonce8 = os.urandom(8)
|
||||
for key in (KEY128, KEY192, KEY256):
|
||||
a = ppc.AES(key)
|
||||
for L in (0, 1, 15, 16, 17, 64, 100):
|
||||
d = os.urandom(L)
|
||||
assert a.decrypt_ecb(a.encrypt_ecb(d)) == d
|
||||
assert a.decrypt_cbc(a.encrypt_cbc(d, iv16), iv16) == d
|
||||
assert a.decrypt_ctr(a.encrypt_ctr(d, nonce8), nonce8) == d
|
||||
assert a.decrypt_cfb(a.encrypt_cfb(d, iv16), iv16) == d
|
||||
assert a.decrypt_ofb(a.encrypt_ofb(d, iv16), iv16) == d
|
||||
|
||||
|
||||
def test_aes_gcm_nist_known():
|
||||
a = ppc.AES(bytes(16))
|
||||
ct, tag = a.gcm_encrypt(bytes(12), b"", b"")
|
||||
assert ct == b"" and tag.hex() == "58e2fccefa7e3061367f1d57a4e7455a"
|
||||
ct, tag = a.gcm_encrypt(bytes(12), bytes(16), b"")
|
||||
assert ct.hex() == "0388dace60b6a392f328c2b971b2fe78"
|
||||
assert tag.hex() == "ab6e47d42cec13bdf53a67b21257bddf"
|
||||
|
||||
|
||||
def test_aes_gcm_vs_pycryptodome():
|
||||
try:
|
||||
from Crypto.Cipher import AES as PAES
|
||||
except ImportError:
|
||||
pytest.skip("pycryptodome not installed")
|
||||
for _ in range(20):
|
||||
key = os.urandom(16)
|
||||
nonce = os.urandom(12)
|
||||
aad = os.urandom(20)
|
||||
data = os.urandom(100)
|
||||
ct, tag = ppc.AES(key).gcm_encrypt(nonce, data, aad)
|
||||
ref = PAES.new(key, PAES.MODE_GCM, nonce=nonce)
|
||||
ref.update(aad)
|
||||
rct, rtag = ref.encrypt_and_digest(data)
|
||||
assert ct == rct and tag == rtag
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# 10. ChaCha20-Poly1305 (RFC 8439 §2.8.2)
|
||||
# ======================================================================
|
||||
|
||||
def test_chacha20poly1305_rfc8439():
|
||||
key = H("808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9f")
|
||||
nonce = H("070000004041424344454647")
|
||||
aad = H("50515253c0c1c2c3c4c5c6c7")
|
||||
plaintext = (b"Ladies and Gentlemen of the class of '99: If I could offer you "
|
||||
b"only one tip for the future, sunscreen would be it.")
|
||||
expect_ct = H(
|
||||
"d31a8d34648e60db7b86afbc53ef7ec2a4aded51296e08fea9e2b5a736ee62d6"
|
||||
"3dbea45e8ca9671282fafb69da92728b1a71de0a9e060b2905d6a5b67ecd3b36"
|
||||
"92ddbd7f2d778b8c9803aee328091b58fab324e4fad675945585808b4831d7bc"
|
||||
"3ff4def08e4b7a9de576d26586cec64b6116")
|
||||
expect_tag = H("1ae10b594f09e26a7e902ecbd0600691")
|
||||
out = ppc.chacha20poly1305_encrypt(key, nonce, plaintext, aad)
|
||||
assert out[:-16] == expect_ct
|
||||
assert out[-16:] == expect_tag
|
||||
assert ppc.chacha20poly1305_decrypt(key, nonce, out, aad) == plaintext
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# 11. AES-GCM-SIV (RFC 8452 Appendix C.1)
|
||||
# ======================================================================
|
||||
|
||||
GCM_SIV_C1 = [
|
||||
(b"", b"", "dc20e2d83f25705bb49e439eca56de25"),
|
||||
(H("0100000000000000"), H("b5d839330ac7b786"), "578782fff6013b815b287c22493a364c"),
|
||||
(H("010000000000000000000000"), H("7323ea61d05932260047d942"),
|
||||
"a4978db357391a0bc4fdec8b0d106639"),
|
||||
(H("01000000000000000000000000000000"), H("743f7c8077ab25f8624e2e948579cf77"),
|
||||
"303aaf90f6fe21199c6068577437a0c4"),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("pt,ct,tag", GCM_SIV_C1)
|
||||
def test_gcm_siv_rfc8452_c1(pt, ct, tag):
|
||||
key = H("01000000000000000000000000000000")
|
||||
nonce = H("030000000000000000000000")
|
||||
got_ct, got_tag = ppc.aes128_gcm_siv_encrypt(key, nonce, pt)
|
||||
assert got_ct == ct
|
||||
assert got_tag.hex() == tag
|
||||
assert ppc.aes128_gcm_siv_decrypt(key, nonce, got_ct, got_tag) == pt
|
||||
|
||||
|
||||
def test_gcm_siv_rfc8452_c2_aes256():
|
||||
key = H("0100000000000000000000000000000000000000000000000000000000000000")
|
||||
nonce = H("030000000000000000000000")
|
||||
ct, tag = ppc.aes256_gcm_siv_encrypt(key, nonce, b"")
|
||||
assert ct == b""
|
||||
assert tag.hex() == "07f5f4169bbf55a8400cd47ea6fd400f"
|
||||
|
||||
|
||||
def test_gcm_siv_vs_cryptography():
|
||||
try:
|
||||
from cryptography.hazmat.primitives.ciphers.aead import AESGCMSIV
|
||||
except ImportError:
|
||||
pytest.skip("cryptography>=45 not installed")
|
||||
for _ in range(10):
|
||||
key = os.urandom(16)
|
||||
nonce = os.urandom(12)
|
||||
pt = os.urandom(50)
|
||||
aad = os.urandom(10)
|
||||
ref = AESGCMSIV(key).encrypt(nonce, pt, aad)
|
||||
ct, tag = ppc.aes128_gcm_siv_encrypt(key, nonce, pt, aad)
|
||||
assert ct == ref[:-16] and tag == ref[-16:]
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# 12. X25519 (RFC 7748)
|
||||
# ======================================================================
|
||||
|
||||
def test_x25519_rfc7748_scalarmult():
|
||||
k = H("a546e36bf0527c9d3b16154b82465edd62144c0ac1fc5a18506a2244ba449ac4")
|
||||
u = H("e6db6867583030db3594c1a424b15f7c726624ec26b3353b10a903a6d0ab1c4c")
|
||||
assert ppc.x25519(k, u).hex() == \
|
||||
"c3da55379de9c6908e94ea4df28d084f32eccf03491c71f754b4075577a28552"
|
||||
|
||||
|
||||
def test_x25519_rfc7748_dh():
|
||||
a = H("77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a")
|
||||
b = H("5dab087e624a8a4b79e17f8b83800ee66f3bb1292618b6fd1c2f8b27ff88e0eb")
|
||||
KA = ppc.x25519_base(a)
|
||||
KB = ppc.x25519_base(b)
|
||||
assert KA.hex() == "8520f0098930a754748b7ddcb43ef75a0dbf3a0d26381af4eba4a98eaa9b4e6a"
|
||||
assert KB.hex() == "de9edb7d7b7dc1b4d35b61c2ece435373f8343c85b78674dadfc7e146f882b4f"
|
||||
sa, _ = ppc.x25519_shared(a, KB)
|
||||
sb, _ = ppc.x25519_shared(b, KA)
|
||||
assert sa == sb
|
||||
assert sa.hex() == "4a5d9d5ba4ce2de1728e3bf480350f25e07e21c947d19e3376f09b3c1e161742"
|
||||
|
||||
|
||||
def test_x25519_rfc7748_iterated_1():
|
||||
k = H("0900000000000000000000000000000000000000000000000000000000000000")
|
||||
assert ppc.x25519(k, k).hex() == \
|
||||
"422c8e7a6227d7bca1350b3e2bb7279f7897b87bb6854b783c60e80311ae3079"
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# 13. Ed25519 (RFC 8032 §7.1)
|
||||
# ======================================================================
|
||||
|
||||
ED25519 = [
|
||||
("TEST1",
|
||||
"9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60",
|
||||
"d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a", "",
|
||||
"e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b"),
|
||||
("TEST2",
|
||||
"4ccd089b28ff96da9db6c346ec114e0f5b8a319f35aba624da8cf6ed4fb8a6fb",
|
||||
"3d4017c3e843895a92b70aa74d1b7ebc9c982ccf2ec4968cc0cd55f12af4660c", "72",
|
||||
"92a009a9f0d4cab8720e820b5f642540a2b27b5416503f8fb3762223ebdb69da085ac1e43e15996e458f3613d0f11d8c387b2eaeb4302aeeb00d291612bb0c00"),
|
||||
("TEST3",
|
||||
"c5aa8df43f9f837bedb7442f31dcb7b166d38535076f094b85ce3a2e0b4458f7",
|
||||
"fc51cd8e6218a1a38da47ed00230f0580816ed13ba3303ac5deb911548908025", "af82",
|
||||
"6291d657deec24024827e69c3abe01a30ce548a284743a445e3680d7db5ac3ac18ff9b538d16f290ae67f760984dc6594a7c15e9716ed28dc027beceea1ec40a"),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("cid,sec,pub,msg,sig", ED25519)
|
||||
def test_ed25519_rfc8032(cid, sec, pub, msg, sig):
|
||||
seed = H(sec)
|
||||
m = H(msg)
|
||||
assert ppc.ed25519_publickey(seed).hex() == pub
|
||||
assert ppc.ed25519_sign(m, seed).hex() == sig
|
||||
assert ppc.ed25519_verify(H(sig), m, H(pub)) is True
|
||||
|
||||
|
||||
@pytest.mark.parametrize("cid,sec,pub,msg,sig", ED25519)
|
||||
def test_ed25519_tamper_rejected(cid, sec, pub, msg, sig):
|
||||
seed = H(sec)
|
||||
m = H(msg)
|
||||
p = H(pub)
|
||||
good = ppc.ed25519_sign(m, seed)
|
||||
bad = good[:-1] + bytes([good[-1] ^ 1])
|
||||
assert ppc.ed25519_verify(bad, m, p) is False
|
||||
assert ppc.ed25519_verify(good, m + b"\x00", p) is False
|
||||
|
||||
|
||||
def test_ed25519_long_message():
|
||||
"""1023/1024/1025-byte boundaries."""
|
||||
seed, pub = ppc.ed25519_keygen()
|
||||
for L in (1023, 1024, 1025):
|
||||
m = os.urandom(L)
|
||||
assert ppc.ed25519_verify(ppc.ed25519_sign(m, seed), m, pub)
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# 14. RSA (OAEP/PSS round-trip + boundaries)
|
||||
# ======================================================================
|
||||
|
||||
def test_rsa_oaep_roundtrip_various():
|
||||
pub, priv = ppc.rsa_keygen(bits=1024, parallel=False)
|
||||
for L in (0, 1, 16, 62): # 1024 bits + SHA-256 -> 62-byte upper limit
|
||||
m = os.urandom(L)
|
||||
ct = ppc.rsa_oaep_encrypt(m, pub)
|
||||
assert not isinstance(ct, tuple), f"encryption failed: {ct}"
|
||||
assert ppc.rsa_oaep_decrypt(ct, priv) == m
|
||||
|
||||
|
||||
def test_rsa_pss_verify_various():
|
||||
pub, priv = ppc.rsa_keygen(bits=1024, parallel=False)
|
||||
for L in (0, 1, 100, 500):
|
||||
m = os.urandom(L)
|
||||
sig = ppc.rsa_pss_sign(m, priv)
|
||||
assert not isinstance(sig, tuple)
|
||||
assert ppc.rsa_pss_verify(m, sig, pub) is True
|
||||
assert ppc.rsa_pss_verify(m + b"!", sig, pub) is False
|
||||
@@ -0,0 +1,68 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""X25519 tests (RFC 7748)."""
|
||||
import os
|
||||
|
||||
import pytest
|
||||
|
||||
from purepycrypto import is_err, PPYC_ERR_INVALID_LENGTH
|
||||
|
||||
from purepycrypto import x25519, x25519_base, x25519_shared, x25519_generate_keypair
|
||||
|
||||
|
||||
def test_rfc7748_vector1():
|
||||
scalar = bytes.fromhex("a546e36bf0527c9d3b16154b82465edd"
|
||||
"62144c0ac1fc5a18506a2244ba449ac4")
|
||||
u = bytes.fromhex("e6db6867583030db3594c1a424b15f7c"
|
||||
"726624ec26b3353b10a903a6d0ab1c4c")
|
||||
expect = bytes.fromhex("c3da55379de9c6908e94ea4df28d084f"
|
||||
"32eccf03491c71f754b4075577a28552")
|
||||
assert x25519(scalar, u) == expect
|
||||
|
||||
|
||||
def test_rfc7748_vector2():
|
||||
scalar = bytes.fromhex("4b66e9d4d1b4673c5ad22691957d6af5"
|
||||
"c11b6421e0ea01d42ca4169e7918ba0d")
|
||||
u = bytes.fromhex("e5210f12786811d3f4b7959d0538ae2c"
|
||||
"31dbe7106fc03c3efc4cd549c715a493")
|
||||
expect = bytes.fromhex("95cbde9476e8907d7aade45cb4b873f8"
|
||||
"8b595a68799fa152e6f8f7647aac7957")
|
||||
assert x25519(scalar, u) == expect
|
||||
|
||||
|
||||
def test_rfc7748_dh():
|
||||
a = bytes.fromhex("77076d0a7318a57d3c16c17251b26645"
|
||||
"df4c2f87ebc0992ab177fba51db92c2a")
|
||||
b = bytes.fromhex("5dab087e624a8a4b79e17f8b83800ee6"
|
||||
"6f3bb1292618b6fd1c2f8b27ff88e0eb")
|
||||
KA = x25519_base(a)
|
||||
KB = x25519_base(b)
|
||||
assert KA.hex() == ("8520f0098930a754748b7ddcb43ef75a"
|
||||
"0dbf3a0d26381af4eba4a98eaa9b4e6a")
|
||||
assert KB.hex() == ("de9edb7d7b7dc1b4d35b61c2ece43537"
|
||||
"3f8343c85b78674dadfc7e146f882b4f")
|
||||
shared_a, zero_a = x25519_shared(a, KB)
|
||||
shared_b, zero_b = x25519_shared(b, KA)
|
||||
assert shared_a == shared_b
|
||||
assert shared_a.hex() == ("4a5d9d5ba4ce2de1728e3bf480350f25"
|
||||
"e07e21c947d19e3376f09b3c1e161742")
|
||||
assert not zero_a and not zero_b
|
||||
|
||||
|
||||
def test_generate_keypair():
|
||||
priv, pub = x25519_generate_keypair()
|
||||
assert len(priv) == 32 and len(pub) == 32
|
||||
assert x25519_base(priv) == pub
|
||||
|
||||
|
||||
def test_low_order_point_detected():
|
||||
"""An all-zero u is a low-order point -> the shared secret should be all zero and flagged."""
|
||||
priv = os.urandom(32)
|
||||
shared, zero = x25519_shared(priv, bytes(32))
|
||||
assert shared == bytes(32) and zero is True
|
||||
|
||||
|
||||
def test_bad_lengths():
|
||||
r = x25519(b"short", bytes(32))
|
||||
assert is_err(r) and r[0] == PPYC_ERR_INVALID_LENGTH
|
||||
r = x25519(bytes(32), b"short")
|
||||
assert is_err(r) and r[0] == PPYC_ERR_INVALID_LENGTH
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"_comment": "AES single-block test vectors from FIPS 197 (Appendix B example key and Appendix C.1/C.2/C.3). Plaintext is the FIPS 197 example block 00112233445566778899aabbccddeeff. Independently verified with PyCryptodome.",
|
||||
"name": "aes_fips197",
|
||||
"source": "FIPS 197",
|
||||
"plaintext_hex": "00112233445566778899aabbccddeeff",
|
||||
"cases": [
|
||||
{"id": "aes128", "cipher": "AES-128", "key_bits": 128, "key_hex": "000102030405060708090a0b0c0d0e0f", "plaintext_hex": "00112233445566778899aabbccddeeff", "ciphertext_hex": "69c4e0d86a7b0430d8cdb78070b4c55a"},
|
||||
{"id": "aes192", "cipher": "AES-192", "key_bits": 192, "key_hex": "000102030405060708090a0b0c0d0e0f1011121314151617", "plaintext_hex": "00112233445566778899aabbccddeeff", "ciphertext_hex": "dda97ca4864cdfe06eaf70a0ec0d7191"},
|
||||
{"id": "aes256", "cipher": "AES-256", "key_bits": 256, "key_hex": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", "plaintext_hex": "00112233445566778899aabbccddeeff", "ciphertext_hex": "8ea2b7ca516745bfeafc49904b496089"}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"_comment": "AES-128-GCM test vectors from the NIST/McGrew-Viega GCM specification (Test Case 1 and 2). key = 00*16, nonce/IV = 00*12, no AAD. Independently verified with PyCryptodome.",
|
||||
"name": "aes_gcm_nist",
|
||||
"source": "NIST SP 800-38D / GCM specification",
|
||||
"cipher": "AES-128-GCM",
|
||||
"key_hex": "00000000000000000000000000000000",
|
||||
"nonce_hex": "000000000000000000000000",
|
||||
"aad_hex": "",
|
||||
"cases": [
|
||||
{"id": "gcm_tc1_empty", "plaintext_hex": "", "ciphertext_hex": "", "tag_hex": "58e2fccefa7e3061367f1d57a4e7455a"},
|
||||
{"id": "gcm_tc2_zeros16", "plaintext_hex": "00000000000000000000000000000000", "ciphertext_hex": "0388dace60b6a392f328c2b971b2fe78", "tag_hex": "ab6e47d42cec13bdf53a67b21257bddf"}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"_comment": "Argon2id test vector from RFC 9106 Section 5.3. password = 0x01*32, salt = 0x02*16, secret(key) = 0x03*8, associated data = 0x04*12, t=3, m=32 (KiB), p=4, taglen=32, version=0x13. The tag was independently verified using the reference Argon2 C implementation (via the argon2-cffi low-level FFI, which supports secret and associated data).",
|
||||
"name": "argon2id_rfc9106",
|
||||
"source": "RFC 9106 Section 5.3",
|
||||
"type": "argon2id",
|
||||
"type_value": 2,
|
||||
"cases": [
|
||||
{
|
||||
"id": "rfc9106_argon2id_tc1",
|
||||
"type": "argon2id",
|
||||
"version": 19,
|
||||
"password_hex": "0101010101010101010101010101010101010101010101010101010101010101",
|
||||
"salt_hex": "02020202020202020202020202020202",
|
||||
"secret_hex": "0303030303030303",
|
||||
"ad_hex": "040404040404040404040404",
|
||||
"t_cost": 3,
|
||||
"m_cost": 32,
|
||||
"lanes": 4,
|
||||
"threads": 4,
|
||||
"parallelism": 4,
|
||||
"taglen": 32,
|
||||
"tag_hex": "0d640df58d78766c08c037a34a8b53c9d01ef0452d75b65eb52520e96b01e659"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"_comment": "BLAKE2b-512 test vectors. Source: RFC 7693 and the canonical BLAKE2 reference test vectors. All digests independently verified with Python hashlib.blake2b.",
|
||||
"name": "blake2b",
|
||||
"source": "RFC 7693 / BLAKE2 reference",
|
||||
"digest_size": 64,
|
||||
"cases": [
|
||||
{"id": "blake2b512_empty", "algorithm": "blake2b", "msg_utf8": "", "digest_hex": "786a02f742015903c6c6fd852552d272912f4740e15847618a86e217f71f5419d25e1031afee585313896444934eb04b903a685b1448b755d56f701afe9be2ce"},
|
||||
{"id": "blake2b512_abc", "algorithm": "blake2b", "msg_utf8": "abc", "digest_hex": "ba80a53f981c4d0d6a2797b69f12f6e94c212f14685ac4b74b12bb6fdbffa2d17d87c5392aab792dc252d5de4533cc9518d38aa8dbf1925ab92386edd4009923"},
|
||||
{"id": "blake2b512_fox", "algorithm": "blake2b", "msg_utf8": "The quick brown fox jumps over the lazy dog", "digest_hex": "a8add4bdddfd93e4877d2746e62817b116364a1fa7bc148d95090bc7333b3673f82401cf7aa2e4cb1ecd90296e3f14cb5413f8ed77be73045b13914cdcd6a918"}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"_comment": "Ed25519 test vectors (RFC 8032 Section 7.1). secret=seed(32B), public(32B), msg, signature(64B).",
|
||||
"name": "ed25519_rfc8032",
|
||||
"source": "RFC 8032",
|
||||
"cases": [
|
||||
{
|
||||
"id": "TEST1",
|
||||
"secret": "9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60",
|
||||
"public": "d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a",
|
||||
"msg": "",
|
||||
"signature": "e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b"
|
||||
},
|
||||
{
|
||||
"id": "TEST2",
|
||||
"secret": "4ccd089b28ff96da9db6c346ec114e0f5b8a319f35aba624da8cf6ed4fb8a6fb",
|
||||
"public": "3d4017c3e843895a92b70aa74d1b7ebc9c982ccf2ec4968cc0cd55f12af4660c",
|
||||
"msg": "72",
|
||||
"signature": "92a009a9f0d4cab8720e820b5f642540a2b27b5416503f8fb3762223ebdb69da085ac1e43e15996e458f3613d0f11d8c387b2eaeb4302aeeb00d291612bb0c00"
|
||||
},
|
||||
{
|
||||
"id": "TEST3",
|
||||
"secret": "c5aa8df43f9f837bedb7442f31dcb7b166d38535076f094b85ce3a2e0b4458f7",
|
||||
"public": "fc51cd8e6218a1a38da47ed00230f0580816ed13ba3303ac5deb911548908025",
|
||||
"msg": "af82",
|
||||
"signature": "6291d657deec24024827e69c3abe01a30ce548a284743a445e3680d7db5ac3ac18ff9b538d16f290ae67f760984dc6594a7c15e9716ed28dc027beceea1ec40a"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
{
|
||||
"_comment": "HKDF with HMAC-SHA256 test vectors from RFC 5869 Appendix A (Test Cases 1, 2 and 3). PRK and OKM both independently verified with a reference HKDF implementation.",
|
||||
"name": "hkdf_rfc5869",
|
||||
"source": "RFC 5869 Appendix A",
|
||||
"hash": "sha256",
|
||||
"cases": [
|
||||
{
|
||||
"id": "rfc5869_tc1",
|
||||
"IKM_hex": "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b",
|
||||
"salt_hex": "000102030405060708090a0b0c",
|
||||
"info_hex": "f0f1f2f3f4f5f6f7f8f9",
|
||||
"L": 42,
|
||||
"PRK_hex": "077709362c2e32df0ddc3f0dc47bba6390b6c73bb50f9c3122ec844ad7c2b3e5",
|
||||
"OKM_hex": "3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865"
|
||||
},
|
||||
{
|
||||
"id": "rfc5869_tc2",
|
||||
"IKM_hex": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f",
|
||||
"salt_hex": "606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeaf",
|
||||
"info_hex": "b0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
|
||||
"L": 82,
|
||||
"PRK_hex": "06a6b88c5853361a06104c9ceb35b45cef760014904671014a193f40c15fc244",
|
||||
"OKM_hex": "b11e398dc80327a1c8e7f78c596a49344f012eda2d4efad8a050cc4c19afa97c59045a99cac7827271cb41c65e590e09da3275600c2f09b8367793a9aca3db71cc30c58179ec3e87c14c01d5c1f3434f1d87"
|
||||
},
|
||||
{
|
||||
"id": "rfc5869_tc3_zero_salt_info",
|
||||
"IKM_hex": "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b",
|
||||
"salt_hex": "",
|
||||
"info_hex": "",
|
||||
"L": 42,
|
||||
"PRK_hex": "19ef24a32c717b167f33a91d6f648bdf96596776afdb6377ac434c1c293ccb04",
|
||||
"OKM_hex": "8da4e775a563c18f715f802a063c5a31b8a11f5c5ee1879ec3454e5f3c738d2d9d201395faa4b61a96c8"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"_comment": "PBKDF2-HMAC-SHA256 test vectors. The first two are the official PBKDF2-HMAC-SHA-256 vectors from RFC 7914 Section 11; the rest are widely used RFC 6070-style vectors re-derived for HMAC-SHA256. All values independently verified with Python hashlib.pbkdf2_hmac.",
|
||||
"name": "pbkdf2",
|
||||
"source": "RFC 7914 Section 11 / RFC 6070 style",
|
||||
"hash": "sha256",
|
||||
"cases": [
|
||||
{"id": "pbkdf2_sha256_passwd_salt_c1_dk64", "algorithm": "sha256", "password_utf8": "passwd", "salt_utf8": "salt", "iterations": 1, "dklen": 64, "derived_key_hex": "55ac046e56e3089fec1691c22544b605f94185216dde0465e68b9d57c20dacbc49ca9cccf179b645991664b39d77ef317c71b845b1e30bd509112041d3a19783"},
|
||||
{"id": "pbkdf2_sha256_Password_NaCl_c80000_dk64", "algorithm": "sha256", "password_utf8": "Password", "salt_utf8": "NaCl", "iterations": 80000, "dklen": 64, "derived_key_hex": "4ddcd8f60b98be21830cee5ef22701f9641a4418d04c0414aeff08876b34ab56a1d425a1225833549adb841b51c9b3176a272bdebba1d078478f62b397f33c8d"},
|
||||
{"id": "pbkdf2_sha256_password_salt_c1_dk64", "algorithm": "sha256", "password_utf8": "password", "salt_utf8": "salt", "iterations": 1, "dklen": 64, "derived_key_hex": "120fb6cffcf8b32c43e7225256c4f837a86548c92ccc35480805987cb70be17b4dbf3a2f3dad3377264bb7b8e8330d4efc7451418617dabef683735361cdc18c"},
|
||||
{"id": "pbkdf2_sha256_password_salt_c4096_dk32", "algorithm": "sha256", "password_utf8": "password", "salt_utf8": "salt", "iterations": 4096, "dklen": 32, "derived_key_hex": "c5e478d59288c841aa530db6845c4c8d962893a001ce4e11a4963873aa98134a"}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"_comment": "Poly1305 one-time authenticator test vector from RFC 8439 Section 2.5.2. Tag independently verified with a reference pure-Python Poly1305 implementation.",
|
||||
"name": "poly1305",
|
||||
"source": "RFC 8439 Section 2.5.2",
|
||||
"cases": [
|
||||
{
|
||||
"id": "rfc8439_poly1305",
|
||||
"key_hex": "85d6be7857556d337f4452fe42d506a80103808afb0db2fd4abff6af4149f51b",
|
||||
"msg_utf8": "Cryptographic Forum Research Group",
|
||||
"msg_hex": "43727970746f6772617068696320466f72756d2052657365617263682047726f7570",
|
||||
"tag_hex": "a8061dc1305136c6c22b8baf0c0127a9"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,439 @@
|
||||
{
|
||||
"_comment": "AES-GCM-SIV (RFC 8452) test vectors. Verified against cryptography 50.0.1 / OpenSSL. 48 vectors covering pt_len 0..>=16, both AES-128 and AES-256, with/without AAD.",
|
||||
"name": "rfc8452_gcm_siv",
|
||||
"source": "RFC 8452 Appendix C / OpenSSL",
|
||||
"cases": [
|
||||
{
|
||||
"key": "01000000000000000000000000000000",
|
||||
"nonce": "030000000000000000000000",
|
||||
"aad": "",
|
||||
"pt": "",
|
||||
"result": "dc20e2d83f25705bb49e439eca56de25",
|
||||
"pt_len": 0,
|
||||
"aad_len": 0
|
||||
},
|
||||
{
|
||||
"key": "01000000000000000000000000000000",
|
||||
"nonce": "030000000000000000000000",
|
||||
"aad": "",
|
||||
"pt": "0100000000000000",
|
||||
"result": "b5d839330ac7b786578782fff6013b815b287c22493a364c",
|
||||
"pt_len": 8,
|
||||
"aad_len": 0
|
||||
},
|
||||
{
|
||||
"key": "01000000000000000000000000000000",
|
||||
"nonce": "030000000000000000000000",
|
||||
"aad": "",
|
||||
"pt": "010000000000000000000000",
|
||||
"result": "7323ea61d05932260047d942a4978db357391a0bc4fdec8b0d106639",
|
||||
"pt_len": 12,
|
||||
"aad_len": 0
|
||||
},
|
||||
{
|
||||
"key": "01000000000000000000000000000000",
|
||||
"nonce": "030000000000000000000000",
|
||||
"aad": "",
|
||||
"pt": "01000000000000000000000000000000",
|
||||
"result": "743f7c8077ab25f8624e2e948579cf77303aaf90f6fe21199c6068577437a0c4",
|
||||
"pt_len": 16,
|
||||
"aad_len": 0
|
||||
},
|
||||
{
|
||||
"key": "01000000000000000000000000000000",
|
||||
"nonce": "030000000000000000000000",
|
||||
"aad": "",
|
||||
"pt": "0100000000000000000000000000000002000000000000000000000000000000",
|
||||
"result": "84e07e62ba83a6585417245d7ec413a9fe427d6315c09b57ce45f2e3936a94451a8e45dcd4578c667cd86847bf6155ff",
|
||||
"pt_len": 32,
|
||||
"aad_len": 0
|
||||
},
|
||||
{
|
||||
"key": "01000000000000000000000000000000",
|
||||
"nonce": "030000000000000000000000",
|
||||
"aad": "",
|
||||
"pt": "010000000000000000000000000000000200000000000000000000000000000003000000000000000000000000000000",
|
||||
"result": "3fd24ce1f5a67b75bf2351f181a475c7b800a5b4d3dcf70106b1eea82fa1d64df42bf7226122fa92e17a40eeaac1201b5e6e311dbf395d35b0fe39c2714388f8",
|
||||
"pt_len": 48,
|
||||
"aad_len": 0
|
||||
},
|
||||
{
|
||||
"key": "01000000000000000000000000000000",
|
||||
"nonce": "030000000000000000000000",
|
||||
"aad": "",
|
||||
"pt": "01000000000000000000000000000000020000000000000000000000000000000300000000000000000000000000000004000000000000000000000000000000",
|
||||
"result": "2433668f1058190f6d43e360f4f35cd8e475127cfca7028ea8ab5c20f7ab2af02516a2bdcbc08d521be37ff28c152bba36697f25b4cd169c6590d1dd39566d3f8a263dd317aa88d56bdf3936dba75bb8",
|
||||
"pt_len": 64,
|
||||
"aad_len": 0
|
||||
},
|
||||
{
|
||||
"key": "01000000000000000000000000000000",
|
||||
"nonce": "030000000000000000000000",
|
||||
"aad": "01",
|
||||
"pt": "0200000000000000",
|
||||
"result": "1e6daba35669f4273b0a1a2560969cdf790d99759abd1508",
|
||||
"pt_len": 8,
|
||||
"aad_len": 1
|
||||
},
|
||||
{
|
||||
"key": "01000000000000000000000000000000",
|
||||
"nonce": "030000000000000000000000",
|
||||
"aad": "01",
|
||||
"pt": "020000000000000000000000",
|
||||
"result": "296c7889fd99f41917f4462008299c5102745aaa3a0c469fad9e075a",
|
||||
"pt_len": 12,
|
||||
"aad_len": 1
|
||||
},
|
||||
{
|
||||
"key": "01000000000000000000000000000000",
|
||||
"nonce": "030000000000000000000000",
|
||||
"aad": "01",
|
||||
"pt": "02000000000000000000000000000000",
|
||||
"result": "e2b0c5da79a901c1745f700525cb335b8f8936ec039e4e4bb97ebd8c4457441f",
|
||||
"pt_len": 16,
|
||||
"aad_len": 1
|
||||
},
|
||||
{
|
||||
"key": "01000000000000000000000000000000",
|
||||
"nonce": "030000000000000000000000",
|
||||
"aad": "01",
|
||||
"pt": "0200000000000000000000000000000003000000000000000000000000000000",
|
||||
"result": "620048ef3c1e73e57e02bb8562c416a319e73e4caac8e96a1ecb2933145a1d71e6af6a7f87287da059a71684ed3498e1",
|
||||
"pt_len": 32,
|
||||
"aad_len": 1
|
||||
},
|
||||
{
|
||||
"key": "01000000000000000000000000000000",
|
||||
"nonce": "030000000000000000000000",
|
||||
"aad": "01",
|
||||
"pt": "020000000000000000000000000000000300000000000000000000000000000004000000000000000000000000000000",
|
||||
"result": "50c8303ea93925d64090d07bd109dfd9515a5a33431019c17d93465999a8b0053201d723120a8562b838cdff25bf9d1e6a8cc3865f76897c2e4b245cf31c51f2",
|
||||
"pt_len": 48,
|
||||
"aad_len": 1
|
||||
},
|
||||
{
|
||||
"key": "01000000000000000000000000000000",
|
||||
"nonce": "030000000000000000000000",
|
||||
"aad": "01",
|
||||
"pt": "02000000000000000000000000000000030000000000000000000000000000000400000000000000000000000000000005000000000000000000000000000000",
|
||||
"result": "2f5c64059db55ee0fb847ed513003746aca4e61c711b5de2e7a77ffd02da42feec601910d3467bb8b36ebbaebce5fba30d36c95f48a3e7980f0e7ac299332a80cdc46ae475563de037001ef84ae21744",
|
||||
"pt_len": 64,
|
||||
"aad_len": 1
|
||||
},
|
||||
{
|
||||
"key": "01000000000000000000000000000000",
|
||||
"nonce": "030000000000000000000000",
|
||||
"aad": "010000000000000000000000",
|
||||
"pt": "02000000",
|
||||
"result": "a8fe3e8707eb1f84fb28f8cb73de8e99e2f48a14",
|
||||
"pt_len": 4,
|
||||
"aad_len": 12
|
||||
},
|
||||
{
|
||||
"key": "01000000000000000000000000000000",
|
||||
"nonce": "030000000000000000000000",
|
||||
"aad": "010000000000000000000000000000000200",
|
||||
"pt": "0300000000000000000000000000000004000000",
|
||||
"result": "6bb0fecf5ded9b77f902c7d5da236a4391dd029724afc9805e976f451e6d87f6fe106514",
|
||||
"pt_len": 20,
|
||||
"aad_len": 18
|
||||
},
|
||||
{
|
||||
"key": "01000000000000000000000000000000",
|
||||
"nonce": "030000000000000000000000",
|
||||
"aad": "0100000000000000000000000000000002000000",
|
||||
"pt": "030000000000000000000000000000000400",
|
||||
"result": "44d0aaf6fb2f1f34add5e8064e83e12a2adabff9b2ef00fb47920cc72a0c0f13b9fd",
|
||||
"pt_len": 18,
|
||||
"aad_len": 20
|
||||
},
|
||||
{
|
||||
"key": "e66021d5eb8e4f4066d4adb9c33560e4",
|
||||
"nonce": "f46e44bb3da0015c94f70887",
|
||||
"aad": "",
|
||||
"pt": "",
|
||||
"result": "a4194b79071b01a87d65f706e3949578",
|
||||
"pt_len": 0,
|
||||
"aad_len": 0
|
||||
},
|
||||
{
|
||||
"key": "36864200e0eaf5284d884a0e77d31646",
|
||||
"nonce": "bae8e37fc83441b16034566b",
|
||||
"aad": "46bb91c3c5",
|
||||
"pt": "7a806c",
|
||||
"result": "af60eb711bd85bc1e4d3e0a462e074eea428a8",
|
||||
"pt_len": 3,
|
||||
"aad_len": 5
|
||||
},
|
||||
{
|
||||
"key": "aedb64a6c590bc84d1a5e269e4b47801",
|
||||
"nonce": "afc0577e34699b9e671fdd4f",
|
||||
"aad": "fc880c94a95198874296",
|
||||
"pt": "bdc66f146545",
|
||||
"result": "bb93a3e34d3cd6a9c45545cfc11f03ad743dba20f966",
|
||||
"pt_len": 6,
|
||||
"aad_len": 10
|
||||
},
|
||||
{
|
||||
"key": "d5cc1fd161320b6920ce07787f86743b",
|
||||
"nonce": "275d1ab32f6d1f0434d8848c",
|
||||
"aad": "046787f3ea22c127aaf195d1894728",
|
||||
"pt": "1177441f195495860f",
|
||||
"result": "4f37281f7ad12949d01d02fd0cd174c84fc5dae2f60f52fd2b",
|
||||
"pt_len": 9,
|
||||
"aad_len": 15
|
||||
},
|
||||
{
|
||||
"key": "b3fed1473c528b8426a582995929a149",
|
||||
"nonce": "9e9ad8780c8d63d0ab4149c0",
|
||||
"aad": "c9882e5386fd9f92ec489c8fde2be2cf97e74e93",
|
||||
"pt": "9f572c614b4745914474e7c7",
|
||||
"result": "f54673c5ddf710c745641c8bc1dc2f871fb7561da1286e655e24b7b0",
|
||||
"pt_len": 12,
|
||||
"aad_len": 20
|
||||
},
|
||||
{
|
||||
"key": "2d4ed87da44102952ef94b02b805249b",
|
||||
"nonce": "ac80e6f61455bfac8308a2d4",
|
||||
"aad": "2950a70d5a1db2316fd568378da107b52b0da55210cc1c1b0a",
|
||||
"pt": "0d8c8451178082355c9e940fea2f58",
|
||||
"result": "c9ff545e07b88a015f05b274540aa183b3449b9f39552de99dc214a1190b0b",
|
||||
"pt_len": 15,
|
||||
"aad_len": 25
|
||||
},
|
||||
{
|
||||
"key": "bde3b2f204d1e9f8b06bc47f9745b3d1",
|
||||
"nonce": "ae06556fb6aa7890bebc18fe",
|
||||
"aad": "1860f762ebfbd08284e421702de0de18baa9c9596291b08466f37de21c7f",
|
||||
"pt": "6b3db4da3d57aa94842b9803a96e07fb6de7",
|
||||
"result": "6298b296e24e8cc35dce0bed484b7f30d5803e377094f04709f64d7b985310a4db84",
|
||||
"pt_len": 18,
|
||||
"aad_len": 30
|
||||
},
|
||||
{
|
||||
"key": "f901cfe8a69615a93fdf7a98cad48179",
|
||||
"nonce": "6245709fb18853f68d833640",
|
||||
"aad": "7576f7028ec6eb5ea7e298342a94d4b202b370ef9768ec6561c4fe6b7e7296fa859c21",
|
||||
"pt": "e42a3c02c25b64869e146d7b233987bddfc240871d",
|
||||
"result": "391cc328d484a4f46406181bcd62efd9b3ee197d052d15506c84a9edd65e13e9d24a2a6e70",
|
||||
"pt_len": 21,
|
||||
"aad_len": 35
|
||||
},
|
||||
{
|
||||
"key": "0100000000000000000000000000000000000000000000000000000000000000",
|
||||
"nonce": "030000000000000000000000",
|
||||
"aad": "",
|
||||
"pt": "",
|
||||
"result": "07f5f4169bbf55a8400cd47ea6fd400f",
|
||||
"pt_len": 0,
|
||||
"aad_len": 0
|
||||
},
|
||||
{
|
||||
"key": "0100000000000000000000000000000000000000000000000000000000000000",
|
||||
"nonce": "030000000000000000000000",
|
||||
"aad": "",
|
||||
"pt": "0100000000000000",
|
||||
"result": "c2ef328e5c71c83b843122130f7364b761e0b97427e3df28",
|
||||
"pt_len": 8,
|
||||
"aad_len": 0
|
||||
},
|
||||
{
|
||||
"key": "0100000000000000000000000000000000000000000000000000000000000000",
|
||||
"nonce": "030000000000000000000000",
|
||||
"aad": "",
|
||||
"pt": "010000000000000000000000",
|
||||
"result": "9aab2aeb3faa0a34aea8e2b18ca50da9ae6559e48fd10f6e5c9ca17e",
|
||||
"pt_len": 12,
|
||||
"aad_len": 0
|
||||
},
|
||||
{
|
||||
"key": "0100000000000000000000000000000000000000000000000000000000000000",
|
||||
"nonce": "030000000000000000000000",
|
||||
"aad": "",
|
||||
"pt": "01000000000000000000000000000000",
|
||||
"result": "85a01b63025ba19b7fd3ddfc033b3e76c9eac6fa700942702e90862383c6c366",
|
||||
"pt_len": 16,
|
||||
"aad_len": 0
|
||||
},
|
||||
{
|
||||
"key": "0100000000000000000000000000000000000000000000000000000000000000",
|
||||
"nonce": "030000000000000000000000",
|
||||
"aad": "",
|
||||
"pt": "0100000000000000000000000000000002000000000000000000000000000000",
|
||||
"result": "4a6a9db4c8c6549201b9edb53006cba821ec9cf850948a7c86c68ac7539d027fe819e63abcd020b006a976397632eb5d",
|
||||
"pt_len": 32,
|
||||
"aad_len": 0
|
||||
},
|
||||
{
|
||||
"key": "0100000000000000000000000000000000000000000000000000000000000000",
|
||||
"nonce": "030000000000000000000000",
|
||||
"aad": "",
|
||||
"pt": "010000000000000000000000000000000200000000000000000000000000000003000000000000000000000000000000",
|
||||
"result": "c00d121893a9fa603f48ccc1ca3c57ce7499245ea0046db16c53c7c66fe717e39cf6c748837b61f6ee3adcee17534ed5790bc96880a99ba804bd12c0e6a22cc4",
|
||||
"pt_len": 48,
|
||||
"aad_len": 0
|
||||
},
|
||||
{
|
||||
"key": "0100000000000000000000000000000000000000000000000000000000000000",
|
||||
"nonce": "030000000000000000000000",
|
||||
"aad": "",
|
||||
"pt": "01000000000000000000000000000000020000000000000000000000000000000300000000000000000000000000000004000000000000000000000000000000",
|
||||
"result": "c2d5160a1f8683834910acdafc41fbb1632d4a353e8b905ec9a5499ac34f96c7e1049eb080883891a4db8caaa1f99dd004d80487540735234e3744512c6f90ce112864c269fc0d9d88c61fa47e39aa08",
|
||||
"pt_len": 64,
|
||||
"aad_len": 0
|
||||
},
|
||||
{
|
||||
"key": "0100000000000000000000000000000000000000000000000000000000000000",
|
||||
"nonce": "030000000000000000000000",
|
||||
"aad": "01",
|
||||
"pt": "0200000000000000",
|
||||
"result": "1de22967237a813291213f267e3b452f02d01ae33e4ec854",
|
||||
"pt_len": 8,
|
||||
"aad_len": 1
|
||||
},
|
||||
{
|
||||
"key": "0100000000000000000000000000000000000000000000000000000000000000",
|
||||
"nonce": "030000000000000000000000",
|
||||
"aad": "01",
|
||||
"pt": "020000000000000000000000",
|
||||
"result": "163d6f9cc1b346cd453a2e4cc1a4a19ae800941ccdc57cc8413c277f",
|
||||
"pt_len": 12,
|
||||
"aad_len": 1
|
||||
},
|
||||
{
|
||||
"key": "0100000000000000000000000000000000000000000000000000000000000000",
|
||||
"nonce": "030000000000000000000000",
|
||||
"aad": "01",
|
||||
"pt": "02000000000000000000000000000000",
|
||||
"result": "c91545823cc24f17dbb0e9e807d5ec17b292d28ff61189e8e49f3875ef91aff7",
|
||||
"pt_len": 16,
|
||||
"aad_len": 1
|
||||
},
|
||||
{
|
||||
"key": "0100000000000000000000000000000000000000000000000000000000000000",
|
||||
"nonce": "030000000000000000000000",
|
||||
"aad": "01",
|
||||
"pt": "0200000000000000000000000000000003000000000000000000000000000000",
|
||||
"result": "07dad364bfc2b9da89116d7bef6daaaf6f255510aa654f920ac81b94e8bad365aea1bad12702e1965604374aab96dbbc",
|
||||
"pt_len": 32,
|
||||
"aad_len": 1
|
||||
},
|
||||
{
|
||||
"key": "0100000000000000000000000000000000000000000000000000000000000000",
|
||||
"nonce": "030000000000000000000000",
|
||||
"aad": "01",
|
||||
"pt": "020000000000000000000000000000000300000000000000000000000000000004000000000000000000000000000000",
|
||||
"result": "c67a1f0f567a5198aa1fcc8e3f21314336f7f51ca8b1af61feac35a86416fa47fbca3b5f749cdf564527f2314f42fe2503332742b228c647173616cfd44c54eb",
|
||||
"pt_len": 48,
|
||||
"aad_len": 1
|
||||
},
|
||||
{
|
||||
"key": "0100000000000000000000000000000000000000000000000000000000000000",
|
||||
"nonce": "030000000000000000000000",
|
||||
"aad": "01",
|
||||
"pt": "02000000000000000000000000000000030000000000000000000000000000000400000000000000000000000000000005000000000000000000000000000000",
|
||||
"result": "67fd45e126bfb9a79930c43aad2d36967d3f0e4d217c1e551f59727870beefc98cb933a8fce9de887b1e40799988db1fc3f91880ed405b2dd298318858467c895bde0285037c5de81e5b570a049b62a0",
|
||||
"pt_len": 64,
|
||||
"aad_len": 1
|
||||
},
|
||||
{
|
||||
"key": "0100000000000000000000000000000000000000000000000000000000000000",
|
||||
"nonce": "030000000000000000000000",
|
||||
"aad": "010000000000000000000000",
|
||||
"pt": "02000000",
|
||||
"result": "22b3f4cd1835e517741dfddccfa07fa4661b74cf",
|
||||
"pt_len": 4,
|
||||
"aad_len": 12
|
||||
},
|
||||
{
|
||||
"key": "0100000000000000000000000000000000000000000000000000000000000000",
|
||||
"nonce": "030000000000000000000000",
|
||||
"aad": "010000000000000000000000000000000200",
|
||||
"pt": "0300000000000000000000000000000004000000",
|
||||
"result": "43dd0163cdb48f9fe3212bf61b201976067f342bb879ad976d8242acc188ab59cabfe307",
|
||||
"pt_len": 20,
|
||||
"aad_len": 18
|
||||
},
|
||||
{
|
||||
"key": "0100000000000000000000000000000000000000000000000000000000000000",
|
||||
"nonce": "030000000000000000000000",
|
||||
"aad": "0100000000000000000000000000000002000000",
|
||||
"pt": "030000000000000000000000000000000400",
|
||||
"result": "462401724b5ce6588d5a54aae5375513a075cfcdf5042112aa29685c912fc2056543",
|
||||
"pt_len": 18,
|
||||
"aad_len": 20
|
||||
},
|
||||
{
|
||||
"key": "e66021d5eb8e4f4066d4adb9c33560e4f46e44bb3da0015c94f7088736864200",
|
||||
"nonce": "e0eaf5284d884a0e77d31646",
|
||||
"aad": "",
|
||||
"pt": "",
|
||||
"result": "169fbb2fbf389a995f6390af22228a62",
|
||||
"pt_len": 0,
|
||||
"aad_len": 0
|
||||
},
|
||||
{
|
||||
"key": "bae8e37fc83441b16034566b7a806c46bb91c3c5aedb64a6c590bc84d1a5e269",
|
||||
"nonce": "e4b47801afc0577e34699b9e",
|
||||
"aad": "4fbdc66f14",
|
||||
"pt": "671fdd",
|
||||
"result": "0eaccb93da9bb81333aee0c785b240d319719d",
|
||||
"pt_len": 3,
|
||||
"aad_len": 5
|
||||
},
|
||||
{
|
||||
"key": "6545fc880c94a95198874296d5cc1fd161320b6920ce07787f86743b275d1ab3",
|
||||
"nonce": "2f6d1f0434d8848c1177441f",
|
||||
"aad": "6787f3ea22c127aaf195",
|
||||
"pt": "195495860f04",
|
||||
"result": "a254dad4f3f96b62b84dc40c84636a5ec12020ec8c2c",
|
||||
"pt_len": 6,
|
||||
"aad_len": 10
|
||||
},
|
||||
{
|
||||
"key": "d1894728b3fed1473c528b8426a582995929a1499e9ad8780c8d63d0ab4149c0",
|
||||
"nonce": "9f572c614b4745914474e7c7",
|
||||
"aad": "489c8fde2be2cf97e74e932d4ed87d",
|
||||
"pt": "c9882e5386fd9f92ec",
|
||||
"result": "0df9e308678244c44bc0fd3dc6628dfe55ebb0b9fb2295c8c2",
|
||||
"pt_len": 9,
|
||||
"aad_len": 15
|
||||
},
|
||||
{
|
||||
"key": "a44102952ef94b02b805249bac80e6f61455bfac8308a2d40d8c845117808235",
|
||||
"nonce": "5c9e940fea2f582950a70d5a",
|
||||
"aad": "0da55210cc1c1b0abde3b2f204d1e9f8b06bc47f",
|
||||
"pt": "1db2316fd568378da107b52b",
|
||||
"result": "8dbeb9f7255bf5769dd56692404099c2587f64979f21826706d497d5",
|
||||
"pt_len": 12,
|
||||
"aad_len": 20
|
||||
},
|
||||
{
|
||||
"key": "9745b3d1ae06556fb6aa7890bebc18fe6b3db4da3d57aa94842b9803a96e07fb",
|
||||
"nonce": "6de71860f762ebfbd08284e4",
|
||||
"aad": "f37de21c7ff901cfe8a69615a93fdf7a98cad481796245709f",
|
||||
"pt": "21702de0de18baa9c9596291b08466",
|
||||
"result": "793576dfa5c0f88729a7ed3c2f1bffb3080d28f6ebb5d3648ce97bd5ba67fd",
|
||||
"pt_len": 15,
|
||||
"aad_len": 25
|
||||
},
|
||||
{
|
||||
"key": "b18853f68d833640e42a3c02c25b64869e146d7b233987bddfc240871d7576f7",
|
||||
"nonce": "028ec6eb5ea7e298342a94d4",
|
||||
"aad": "9c2159058b1f0fe91433a5bdc20e214eab7fecef4454a10ef0657df21ac7",
|
||||
"pt": "b202b370ef9768ec6561c4fe6b7e7296fa85",
|
||||
"result": "857e16a64915a787637687db4a9519635cdd454fc2a154fea91f8363a39fec7d0a49",
|
||||
"pt_len": 18,
|
||||
"aad_len": 30
|
||||
},
|
||||
{
|
||||
"key": "3c535de192eaed3822a2fbbe2ca9dfc88255e14a661b8aa82cc54236093bbc23",
|
||||
"nonce": "688089e55540db1872504e1c",
|
||||
"aad": "734320ccc9d9bbbb19cb81b2af4ecbc3e72834321f7aa0f70b7282b4f33df23f167541",
|
||||
"pt": "ced532ce4159b035277d4dfbb7db62968b13cd4eec",
|
||||
"result": "626660c26ea6612fb17ad91e8e767639edd6c9faee9d6c7029675b89eaf4ba1ded1a286594",
|
||||
"pt_len": 21,
|
||||
"aad_len": 35
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"_comment": "scrypt test vectors from RFC 7914 Section 12. All three vectors independently verified with Python hashlib.scrypt.",
|
||||
"name": "scrypt",
|
||||
"source": "RFC 7914 Section 12",
|
||||
"cases": [
|
||||
{"id": "scrypt_rfc7914_1", "password_utf8": "", "salt_utf8": "", "N": 16, "r": 1, "p": 1, "dklen": 64, "derived_key_hex": "77d6576238657b203b19ca42c18a0497f16b4844e3074ae8dfdffa3fede21442fcd0069ded0948f8326a753a0fc81f17e8d3e0fb2e0d3628cf35e20c38d18906"},
|
||||
{"id": "scrypt_rfc7914_2", "password_utf8": "password", "salt_utf8": "NaCl", "N": 1024, "r": 8, "p": 16, "dklen": 64, "derived_key_hex": "fdbabe1c9d3472007856e7190d01e9fe7c6ad7cbc8237830e77376634b3731622eaf30d92e22a3886ff109279d9830dac727afb94a83ee6d8360cbdfa2cc0640"},
|
||||
{"id": "scrypt_rfc7914_3", "password_utf8": "pleaseletmein", "salt_utf8": "SodiumChloride", "N": 16384, "r": 8, "p": 1, "dklen": 64, "derived_key_hex": "7023bdcb3afd7348461c06cd81fd38ebfda8fbba904f8e3ea9b543f6545da1f2d5432955613f0fcf62d49705242a9af9e61e85dc0d651e40dfcf017b45575887"}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"_comment": "SHA-2 (FIPS 180-4) standard test vectors. Sources: FIPS 180-4 appendix examples and the classic NIST example message set. All digests independently verified with Python hashlib.",
|
||||
"name": "sha2",
|
||||
"source": "FIPS 180-4 / NIST",
|
||||
"cases": [
|
||||
{"id": "sha256_empty", "algorithm": "sha256", "msg_utf8": "", "digest_hex": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"},
|
||||
{"id": "sha256_abc", "algorithm": "sha256", "msg_utf8": "abc", "digest_hex": "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"},
|
||||
{"id": "sha256_message_digest", "algorithm": "sha256", "msg_utf8": "message digest", "digest_hex": "f7846f55cf23e14eebeab5b4e1550cad5b509e3348fbc4efa3a1413d393cb650"},
|
||||
{"id": "sha256_alpha", "algorithm": "sha256", "msg_utf8": "abcdefghijklmnopqrstuvwxyz", "digest_hex": "71c480df93d6ae2f1efad1447c66c9525e316218cf51fc8d9ed832f2daf18b73"},
|
||||
{"id": "sha256_alnum", "algorithm": "sha256", "msg_utf8": "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", "digest_hex": "db4bfcbd4da0cd85a60c3c37d3fbd8805c77f15fc6b1fdfe614ee0a7c8fdb4c0"},
|
||||
{"id": "sha256_digits80", "algorithm": "sha256", "msg_utf8": "12345678901234567890123456789012345678901234567890123456789012345678901234567890", "digest_hex": "f371bc4a311f2b009eef952dd83ca80e2b60026c8e935592d0f9c308453c813e"},
|
||||
|
||||
{"id": "sha512_empty", "algorithm": "sha512", "msg_utf8": "", "digest_hex": "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e"},
|
||||
{"id": "sha512_abc", "algorithm": "sha512", "msg_utf8": "abc", "digest_hex": "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f"},
|
||||
{"id": "sha512_message_digest", "algorithm": "sha512", "msg_utf8": "message digest", "digest_hex": "107dbf389d9e9f71a3a95f6c055b9251bc5268c2be16d6c13492ea45b0199f3309e16455ab1e96118e8a905d5597b72038ddb372a89826046de66687bb420e7c"},
|
||||
{"id": "sha512_alpha", "algorithm": "sha512", "msg_utf8": "abcdefghijklmnopqrstuvwxyz", "digest_hex": "4dbff86cc2ca1bae1e16468a05cb9881c97f1753bce3619034898faa1aabe429955a1bf8ec483d7421fe3c1646613a59ed5441fb0f321389f77f48a879c7b1f1"},
|
||||
{"id": "sha512_alnum", "algorithm": "sha512", "msg_utf8": "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", "digest_hex": "1e07be23c26a86ea37ea810c8ec7809352515a970e9253c26f536cfc7a9996c45c8370583e0a78fa4a90041d71a4ceab7423f19c71b9d5a3e01249f0bebd5894"},
|
||||
{"id": "sha512_digits80", "algorithm": "sha512", "msg_utf8": "12345678901234567890123456789012345678901234567890123456789012345678901234567890", "digest_hex": "72ec1ef1124a45b047e8b7c75a932195135bb61de24ec0d1914042246e0aec3a2354e093d76f3048b456764346900cb130d2a4fd5dd16abb5e30bcb850dee843"}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
{
|
||||
"_comment": "SHA-3 / SHAKE (FIPS 202) test vectors. SHA3 digests verified against Python hashlib. Sources: FIPS 202 examples.",
|
||||
"name": "sha3_fips202",
|
||||
"source": "FIPS 202 / hashlib",
|
||||
"cases": [
|
||||
{
|
||||
"id": "empty",
|
||||
"msg_utf8": "",
|
||||
"sha3_224": "6b4e03423667dbb73b6e15454f0eb1abd4597f9a1b078e3f5b5a6bc7",
|
||||
"sha3_256": "a7ffc6f8bf1ed76651c14756a061d662f580ff4de43b49fa82d80a4b80f8434a",
|
||||
"sha3_384": "0c63a75b845e4f7d01107d852e4c2485c51a50aaaa94fc61995e71bbee983a2ac3713831264adb47fb6bd1e058d5f004",
|
||||
"sha3_512": "a69f73cca23a9ac5c8b567dc185a756e97c982164fe25859e0d1dcc1475c80a615b2123af1f5f94c11e3e9402c3ac558f500199d95b6d3e301758586281dcd26"
|
||||
},
|
||||
{
|
||||
"id": "abc",
|
||||
"msg_utf8": "abc",
|
||||
"sha3_224": "e642824c3f8cf24ad09234ee7d3c766fc9a3a5168d0c94ad73b46fdf",
|
||||
"sha3_256": "3a985da74fe225b2045c172d6bd390bd855f086e3e9d525b46bfe24511431532",
|
||||
"sha3_384": "ec01498288516fc926459f58e2c6ad8df9b473cb0fc08c2596da7cf0e49be4b298d88cea927ac7f539f1edf228376d25",
|
||||
"sha3_512": "b751850b1a57168a5693cd924b6b096e08f621827444f70d884f5d0240d2712e10e116e9192af3c91a7ec57647e3934057340b4cf408d5a56592f8274eec53f0"
|
||||
},
|
||||
{
|
||||
"id": "msgdigest",
|
||||
"msg_utf8": "message digest",
|
||||
"sha3_224": "18768bb4c48eb7fc88e5ddb17efcf2964abd7798a39d86a4b4a1e4c8",
|
||||
"sha3_256": "edcdb2069366e75243860c18c3a11465eca34bce6143d30c8665cefcfd32bffd",
|
||||
"sha3_384": "d9519709f44af73e2c8e291109a979de3d61dc02bf69def7fbffdfffe662751513f19ad57e17d4b93ba1e484fc1980d5",
|
||||
"sha3_512": "3444e155881fa15511f57726c7d7cfe80302a7433067b29d59a71415ca9dd141ac892d310bc4d78128c98fda839d18d7f0556f2fe7acb3c0cda4bff3a25f5f59"
|
||||
},
|
||||
{
|
||||
"id": "alnum",
|
||||
"msg_utf8": "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
|
||||
"sha3_224": "a67c289b8250a6f437a20137985d605589a8c163d45261b15419556e",
|
||||
"sha3_256": "a79d6a9da47f04a3b9a9323ec9991f2105d4c78a7bc7beeb103855a7a11dfb9f",
|
||||
"sha3_384": "d5b972302f5080d0830e0de7b6b2cf383665a008f4c4f386a61112652c742d20cb45aa51bd4f542fc733e2719e999291",
|
||||
"sha3_512": "d1db17b4745b255e5eb159f66593cc9c143850979fc7a3951796aba80165aab536b46174ce19e3f707f0e5c6487f5f03084bc0ec9461691ef20113e42ad28163"
|
||||
},
|
||||
{
|
||||
"id": "digits80",
|
||||
"msg_utf8": "12345678901234567890123456789012345678901234567890123456789012345678901234567890",
|
||||
"sha3_224": "0526898e185869f91b3e2a76dd72a15dc6940a67c8164a044cd25cc8",
|
||||
"sha3_256": "293e5ce4ce54ee71990ab06e511b7ccd62722b1beb414f5ff65c8274e0f5be1d",
|
||||
"sha3_384": "3c213a17f514638acb3bf17f109f3e24c16f9f14f085b52a2f2b81adc0db83df1a58db2ce013191b8ba72d8fae7e2a5e",
|
||||
"sha3_512": "9524b9a5536b91069526b4f6196b7e9475b4da69e01f0c855797f224cd7335ddb286fd99b9b32ffe33b59ad424cc1744f6eb59137f5fb8601932e8a8af0ae930"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
{
|
||||
"_comment": "SHAKE128/SHAKE256 (FIPS 202) extendable-output vectors, verified against hashlib.",
|
||||
"name": "shake_fips202",
|
||||
"source": "FIPS 202 / hashlib",
|
||||
"cases": [
|
||||
{
|
||||
"id": "empty",
|
||||
"msg_utf8": "",
|
||||
"shake128_32": "7f9c2ba4e88f827d616045507605853ed73b8093f6efbc88eb1a6eacfa66ef26",
|
||||
"shake128_64": "7f9c2ba4e88f827d616045507605853ed73b8093f6efbc88eb1a6eacfa66ef263cb1eea988004b93103cfb0aeefd2a686e01fa4a58e8a3639ca8a1e3f9ae57e2",
|
||||
"shake256_32": "46b9dd2b0ba88d13233b3feb743eeb243fcd52ea62b81b82b50c27646ed5762f",
|
||||
"shake256_64": "46b9dd2b0ba88d13233b3feb743eeb243fcd52ea62b81b82b50c27646ed5762fd75dc4ddd8c0f200cb05019d67b592f6fc821c49479ab48640292eacb3b7c4be"
|
||||
},
|
||||
{
|
||||
"id": "abc",
|
||||
"msg_utf8": "abc",
|
||||
"shake128_32": "5881092dd818bf5cf8a3ddb793fbcba74097d5c526a6d35f97b83351940f2cc8",
|
||||
"shake128_64": "5881092dd818bf5cf8a3ddb793fbcba74097d5c526a6d35f97b83351940f2cc844c50af32acd3f2cdd066568706f509bc1bdde58295dae3f891a9a0fca578378",
|
||||
"shake256_32": "483366601360a8771c6863080cc4114d8db44530f8f1e1ee4f94ea37e78b5739",
|
||||
"shake256_64": "483366601360a8771c6863080cc4114d8db44530f8f1e1ee4f94ea37e78b5739d5a15bef186a5386c75744c0527e1faa9f8726e462a12a4feb06bd8801e751e4"
|
||||
},
|
||||
{
|
||||
"id": "msgdigest",
|
||||
"msg_utf8": "message digest",
|
||||
"shake128_32": "cbef732961b55b4c31396796577df491b6eed61d8949ce967226801e411e53f0",
|
||||
"shake128_64": "cbef732961b55b4c31396796577df491b6eed61d8949ce967226801e411e53f09544c13fe4df40fc8df5f9853e8541d04541f10077d9d44e7493e87f160a0a0d",
|
||||
"shake256_32": "718e224088856840ade4dc73487e15826a07ecb8ed5e2bda526cc1acddb99d00",
|
||||
"shake256_64": "718e224088856840ade4dc73487e15826a07ecb8ed5e2bda526cc1acddb99d006049815844be0c6c29b759db80b7daa684cb46d90f7eef107d24aafcfaf0daca"
|
||||
},
|
||||
{
|
||||
"id": "alnum",
|
||||
"msg_utf8": "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
|
||||
"shake128_32": "54dd201e53249910db3c7d366574fbb64e71fae442a4bac13439f26dd4896883",
|
||||
"shake128_64": "54dd201e53249910db3c7d366574fbb64e71fae442a4bac13439f26dd489688370d012a15586d87e7300beedd9233eea98f916dab266513802502440315bba9e",
|
||||
"shake256_32": "31f19a097c723e91fa59b0998dd8523c2a9e7e13b4025d6b48fcbc328973a108",
|
||||
"shake256_64": "31f19a097c723e91fa59b0998dd8523c2a9e7e13b4025d6b48fcbc328973a10878cfbeb3810d882fdb6a06e87f3ea52cf826ca5522316fb645b708acbe43b2cb"
|
||||
},
|
||||
{
|
||||
"id": "digits80",
|
||||
"msg_utf8": "12345678901234567890123456789012345678901234567890123456789012345678901234567890",
|
||||
"shake128_32": "7bf451c92fdc77b9771e6c9056445894ee867f00c2b70d3af0d196a0cf6b28e1",
|
||||
"shake128_64": "7bf451c92fdc77b9771e6c9056445894ee867f00c2b70d3af0d196a0cf6b28e12ced960537f22a0e90334103675844993c4fd713646800bd899951e56f0645fc",
|
||||
"shake256_32": "24c508adefdf5e3f2596e8b5a888fe10eb7b5b22e1f35d858e6eff3025c4cc18",
|
||||
"shake256_64": "24c508adefdf5e3f2596e8b5a888fe10eb7b5b22e1f35d858e6eff3025c4cc18a3c9ace51ddd243d08c8c70cf68e91d170603dc3e2a31c6ca89f20c4a595a265"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
{
|
||||
"_comment": "X25519 test vectors from RFC 7748: Section 5.2 (scalar multiplication example) and Section 6.1 (Diffie-Hellman key exchange). All values independently verified with the cryptography library.",
|
||||
"name": "x25519_rfc7748",
|
||||
"source": "RFC 7748",
|
||||
"cases": [
|
||||
{
|
||||
"id": "x25519_scalar_mult",
|
||||
"type": "x25519_scalarmult",
|
||||
"scalar_hex": "a546e36bf0527c9d3b16154b82465edd62144c0ac1fc5a18506a2244ba449ac4",
|
||||
"u_hex": "e6db6867583030db3594c1a424b15f7c726624ec26b3353b10a903a6d0ab1c4c",
|
||||
"output_hex": "c3da55379de9c6908e94ea4df28d084f32eccf03491c71f754b4075577a28552"
|
||||
},
|
||||
{
|
||||
"id": "x25519_alice_public",
|
||||
"type": "x25519_base",
|
||||
"scalar_hex": "77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a",
|
||||
"output_hex": "8520f0098930a754748b7ddcb43ef75a0dbf3a0d26381af4eba4a98eaa9b4e6a"
|
||||
},
|
||||
{
|
||||
"id": "x25519_bob_public",
|
||||
"type": "x25519_base",
|
||||
"scalar_hex": "5dab087e624a8a4b79e17f8b83800ee66f3bb1292618b6fd1c2f8b27ff88e0eb",
|
||||
"output_hex": "de9edb7d7b7dc1b4d35b61c2ece435373f8343c85b78674dadfc7e146f882b4f"
|
||||
},
|
||||
{
|
||||
"id": "x25519_shared_secret",
|
||||
"type": "x25519_shared",
|
||||
"alice_priv_hex": "77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a",
|
||||
"alice_pub_hex": "8520f0098930a754748b7ddcb43ef75a0dbf3a0d26381af4eba4a98eaa9b4e6a",
|
||||
"bob_priv_hex": "5dab087e624a8a4b79e17f8b83800ee66f3bb1292618b6fd1c2f8b27ff88e0eb",
|
||||
"bob_pub_hex": "de9edb7d7b7dc1b4d35b61c2ece435373f8343c85b78674dadfc7e146f882b4f",
|
||||
"shared_hex": "4a5d9d5ba4ce2de1728e3bf480350f25e07e21c947d19e3376f09b3c1e161742"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""purepycrypto.x25519
|
||||
========================================
|
||||
purepycrypto - Pure-Python cryptography library (zero dependencies)
|
||||
X25519 (Curve25519 ECDH, RFC 7748), Montgomery ladder + constant-time cswap.
|
||||
|
||||
Unified error system
|
||||
------------
|
||||
This module follows the unified purepycrypto error contract (see ``purepycrypto._ppyc_error``):
|
||||
* **Non-fatal errors** (invalid argument lengths, etc.) -> return a 3-tuple
|
||||
``(error_code, error_message, suggestion)``;
|
||||
* On success -> return the normal value (``bytes`` / ``(bytes, bool)`` / ``(bytes, bytes)``).
|
||||
* For a low-order point (a peer public key that yields an all-zero shared secret), the return value ``(shared, is_zero)``
|
||||
is **kept**; its semantics correspond to ``PPYC_ERR_INVALID_POINT`` (the caller should use ``is_zero`` and
|
||||
reject that shared secret to avoid invalid-curve attacks).
|
||||
|
||||
Callers use ``purepycrypto._ppyc_error.is_err(result)`` to tell whether an error tuple was returned.
|
||||
"""
|
||||
|
||||
import os
|
||||
from typing import Tuple, Union
|
||||
|
||||
from ._ppyc_error import (
|
||||
PPYC_ERR,
|
||||
err, is_err, ok,
|
||||
PPYC_ERR_INVALID_LENGTH,
|
||||
PPYC_ERR_INVALID_POINT,
|
||||
PPYCResult,
|
||||
)
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 11. X25519
|
||||
# ============================================================
|
||||
|
||||
P25519 = 2 ** 255 - 19
|
||||
A24_25519 = 121665
|
||||
|
||||
|
||||
def _cswap(swap: int, x2: int, x3: int) -> Tuple[int, int]:
|
||||
mask = -swap
|
||||
dummy = mask & (x2 ^ x3)
|
||||
return x2 ^ dummy, x3 ^ dummy
|
||||
|
||||
|
||||
def x25519(k_bytes: bytes, u_bytes: bytes) -> Union[bytes, PPYCResult]:
|
||||
"""X25519 scalar multiplication (RFC 7748 section 5).
|
||||
|
||||
Runs the Montgomery ladder on a 32-byte scalar k and a 32-byte u coordinate and returns the u coordinate
|
||||
``k*u``.
|
||||
|
||||
Returns
|
||||
----
|
||||
bytes
|
||||
32-byte result (little-endian).
|
||||
(str, str, str)
|
||||
A non-fatal error tuple; ``PPYC_ERR_INVALID_LENGTH`` (the length of k or u is not 32 bytes).
|
||||
"""
|
||||
if len(k_bytes) != 32 or len(u_bytes) != 32:
|
||||
return err(PPYC_ERR_INVALID_LENGTH,
|
||||
f"X25519 k and u must each be 32 bytes (got k={len(k_bytes)}, u={len(u_bytes)})",
|
||||
"pass a 32-byte scalar and u coordinate")
|
||||
|
||||
k_list = bytearray(k_bytes)
|
||||
k_list[0] &= 248
|
||||
k_list[31] &= 127
|
||||
k_list[31] |= 64
|
||||
k = int.from_bytes(k_list, "little")
|
||||
|
||||
u_list = bytearray(u_bytes)
|
||||
u_list[31] &= 0x7F
|
||||
u = int.from_bytes(u_list, "little")
|
||||
u %= P25519
|
||||
|
||||
x1 = u
|
||||
x2, z2 = 1, 0
|
||||
x3, z3 = u, 1
|
||||
swap = 0
|
||||
|
||||
for t in range(254, -1, -1):
|
||||
kt = (k >> t) & 1
|
||||
swap ^= kt
|
||||
x2, x3 = _cswap(swap, x2, x3)
|
||||
z2, z3 = _cswap(swap, z2, z3)
|
||||
swap = kt
|
||||
|
||||
A = (x2 + z2) % P25519
|
||||
AA = A * A % P25519
|
||||
B = (x2 - z2) % P25519
|
||||
BB = B * B % P25519
|
||||
E = (AA - BB) % P25519
|
||||
C = (x3 + z3) % P25519
|
||||
D = (x3 - z3) % P25519
|
||||
DA = D * A % P25519
|
||||
CB = C * B % P25519
|
||||
|
||||
x3 = (DA + CB) ** 2 % P25519
|
||||
z3 = x1 * (DA - CB) ** 2 % P25519
|
||||
x2 = AA * BB % P25519
|
||||
z2 = E * (AA + A24_25519 * E) % P25519
|
||||
|
||||
x2, x3 = _cswap(swap, x2, x3)
|
||||
z2, z3 = _cswap(swap, z2, z3)
|
||||
|
||||
result = x2 * pow(z2, P25519 - 2, P25519) % P25519
|
||||
return result.to_bytes(32, "little")
|
||||
|
||||
|
||||
def x25519_base(k_bytes: bytes) -> Union[bytes, PPYCResult]:
|
||||
"""X25519 base-point scalar multiplication k*9 (used to derive a public key).
|
||||
|
||||
Returns
|
||||
----
|
||||
bytes
|
||||
32-byte public key.
|
||||
(str, str, str)
|
||||
A non-fatal error tuple (propagates the ``x25519`` error); ``PPYC_ERR_INVALID_LENGTH``.
|
||||
"""
|
||||
return x25519(k_bytes, (9).to_bytes(32, "little"))
|
||||
|
||||
|
||||
def x25519_shared(priv_bytes: bytes, peer_pub_bytes: bytes) -> Union[Tuple[bytes, bool], PPYCResult]:
|
||||
"""X25519 ECDH shared secret computation with low-order point detection.
|
||||
|
||||
Returns
|
||||
----
|
||||
(bytes, bool)
|
||||
(32-byte shared secret, whether it is all zero). All zero means the peer u is a low-order point
|
||||
(invalid-curve attack risk); its semantics correspond to ``PPYC_ERR_INVALID_POINT`` -- for compatibility
|
||||
with the existing API this function keeps that return form, but **the caller should use the second item to decide whether to reject** the shared secret.
|
||||
(str, str, str)
|
||||
A non-fatal error tuple; ``PPYC_ERR_INVALID_LENGTH`` (invalid private key or peer public key length).
|
||||
"""
|
||||
shared = x25519(priv_bytes, peer_pub_bytes)
|
||||
if is_err(shared):
|
||||
return shared
|
||||
acc = 0
|
||||
for b in shared:
|
||||
acc |= b
|
||||
return shared, (acc == 0)
|
||||
|
||||
|
||||
def x25519_generate_keypair() -> Tuple[bytes, bytes]:
|
||||
"""Generate an X25519 key pair.
|
||||
|
||||
Returns
|
||||
----
|
||||
(bytes, bytes)
|
||||
(32-byte private key, 32-byte public key).
|
||||
"""
|
||||
priv = os.urandom(32)
|
||||
pub = x25519_base(priv)
|
||||
if is_err(pub):
|
||||
raise PPYC_ERR(pub[0], pub[1], pub[2]) # a 32-byte random private key should not fail: internal invariant
|
||||
return priv, pub
|
||||
@@ -0,0 +1,86 @@
|
||||
[build-system]
|
||||
requires = ["setuptools>=61.0", "wheel"]
|
||||
build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "purepycrypto"
|
||||
version = "3.2.0"
|
||||
description = "Pure-Python cryptography library (zero dependencies): SHA-2/SHA-3/BLAKE2b, AES-GCM(-SIV), ChaCha20-Poly1305, X25519/Ed25519, RSA-OAEP/PSS, with built-in TUI and command-line tool"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.7"
|
||||
license = { text = "MIT" }
|
||||
authors = [
|
||||
{ name = "Dvs(DvsXT)", email = "dvs6666@163.com" },
|
||||
]
|
||||
keywords = [
|
||||
"cryptography", "crypto", "pure-python", "aes", "aes-gcm", "aes-gcm-siv",
|
||||
"chacha20", "poly1305", "x25519", "ed25519", "rsa", "oaep", "pss",
|
||||
"sha256", "sha512", "sha3", "keccak", "shake", "blake2b",
|
||||
"argon2", "scrypt", "hkdf", "pbkdf2", "hmac", "cli", "tui",
|
||||
]
|
||||
classifiers = [
|
||||
"Development Status :: 5 - Production/Stable",
|
||||
"Intended Audience :: Developers",
|
||||
"License :: OSI Approved :: MIT License",
|
||||
"Operating System :: OS Independent",
|
||||
"Environment :: Console",
|
||||
"Programming Language :: Python :: 3",
|
||||
"Programming Language :: Python :: 3.7",
|
||||
"Programming Language :: Python :: 3.8",
|
||||
"Programming Language :: Python :: 3.9",
|
||||
"Programming Language :: Python :: 3.10",
|
||||
"Programming Language :: Python :: 3.11",
|
||||
"Programming Language :: Python :: 3.12",
|
||||
"Programming Language :: Python :: 3.13",
|
||||
"Topic :: Security :: Cryptography",
|
||||
"Topic :: Software Development :: Libraries :: Python Modules",
|
||||
]
|
||||
dependencies = []
|
||||
|
||||
[project.optional-dependencies]
|
||||
test = ["pytest>=7.0"]
|
||||
dev = ["pytest>=7.0", "build", "twine"]
|
||||
# Cross-verification / comparison (optional; test-only, not a runtime dependency)
|
||||
compare = ["pycryptodome", "cryptography>=45"]
|
||||
|
||||
[project.urls]
|
||||
Homepage = "https://apds.top"
|
||||
Documentation = "https://apds.top"
|
||||
Source = "https://apds.top"
|
||||
|
||||
[project.scripts]
|
||||
# ----------------------------------------------------------------------
|
||||
# Executable command (installed into Python's Scripts directory)
|
||||
# ----------------------------------------------------------------------
|
||||
# Register only ONE command, `purepycrypto`, targeting `purepycrypto:main`:
|
||||
# * no arguments -> launch the interactive TUI
|
||||
# * with arguments -> command-line mode (hash/aes/rsa/x25519/kdf/...)
|
||||
#
|
||||
# After installation it can be used directly:
|
||||
# purepycrypto # TUI
|
||||
# purepycrypto hash --text abc --hex # command line
|
||||
# purepycrypto --help # help
|
||||
#
|
||||
# As a library: import purepycrypto
|
||||
# Without installation, the equivalent is: python -m purepycrypto [subcommand]
|
||||
purepycrypto = "purepycrypto:main"
|
||||
|
||||
[tool.setuptools]
|
||||
packages = [
|
||||
"purepycrypto",
|
||||
"purepycrypto.tests",
|
||||
"purepycrypto.examples",
|
||||
"purepycrypto.scripts",
|
||||
"purepycrypto.single",
|
||||
]
|
||||
|
||||
[tool.setuptools.package-data]
|
||||
"purepycrypto" = ["py.typed"]
|
||||
"purepycrypto.tests" = ["vectors/*.json"]
|
||||
# Single-file bundle (if generated)
|
||||
"purepycrypto.single" = ["*.py"]
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
testpaths = ["purepycrypto/tests"]
|
||||
python_files = ["test_*.py"]
|
||||
addopts = "-v --tb=short"
|
||||
@@ -0,0 +1,154 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
purepycrypto — setup.py (legacy setuptools entry point)
|
||||
|
||||
Modern usage prefers pyproject.toml:
|
||||
pip install .
|
||||
pip install -e .
|
||||
python -m build
|
||||
|
||||
======================================================================
|
||||
Three usage modes provided after installation (important)
|
||||
======================================================================
|
||||
After installing this package, an executable command is created in the
|
||||
**Python Scripts directory**:
|
||||
|
||||
<Python>/Scripts/purepycrypto (Windows: purepycrypto.exe)
|
||||
|
||||
The command is registered via ``entry_points.console_scripts`` and points to
|
||||
``purepycrypto:main``; ``main()`` dispatches automatically based on whether
|
||||
arguments are given:
|
||||
|
||||
1) purepycrypto # no arguments -> launch [interactive TUI]
|
||||
2) purepycrypto hash --text abc --hex # with arguments -> [command-line mode]
|
||||
3) purepycrypto --help # show command-line help
|
||||
4) purepycrypto version / selftest # version / self-test
|
||||
|
||||
It can also be used as a library:
|
||||
|
||||
import purepycrypto
|
||||
purepycrypto.sha256(b"abc")
|
||||
|
||||
And the equivalent without installation:
|
||||
|
||||
python -m purepycrypto # TUI
|
||||
python -m purepycrypto hash --text abc --hex # command line
|
||||
|
||||
That is: **one single command — no arguments for the TUI, arguments for the command line**
|
||||
(no separate -args command required).
|
||||
|
||||
======================================================================
|
||||
Where CLI / TUI are implemented (for packaging and maintenance reference)
|
||||
======================================================================
|
||||
purepycrypto/cli.py TUI implementation (menus, self-test, CN/EN language switch)
|
||||
purepycrypto/cli_args.py command-line mode implementation (argparse subcommands)
|
||||
purepycrypto/__init__.py unified entry main() / run_tui() / run_cli()
|
||||
purepycrypto/__main__.py python -m purepycrypto entry point
|
||||
purepycrypto/single/ single-file bundle artifact (build_single.py --mode one)
|
||||
|
||||
Build the single file:
|
||||
python purepycrypto/scripts/build_single.py --mode one
|
||||
# generates purepycrypto/single/purepycrypto.py (no arguments = TUI, arguments = command line)
|
||||
======================================================================
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
|
||||
from setuptools import setup, find_packages
|
||||
|
||||
VERSION = "3.2.0"
|
||||
HERE = os.path.abspath(os.path.dirname(__file__))
|
||||
|
||||
|
||||
def _read(rel, fallback=""):
|
||||
try:
|
||||
with open(os.path.join(HERE, rel), "r", encoding="utf-8") as f:
|
||||
return f.read()
|
||||
except OSError:
|
||||
return fallback
|
||||
|
||||
|
||||
def write_version_file():
|
||||
"""Write the version into purepycrypto/_version.py (keeps the runtime and packaged versions in sync)."""
|
||||
path = os.path.join(HERE, "purepycrypto", "_version.py")
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
with open(path, "w", encoding="utf-8") as f:
|
||||
f.write('__version__ = "%s"\n' % VERSION)
|
||||
|
||||
|
||||
write_version_file()
|
||||
|
||||
long_description = _read("README.md", "purepycrypto - pure Python cryptography library")
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# console_scripts entry point (installed into the Python Scripts directory)
|
||||
# ----------------------------------------------------------------------
|
||||
# Notes:
|
||||
# * Register only ONE command, `purepycrypto`, to avoid command sprawl;
|
||||
# * The target is `purepycrypto:main`, whose behavior is:
|
||||
# no arguments -> TUI
|
||||
# with arguments -> command-line mode
|
||||
# * After installation it can therefore be used directly:
|
||||
# purepycrypto (TUI)
|
||||
# purepycrypto hash --help (command line)
|
||||
CONSOLE_SCRIPTS = [
|
||||
"purepycrypto = purepycrypto:main",
|
||||
]
|
||||
|
||||
setup(
|
||||
name="purepycrypto",
|
||||
version=VERSION,
|
||||
description=("Pure-Python cryptography library (zero dependencies): "
|
||||
"SHA-2/SHA-3/BLAKE2b, AES-GCM(-SIV), ChaCha20-Poly1305, "
|
||||
"X25519/Ed25519, RSA-OAEP/PSS, with built-in TUI and command-line tool"),
|
||||
long_description=long_description,
|
||||
long_description_content_type="text/markdown",
|
||||
author="Dvs(DvsXT)",
|
||||
author_email="dvs6666@163.com",
|
||||
url="https://apds.top",
|
||||
license="MIT",
|
||||
packages=find_packages(include=[
|
||||
"purepycrypto", "purepycrypto.*",
|
||||
]),
|
||||
python_requires=">=3.7",
|
||||
install_requires=[],
|
||||
extras_require={
|
||||
"test": ["pytest>=7.0"],
|
||||
"dev": ["pytest>=7.0", "build", "twine"],
|
||||
"compare": ["pycryptodome", "cryptography>=45"],
|
||||
},
|
||||
# ---- key: register the executable command (no arguments = TUI, arguments = CLI) ----
|
||||
entry_points={
|
||||
"console_scripts": CONSOLE_SCRIPTS,
|
||||
},
|
||||
include_package_data=True,
|
||||
package_data={
|
||||
"purepycrypto": ["py.typed"],
|
||||
"purepycrypto.tests": ["vectors/*.json"],
|
||||
# Single-file bundle (if generated)
|
||||
"purepycrypto.single": ["*.py"],
|
||||
},
|
||||
zip_safe=False,
|
||||
classifiers=[
|
||||
"Development Status :: 5 - Production/Stable",
|
||||
"Intended Audience :: Developers",
|
||||
"License :: OSI Approved :: MIT License",
|
||||
"Operating System :: OS Independent",
|
||||
"Environment :: Console",
|
||||
"Programming Language :: Python :: 3",
|
||||
"Programming Language :: Python :: 3.7",
|
||||
"Programming Language :: Python :: 3.8",
|
||||
"Programming Language :: Python :: 3.9",
|
||||
"Programming Language :: Python :: 3.10",
|
||||
"Programming Language :: Python :: 3.11",
|
||||
"Programming Language :: Python :: 3.12",
|
||||
"Programming Language :: Python :: 3.13",
|
||||
"Topic :: Security :: Cryptography",
|
||||
"Topic :: Software Development :: Libraries :: Python Modules",
|
||||
],
|
||||
keywords=("cryptography crypto pure-python aes aes-gcm aes-gcm-siv "
|
||||
"chacha20 poly1305 x25519 ed25519 rsa oaep pss "
|
||||
"sha256 sha512 sha3 keccak shake blake2b argon2 scrypt hkdf pbkdf2 hmac "
|
||||
"cli tui"),
|
||||
)
|
||||
Reference in New Issue
Block a user