Files
dvs 0d69391aa9 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
2026-09-27 09:40:12 +08:00

455 lines
16 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 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.*