Files
purepycrypto/docs/quickstart.md
T
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

467 lines
15 KiB
Markdown
Raw 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.
# 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.