- 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
52 KiB
API Reference
This file is the complete API reference for purepycrypto v3.2.0. The v1.0 public interfaces can be imported directly from the top-level package:
from purepycrypto import sha256, AES, rsa_keygen
SHA-3 / SHAKE, Ed25519, and AES-GCM-SIV can be imported both from their own submodules (e.g.
from purepycrypto.sha3 import sha3_256) and from the top-level exports, see §11, §12, §13.⚠️ As of v3.2.0 the library uses a unified error system: expected failures return a 3-tuple instead of raising, see §0.
The following sections are organized by module; each function gives its signature, parameter table, return value, example, and notes.
For an overview and tutorials, see ../README.md and quickstart.md.
Table of Contents
- 0. Unified Error System (New in v3.2.0)
- Module Overview
- 1. common — Basic Utilities
- 2. hash — Hashing
- 3. kdf — Key Derivation and Message Authentication
- 4. aes — AES Symmetric Encryption
- 5. chacha — ChaCha20 / Poly1305 / AEAD
- 6. x25519 — X25519 Key Exchange
- 7. rsa — RSA Public-Key Cryptography
- 8. der — ASN.1 DER / PEM Serialization
- 9. parallel — Multiprocessing Acceleration
- 10. Command-Line Interface
- 11. sha3 — SHA-3 / Keccak / SHAKE
- 12. ed25519 — Ed25519 Digital Signatures
- 13. aes_gcm_siv — AES-GCM-SIV
- 14. Exceptions and the Error System
- 15. Top-Level Export List
- 16. kdf2 — Hardened Key Derivation (New in v3.2.0)
- 17. encoding — Encoding (New in v3.2.0)
- 18. rand — CSPRNG Utilities (New in v3.2.0)
0. Unified Error System (New in v3.2.0)
As of v3.2.0, purepycrypto uses a unified error system library-wide; the authoritative reference is errors.md.
| 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 |
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)
| Helper / Name | Description |
|---|---|
PPYC_ERR(code, message, suggestion="") |
fatal-error exception (PPYCError is an alias), with code / message / suggestion attributes and as_tuple() |
CryptoError / DecryptionError / Ed25519Error |
legacy exception names (subclasses of PPYC_ERR; default codes are PPYC_ERR_INTERNAL / PPYC_ERR_AUTH_FAILED / PPYC_ERR_INVALID_ARG) |
err(code, message, suggestion="") |
construct a non-fatal 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) / is_err(result) |
determine whether the return value is a success / an error tuple |
raise_ppyc(code, message, suggestion="") |
convenience for raising PPYC_ERR |
PPYCResult |
type alias Tuple[Optional[str], Optional[str], Optional[str]] |
ALL_ERROR_CODES |
all 41 error code constants (tuple); a single constant can be imported via from purepycrypto import PPYC_ERR_xxx |
Caller check:
result = some_api(...)
if is_err(result):
code, msg, hint = result
...
else:
value = result
Module Overview
| Module | Responsibility | Key public interfaces |
|---|---|---|
_ppyc_error |
Unified error system (v3.2.0): exceptions, error codes, tuple helpers | PPYC_ERR, err, ok, is_ok, is_err, OK_TUPLE, ALL_ERROR_CODES |
common |
constant-time comparison, secure random, padding, mask constants | rand_bytes, rand_int, _consttime_eq |
hash |
SHA-256 / SHA-512 / BLAKE2b | sha256, sha512, blake2b |
sha3 |
SHA-3 / Keccak / SHAKE / HMAC-SHA3 | sha3_256, shake128, hmac_sha3_256 |
kdf |
HMAC / PBKDF2 / HKDF / scrypt / Argon2id | hmac_sha256, pbkdf2_hmac, hkdf, scrypt, argon2id |
aes |
AES block cipher and operation modes | AES |
aes_gcm_siv |
AES-GCM-SIV (nonce-misuse resistant AEAD) | aes_gcm_siv_encrypt, aes128_gcm_siv_encrypt, polyval |
chacha |
ChaCha20-Poly1305 / XChaCha20-Poly1305 / Poly1305 | chacha20poly1305_encrypt, xchacha20poly1305_encrypt, poly1305_mac |
x25519 |
X25519 key exchange | x25519, x25519_base, x25519_shared, x25519_generate_keypair |
rsa |
RSA key generation / OAEP / PSS | rsa_keygen, rsa_oaep_encrypt, rsa_pss_sign, RSAPublicKey, RSAPrivateKey |
ed25519 |
Ed25519 digital signatures | ed25519_keygen, ed25519_sign, ed25519_verify |
der |
PKCS#1 / PKCS#8 / SPKI / PEM | private_key_to_pem, public_key_to_pem, parse_private_pem |
parallel |
process-pool reuse + SharedMemory | _HAS_MP (capability probe), internal process pool |
cli |
interactive TUI (CN/EN bilingual) | python -m purepycrypto (no arguments) |
cli_args |
command-line mode | purepycrypto <subcommand> (see cli.md) |
1. common — Basic Utilities
The module purepycrypto.common provides low-level utilities and exception types.
1.1 rand_bytes(n)
rand_bytes(n: int) -> bytes
| Parameter | Type | Description |
|---|---|---|
n |
int |
number of random bytes to generate |
Return value: bytes, n bytes of cryptographically secure random data.
Example
from purepycrypto import rand_bytes
salt = rand_bytes(16)
print(len(salt)) # 16
Notes: internally calls os.urandom(n) directly (the OS CSPRNG), with no seedable state.
1.2 rand_int(a, b)
rand_int(a: int, b: int) -> int
| Parameter | Type | Description |
|---|---|---|
a |
int |
lower bound (inclusive) |
b |
int |
upper bound (inclusive) |
Return value: int, a uniformly distributed random integer in [a, b].
Example
from purepycrypto import rand_int
x = rand_int(1, 6) # simulate a die
Notes: when a > b it returns an error tuple (PPYC_ERR_INVALID_ARG); internally uses rejection sampling to avoid modulo bias.
1.3 Constant-Time Comparison (internal utilities)
| Function | Signature | Description |
|---|---|---|
_consttime_eq |
_consttime_eq(a: bytes, b: bytes) -> bool |
constant-time comparison of two byte strings |
_consttime_int_eq |
_consttime_int_eq(a: int, b: int, bits: int) -> bool |
constant-time comparison of two integers (expanded over bits bits) |
_consttime_select |
_consttime_select(cond: int, a: int, b: int, bits: int) -> int |
constant-time bitwise selection (a if cond is nonzero, otherwise b) |
Notes: names beginning with _ are library-internal functions used by sensitive paths such as the GCM Tag, Poly1305 Tag, and X25519; ordinary users do not need to call them directly.
1.4 Padding Utilities (internal)
| Function | Signature | Description |
|---|---|---|
_pad16 |
_pad16(data: bytes) -> bytes |
pad with 0x00 to a multiple of 16 |
_pad_pkcs7 |
_pad_pkcs7(data: bytes, bs: int = 16) -> bytes |
PKCS#7 padding |
_unpad_pkcs7 |
_unpad_pkcs7(data: bytes) -> bytes |
remove PKCS#7 padding (invalid padding returns an error tuple PPYC_ERR_INVALID_PADDING) |
1.5 Constants
| Name | Value | Description |
|---|---|---|
MASK32 |
0xFFFFFFFF |
32-bit mask |
MASK64 |
0xFFFFFFFFFFFFFFFF |
64-bit mask |
MASK128 |
(1 << 128) - 1 |
128-bit mask |
POLY1305_P |
(1 << 130) - 5 |
Poly1305 prime 2^130 - 5 |
GHASH_R |
0xE1000000000000000000000000000000 |
GCM GHASH reduction constant |
R_CONST |
same as GHASH_R |
alias |
2. hash — Hashing
2.1 sha256
sha256(message: bytes) -> bytes
| Parameter | Type | Description |
|---|---|---|
message |
bytes |
data to hash |
Return value: bytes, a 32-byte digest (FIPS 180-4).
Example
from purepycrypto import sha256
assert sha256(b"abc").hex() == (
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
)
2.2 sha512
sha512(message: bytes) -> bytes
| Parameter | Type | Description |
|---|---|---|
message |
bytes |
data to hash |
Return value: bytes, a 64-byte digest (FIPS 180-4).
Example
from purepycrypto import sha512
assert len(sha512(b"abc")) == 64
2.3 blake2b
blake2b(data: bytes, digest_size: int = 64) -> bytes
| Parameter | Type | Default | Description |
|---|---|---|---|
data |
bytes |
— | data to hash |
digest_size |
int |
64 |
digest length (1–64 bytes) |
Return value: bytes, a digest of length digest_size (RFC 7693).
Example
from purepycrypto import blake2b
print(len(blake2b(b"abc"))) # 64
print(len(blake2b(b"abc", 32))) # 32
Notes: this library's BLAKE2b is also used as the underlying hash for Argon2id (H′ and H0 computation). When digest_size is outside 1–64 it returns an error tuple (PPYC_ERR_INVALID_ARG) instead of raising.
v1.1 adds SHA-3 / Keccak / SHAKE, see §11.
3. kdf — Key Derivation and Message Authentication
3.1 hmac_sha256
hmac_sha256(key: bytes, message: bytes) -> bytes
| Parameter | Type | Description |
|---|---|---|
key |
bytes |
key (any length; if longer than 64 bytes it is first compressed with SHA-256) |
message |
bytes |
message |
Return value: bytes, a 32-byte HMAC value (RFC 2104).
Example
from purepycrypto import hmac_sha256
key = b"\x0b" * 20
mac = hmac_sha256(key, b"Hi There")
assert mac.hex() == "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7"
3.2 hmac_sha512
hmac_sha512(key: bytes, message: bytes) -> bytes
As described for hmac_sha256, but returns a 64-byte HMAC value with a 128-byte block size.
3.3 pbkdf2_hmac
pbkdf2_hmac(password: bytes, salt: bytes, iterations: int,
dklen: int, hash_name: str = "sha256") -> bytes
| Parameter | Type | Default | Description |
|---|---|---|---|
password |
bytes |
— | password |
salt |
bytes |
— | salt (recommended ≥ 16 bytes, unique per password) |
iterations |
int |
— | iteration count, must be ≥ 1 |
dklen |
int |
— | derived key length (bytes), must be ≥ 1 |
hash_name |
str |
"sha256" |
underlying hash, "sha256" or "sha512" |
Return value: bytes, a derived key of length dklen (RFC 8018).
Example
from purepycrypto import pbkdf2_hmac
dk = pbkdf2_hmac(b"password", b"salt", iterations=1, dklen=32)
assert dk.hex() == "120fb6cffcf8b32c43e7225256c4f837a86548c92ccc35480805987cb70be17b"
Notes: when hash_name is neither "sha256" nor "sha512" it returns an error tuple (PPYC_ERR_INVALID_ALGO); iterations < 1 returns PPYC_ERR_INVALID_KDF_PARAM.
3.4 hkdf_extract
hkdf_extract(salt: bytes, ikm: bytes, hash_name: str = "sha256") -> bytes
| Parameter | Type | Default | Description |
|---|---|---|---|
salt |
bytes |
— | salt (may be empty b"") |
ikm |
bytes |
— | input keying material |
hash_name |
str |
"sha256" |
"sha256" or "sha512" |
Return value: bytes, the pseudorandom key PRK (HKDF-Extract, RFC 5869).
3.5 hkdf_expand
hkdf_expand(prk: bytes, info: bytes, length: int, hash_name: str = "sha256") -> bytes
| Parameter | Type | Default | Description |
|---|---|---|---|
prk |
bytes |
— | the PRK obtained from hkdf_extract |
info |
bytes |
— | context/purpose information (to distinguish different subkeys) |
length |
int |
— | output length (bytes) |
hash_name |
str |
"sha256" |
"sha256" or "sha512" |
Return value: bytes, the output keying material OKM of length length (HKDF-Expand, RFC 5869).
3.6 hkdf
hkdf(ikm: bytes, salt: bytes = b"", info: bytes = b"",
length: int = 32, hash_name: str = "sha256") -> bytes
A one-shot wrapper for hkdf = hkdf_expand(hkdf_extract(salt, ikm, hash_name), info, length, hash_name).
Example
from purepycrypto import hkdf
okm = hkdf(b"master", salt=b"salt", info=b"ctx", length=32)
3.7 scrypt
scrypt(password, salt, N=4096, r=8, p=1, dklen=32) -> bytes
| Parameter | Type | Default | Description |
|---|---|---|---|
password |
bytes |
— | password |
salt |
bytes |
— | salt |
N |
int |
4096 |
CPU/memory cost parameter, must be a power of 2 and > 1 |
r |
int |
8 |
block size parameter, must be ≥ 1 |
p |
int |
1 |
parallelism parameter, must be ≥ 1 |
dklen |
int |
32 |
derived key length (bytes) |
Return value: bytes, a derived key of length dklen (RFC 7914).
Example
from purepycrypto import scrypt
dk = scrypt(b"password", b"NaCl", N=1024, r=8, p=16, dklen=64)
Notes: the implementation includes the Salsa20/8 core, BlockMix, and ROMix. When N is invalid (not a power of 2 or ≤ 1) it returns an error tuple (PPYC_ERR_INVALID_KDF_PARAM).
3.8 argon2id
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) -> bytes
| Parameter | Type | Default | Description |
|---|---|---|---|
password |
bytes |
— | password |
salt |
bytes |
— | salt (recommended ≥ 16 bytes) |
t |
int |
1 |
iteration (time) count, must be ≥ 1 |
m |
int |
256 |
memory cost, in KiB, must be ≥ 8*p |
p |
int |
1 |
parallelism, must be ≥ 1 |
tag_length |
int |
32 |
output length (bytes), must be ≥ 4 |
secret |
bytes |
b"" |
optional key (pepper, not written to storage beyond the digest input) |
ad |
bytes |
b"" |
optional associated data |
version |
int |
0x13 |
Argon2 version number (0x13 = 19) |
Return value: bytes, an Argon2id tag of length tag_length (RFC 9106).
Example
from purepycrypto import argon2id
tag = argon2id(
password=b"password",
salt=b"saltsaltsaltsalt",
t=3, m=65536, p=4,
tag_length=32,
)
Notes: when a parameter is out of range (e.g. t < 1, p < 1, m < 8*p, tag_length < 4) it returns an error tuple (PPYC_ERR_INVALID_KDF_PARAM). This is a memory-hard function; a larger m is slower and safer.
3.9 poly1305_mac
See §5.1.
4. aes — AES Symmetric Encryption
4.1 The AES class
AES(key: bytes)
| Parameter | Type | Description |
|---|---|---|
key |
bytes |
16 / 24 / 32 bytes → AES-128 / 192 / 256 |
Example
from purepycrypto import AES
import os
aes = AES(os.urandom(32)) # AES-256
Notes: key expansion (T-table implementation) is performed at construction time. An invalid key length raises an exception.
4.2 encrypt_ecb(data, n_workers=None) / decrypt_ecb(data, n_workers=None)
| Parameter | Type | Default | Description |
|---|---|---|---|
data |
bytes |
— | plaintext / ciphertext, length must be a multiple of 16 |
n_workers |
int |
None |
number of parallel workers (None = auto) |
Return value: bytes.
⚠️ ECB does not hide data patterns and is not recommended for general encryption; use it only for compatibility or deterministic scenarios.
4.3 encrypt_cbc(data, iv) / decrypt_cbc(data, iv, n_workers=None)
| Parameter | Type | Description |
|---|---|---|
data |
bytes |
length must be a multiple of 16 |
iv |
bytes |
16-byte initialization vector, must be random and unpredictable |
n_workers |
int |
only decrypt_cbc supports parallelism |
Example
iv = os.urandom(16)
ct = aes.encrypt_cbc(b"data" * 4, iv)
pt = aes.decrypt_cbc(ct, iv)
4.4 encrypt_ctr(data, nonce, n_workers=None) / decrypt_ctr(data, nonce, n_workers=None)
| Parameter | Type | Description |
|---|---|---|
data |
bytes |
any length |
nonce |
bytes |
8-byte nonce (the counter starts at 0) |
n_workers |
int |
supports parallelism |
⚠️ Never repeat the nonce under the same key, otherwise keystream reuse completely breaks confidentiality.
4.5 encrypt_cfb(data, iv) / decrypt_cfb(data, iv)
CFB mode; iv is 16 bytes.
4.6 encrypt_ofb(data, iv) / decrypt_ofb(data, iv)
OFB mode; iv is 16 bytes.
4.7 GCM (AEAD)
gcm_encrypt(nonce, plaintext, aad=b"") -> (bytes, bytes) # (ciphertext, tag)
gcm_decrypt(nonce, ct, tag, aad=b"") -> bytes
| Parameter | Type | Default | Description |
|---|---|---|---|
nonce |
bytes |
— | 12-byte nonce |
plaintext |
bytes |
— | plaintext (gcm_encrypt) |
ct |
bytes |
— | ciphertext (gcm_decrypt) |
tag |
bytes |
— | authentication tag (16 bytes) |
aad |
bytes |
b"" |
additional authenticated data |
Return value: gcm_encrypt returns (ciphertext, tag); gcm_decrypt returns the plaintext bytes.
Example
nonce = os.urandom(12)
ct, tag = aes.gcm_encrypt(nonce, b"secret", aad=b"header")
pt = aes.gcm_decrypt(nonce, ct, tag, aad=b"header")
Notes: when authentication fails or the ciphertext is tampered with it returns an error tuple (PPYC_ERR_AUTH_FAILED, msg, hint) and never returns unauthenticated plaintext (the historical DecryptionError can still be caught). GCM's GHASH can process large messages in parallel (n_workers).
4.8 encrypt_block(block) / decrypt_block(block)
Encrypt/decrypt a single 16-byte block (the low-level primitive).
v1.1 adds AES-GCM-SIV (nonce-misuse resistant AEAD), see §13.
5. chacha — ChaCha20 / Poly1305 / AEAD
5.1 poly1305_mac
poly1305_mac(key32: bytes, msg: bytes) -> bytes
| Parameter | Type | Description |
|---|---|---|
key32 |
bytes |
32-byte one-time key (r = the first 16 bytes, s = the last 16 bytes) |
msg |
bytes |
message to authenticate |
Return value: bytes, a 16-byte authenticator (RFC 8439).
Notes: r is clamped per the Poly1305 rules. The one-time key must never be reused.
5.2 chacha20poly1305_encrypt / chacha20poly1305_decrypt
chacha20poly1305_encrypt(key: bytes, nonce: bytes, plaintext: bytes,
aad: bytes = b"") -> bytes
chacha20poly1305_decrypt(key: bytes, nonce: bytes, ct_with_tag: bytes,
aad: bytes = b"") -> bytes
| Parameter | Type | Default | Description |
|---|---|---|---|
key |
bytes |
— | 32-byte key |
nonce |
bytes |
— | 12-byte nonce |
plaintext |
bytes |
— | plaintext (encryption) |
ct_with_tag |
bytes |
— | ciphertext |
aad |
bytes |
b"" |
additional authenticated data |
Return value: encryption returns ciphertext || Tag; decryption returns the plaintext bytes.
Example
from purepycrypto import chacha20poly1305_encrypt, chacha20poly1305_decrypt
import os
key, nonce = os.urandom(32), os.urandom(12)
blob = chacha20poly1305_encrypt(key, nonce, b"msg", aad=b"aad")
pt = chacha20poly1305_decrypt(key, nonce, blob, aad=b"aad")
Notes: authentication failure returns an error tuple (PPYC_ERR_AUTH_FAILED, msg, hint) (RFC 8439; equivalent to IETF ChaCha20-Poly1305).
5.3 xchacha20poly1305_encrypt / xchacha20poly1305_decrypt
xchacha20poly1305_encrypt(key: bytes, nonce: bytes, plaintext: bytes,
aad: bytes = b"") -> bytes
xchacha20poly1305_decrypt(key: bytes, nonce: bytes, ct_with_tag: bytes,
aad: bytes = b"") -> bytes
Same as §5.2, except that nonce is 24 bytes (192-bit).
The large nonce space allows nonces to be generated safely at random, without counter management.
Notes: internally uses HChaCha20 to derive the subkey from the 24-byte nonce.
6. x25519 — X25519 Key Exchange
6.1 x25519
x25519(k: bytes, u: bytes) -> bytes
| Parameter | Type | Description |
|---|---|---|
k |
bytes |
32-byte scalar (private key) |
u |
bytes |
32-byte u-coordinate (public key) |
Return value: bytes, a 32-byte result (RFC 7748).
Notes: internally k is clamped and the top bit of u is cleared; scalar multiplication is constant-time (cswap implementation). When the length of k or u is not 32 it returns an error tuple (PPYC_ERR_INVALID_LENGTH).
6.2 x25519_base
x25519_base(scalar: bytes) -> bytes
Equivalent to x25519(scalar, (9).to_bytes(32, "little")), i.e. base-point multiplication, yielding the public key.
Example
from purepycrypto import x25519_base
import os
priv = os.urandom(32)
pub = x25519_base(priv)
6.3 x25519_shared
x25519_shared(priv: bytes, peer_pub: bytes) -> (bytes, bool)
| Parameter | Type | Description |
|---|---|---|
priv |
bytes |
own 32-byte private key |
peer_pub |
bytes |
peer's 32-byte public key |
Return value: (shared, is_zero) — shared is the 32-byte shared secret; is_zero being True means the result is all zeros (low-order point / forged public key).
Example
from purepycrypto import x25519_generate_keypair, x25519_shared
priv_a, pub_a = x25519_generate_keypair()
priv_b, pub_b = x25519_generate_keypair()
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
Notes: callers must check is_zero and reject an all-zero result (RFC 7748 §6.1).
6.4 x25519_generate_keypair
x25519_generate_keypair() -> (bytes, bytes)
Return value: (priv, pub), both 32 bytes. The private key is generated by os.urandom(32).
7. rsa — RSA Public-Key Cryptography
7.1 RSAPublicKey
RSAPublicKey(n: int, e: int)
| Attribute | Type | Description |
|---|---|---|
n |
int |
modulus |
e |
int |
public exponent |
k |
int (attribute) |
modulus length in bytes |
hash_func / h_len |
— | the hash function automatically chosen from the modulus length and its length |
7.2 RSAPrivateKey
RSAPrivateKey(n, e, d, p, q, verify=True)
| Attribute | Type | Description |
|---|---|---|
n, e, d, p, q |
int |
modulus, public exponent, private exponent, the two large prime factors |
dp, dq, q_inv |
int |
CRT parameters |
k |
int (attribute) |
modulus length in bytes |
salt_len |
int (attribute) |
the recommended/default PSS salt length for this key |
Notes: an optional self-verification is performed at construction time (verify=True); internally it includes blinding and CRT + Montgomery acceleration.
7.3 rsa_keygen
rsa_keygen(bits: int = 2048, parallel: bool = True) -> (RSAPublicKey, RSAPrivateKey)
| Parameter | Type | Default | Description |
|---|---|---|---|
bits |
int |
2048 |
modulus bit size, must be ≥ 521 |
parallel |
bool |
True |
whether to use multiprocessing to search for the two prime factors in parallel |
Return value: (pub, priv).
Example
from purepycrypto import rsa_keygen
pub, priv = rsa_keygen(bits=2048)
Notes: bits < 521 immediately raises PPYC_ERR(PPYC_ERR_INVALID_RSA_BITS, ...) (unable to continue during construction → fatal error). Primality testing uses trial division + Miller-Rabin + strong Lucas (BPSW). A larger bits is slower to generate.
7.4 rsa_oaep_encrypt / rsa_oaep_decrypt
rsa_oaep_encrypt(message: bytes, pub: RSAPublicKey, label: bytes = b"") -> bytes
rsa_oaep_decrypt(ciphertext: bytes, priv: RSAPrivateKey, label: bytes = b"") -> bytes
| Parameter | Type | Default | Description |
|---|---|---|---|
message |
bytes |
— | plaintext (length-limited, approx. k - 2*h_len - 2) |
ciphertext |
bytes |
— | ciphertext (length must equal k) |
pub / priv |
— | — | public key / private key |
label |
bytes |
b"" |
OAEP label (participates in derivation) |
Return value: encryption returns a k-byte ciphertext; decryption returns the plaintext.
Example
ct = rsa_oaep_encrypt(b"secret", pub, label=b"ctx")
pt = rsa_oaep_decrypt(ct, priv, label=b"ctx")
Notes: decryption failure (wrong length, label mismatch, invalid padding, etc.) returns an error tuple (PPYC_ERR_DECRYPT_FAILED, msg, hint) (without distinguishing the specific cause, keeping behavior constant).
7.5 rsa_pss_sign / rsa_pss_verify
rsa_pss_sign(message: bytes, priv: RSAPrivateKey, salt_len: int = None) -> bytes
rsa_pss_verify(message: bytes, signature: bytes, pub: RSAPublicKey,
salt_len: int = None) -> bool
| Parameter | Type | Default | Description |
|---|---|---|---|
message |
bytes |
— | message to sign |
signature |
bytes |
— | signature (length must equal k) |
priv / pub |
— | — | private key / public key |
salt_len |
int |
None |
PSS salt length; None uses the key's default |
Return value: rsa_pss_sign returns a k-byte signature; rsa_pss_verify returns a bool.
Example
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
Notes: verification failure returns False (no exception).
8. der — ASN.1 DER / PEM Serialization
8.1 private_key_to_pkcs1_der
private_key_to_pkcs1_der(priv: RSAPrivateKey) -> bytes
Returns the DER encoding of the PKCS#1 RSAPrivateKey.
8.2 public_key_to_pkcs1_der
public_key_to_pkcs1_der(pub: RSAPublicKey) -> bytes
Returns the DER encoding of the PKCS#1 RSAPublicKey (SEQUENCE { n, e }).
8.3 private_key_to_pkcs8_der
private_key_to_pkcs8_der(priv: RSAPrivateKey) -> bytes
Returns the DER encoding of the PKCS#8 PrivateKeyInfo (RFC 5958), with the algorithm identifier rsaEncryption.
8.4 public_key_to_spki_der
public_key_to_spki_der(pub: RSAPublicKey) -> bytes
Returns the DER encoding of the SubjectPublicKeyInfo (RFC 5280).
8.5 private_key_to_pem
private_key_to_pem(priv: RSAPrivateKey) -> str
Returns PEM text with the label PRIVATE KEY (PKCS#8).
8.6 public_key_to_pem
public_key_to_pem(pub: RSAPublicKey) -> str
Returns PEM text with the label PUBLIC KEY (SPKI).
8.7 parse_private_pem
parse_private_pem(pem: str) -> RSAPrivateKey
Parses a PKCS#8 PEM private key (containing PKCS#1) and returns an RSAPrivateKey.
Example
from purepycrypto import rsa_keygen, private_key_to_pem, parse_private_pem
pub, priv = rsa_keygen(2048)
pem = private_key_to_pem(priv)
priv2 = parse_private_pem(pem)
assert priv2.n == priv.n
Notes: only RSA PKCS#8 private-key PEM is supported; the legacy PKCS#1 RSA PRIVATE KEY label is not supported, nor are algorithms such as EC.
9. parallel — Multiprocessing Acceleration
The module purepycrypto.parallel provides process-pool reuse and shared memory.
| Name | Description |
|---|---|
_HAS_MP |
bool, whether the platform supports multiprocessing and SharedMemory |
_get_pool(n) |
obtain/reuse a process pool of size n (internal) |
_alloc_shm(data) / _free_shm(shm) |
shared-memory allocation and release (internal) |
_cleanup_pool() |
registered via atexit to clean up the process pool at process exit |
Notes: when _HAS_MP is False or parallelism fails, the library automatically falls back to the serial implementation, with no functional change. It is used by AES's ECB/CBC/CTR/GCM and by RSA generation.
10. Command-Line Interface
A single command purepycrypto, whose behavior is dispatched automatically based on whether arguments are present:
purepycrypto # no arguments -> interactive TUI
purepycrypto hash --text abc --hex # with arguments -> command-line mode
purepycrypto --help # command-line help
When not installed, the equivalent is: python -m purepycrypto [subcommand].
- Interactive TUI: you can select and perform hashing, KDF (PBKDF2/HKDF/scrypt/Argon2id), AES, ChaCha20-Poly1305, X25519, RSA, PEM/DER encoding and decoding, etc.; CN/EN switching is supported (default EN).
- Command-line mode: subcommands
hash/hmac/kdf/aes/chacha/x25519/rsa/rand/selftest/version. - CLI exit codes:
0success /1other /2PPYC_ERR/3file not found /4argument error.
See cli.md for details.
11. sha3 — SHA-3 / Keccak / SHAKE
The module purepycrypto.sha3 implements the FIPS 202 SHA-3 fixed-length hashes, the SHAKE extendable-output functions (XOFs),
and HMAC-SHA3. All are imported through the purepycrypto.sha3 submodule:
from purepycrypto.sha3 import (
sha3_224, sha3_256, sha3_384, sha3_512,
shake128, shake256, hmac_sha3_256, hmac_sha3_512,
)
11.1 sha3_224 / sha3_256 / sha3_384 / sha3_512
sha3_224(data: bytes) -> bytes # 28 bytes
sha3_256(data: bytes) -> bytes # 32 bytes
sha3_384(data: bytes) -> bytes # 48 bytes
sha3_512(data: bytes) -> bytes # 64 bytes
| Parameter | Type | Description |
|---|---|---|
data |
bytes |
data to hash |
Return value: bytes, a SHA-3 digest of the corresponding length (FIPS 202).
Example
from purepycrypto.sha3 import sha3_256, sha3_512
assert sha3_256(b"abc").hex() == (
"3a985da74fe225b2045c172d6bd390bd855f086e3e9d525b46bfe24511431532"
)
assert len(sha3_512(b"abc")) == 64
Notes: fully compatible with hashlib.sha3_256, etc. (already cross-verified).
11.2 shake128 / shake256
shake128(data: bytes, outlen: int) -> bytes
shake256(data: bytes, outlen: int) -> bytes
| Parameter | Type | Description |
|---|---|---|
data |
bytes |
input data |
outlen |
int |
output length (bytes), must be >= 0 |
Return value: bytes, an XOF output of exactly outlen bytes.
Example
from purepycrypto.sha3 import shake128, shake256
assert shake128(b"abc", 32).hex() == (
"5881092dd818bf5cf8a3ddb793fbcba74097d5c526a6d35f97b83351940f2cc8"
)
assert len(shake256(b"abc", 100)) == 100
Notes: outlen < 0 returns an error tuple (PPYC_ERR_INVALID_ARG); outlen may be 0. Compatible with hashlib.shake_*.
11.3 hmac_sha3_256 / hmac_sha3_512
hmac_sha3_256(key: bytes, message: bytes) -> bytes # 32 bytes
hmac_sha3_512(key: bytes, message: bytes) -> bytes # 64 bytes
| Parameter | Type | Description |
|---|---|---|
key |
bytes |
key (any length; if longer than the block size it is first compressed with the corresponding SHA-3) |
message |
bytes |
message |
Return value: bytes, a 32 / 64-byte HMAC-SHA3 value.
Example
from purepycrypto.sha3 import hmac_sha3_256
mac = hmac_sha3_256(b"key", b"message") # 32 bytes
Notes: the block size B is the rate r of that SHA-3 variant (SHA3-256 → 136, SHA3-512 → 72), consistent with the OpenSSL / hashlib / hmac convention.
11.4 Convenient Hex Interfaces
| Function | Signature | Description |
|---|---|---|
sha3_224_hex / sha3_256_hex / sha3_384_hex / sha3_512_hex |
sha3_xxx_hex(data: bytes) -> str |
hex string of the corresponding SHA-3 digest |
shake128_hex / shake256_hex |
shake_xxx_hex(data: bytes, outlen: int) -> str |
hex string of the XOF output |
11.5 Low-Level and Constants
| Name | Description |
|---|---|
keccak_f1600(state) |
Keccak-f[1600] permutation (modifies in place and returns a list of 25 64-bit lanes) |
RATE_SHA3_224 / 256 / 384 / 512, RATE_SHAKE128 / 256 |
the rate r (bytes) of each variant |
SUFFIX_SHA3 (0x06), SUFFIX_SHAKE (0x1F) |
domain-separation suffixes |
11.6 sha3_batch (New in v3.2.0)
sha3_batch(items: list[bytes], algo: str = "sha3_256", n_workers: int = None) -> list[bytes]
Batch-hashes multiple independent messages (the SHA-3 sponge cannot split a single long message across blocks, so the parallel granularity is "multiple messages").
| Parameter | Type | Default | Description |
|---|---|---|---|
items |
list[bytes] |
— | list of messages to hash |
algo |
str |
"sha3_256" |
sha3_224 / sha3_256 / sha3_384 / sha3_512 / shake128 / shake256 |
n_workers |
int |
None |
None auto-detects the CPU count; 1 forces serial |
Return value: a list of digests in the same order as items; when algo is invalid it returns an error tuple (PPYC_ERR_INVALID_ALGO).
from purepycrypto import sha3_batch
digests = sha3_batch([b"a", b"b", b"c"], algo="sha3_256", n_workers=4)
⚠️ Multiprocessing on Windows requires the
if __name__ == "__main__":guard;sha3_batchhas a built-in fallback, so if multiprocessing fails to start it degenerates to serial automatically.
12. ed25519 — Ed25519 Digital Signatures
The module purepycrypto.ed25519 implements Pure Ed25519 (EdDSA) from RFC 8032.
All are imported through the purepycrypto.ed25519 submodule:
from purepycrypto.ed25519 import (
ed25519_keygen, ed25519_publickey, ed25519_sign, ed25519_verify,
)
12.1 ed25519_keygen
ed25519_keygen() -> (bytes, bytes)
Return value: a (seed32, pub32) tuple. seed32 is the 32-byte private-key seed (i.e. the RFC 8032 private key),
and pub32 is the corresponding 32-byte public key (compressed point encoding).
Example
from purepycrypto.ed25519 import ed25519_keygen
seed, pub = ed25519_keygen()
assert len(seed) == 32 and len(pub) == 32
Notes: the seed comes from os.urandom(32); the private key is the seed, and ed25519_sign uses that seed directly.
12.2 ed25519_publickey
ed25519_publickey(seed32: bytes) -> bytes
| Parameter | Type | Description |
|---|---|---|
seed32 |
bytes |
32-byte private-key seed |
Return value: bytes, the 32-byte public key.
Example
from purepycrypto.ed25519 import ed25519_publickey
seed = bytes.fromhex(
"9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60")
assert ed25519_publickey(seed).hex() == (
"d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a")
12.3 ed25519_sign
ed25519_sign(message: bytes, seed32: bytes) -> bytes
| Parameter | Type | Description |
|---|---|---|
message |
bytes |
message to sign (any length, bytes-like) |
seed32 |
bytes |
32-byte private-key seed |
Return value: bytes, a 64-byte signature R || S.
Example
from purepycrypto.ed25519 import ed25519_keygen, ed25519_sign
seed, pub = ed25519_keygen()
sig = ed25519_sign(b"hello", seed)
assert len(sig) == 64
Notes: Ed25519 is a deterministic signature (same seed + same message → same signature), requiring no external randomness source.
12.4 ed25519_verify
ed25519_verify(signature64: bytes, message: bytes, pub32: bytes) -> bool
| Parameter | Type | Description |
|---|---|---|
signature64 |
bytes |
64-byte signature |
message |
bytes |
message |
pub32 |
bytes |
32-byte public key |
Return value: bool, True if verification passes, otherwise False.
Example
from purepycrypto.ed25519 import ed25519_keygen, ed25519_sign, ed25519_verify
seed, pub = ed25519_keygen()
sig = ed25519_sign(b"hello", seed)
assert ed25519_verify(sig, b"hello", pub) is True
assert ed25519_verify(sig, b"hell0", pub) is False
Notes: any invalid input (wrong length, invalid point encoding, S >= L) or verification failure always returns False,
without raising; callers must check the return value explicitly.
12.5 Helper Interfaces and Exceptions
| Name | Signature / Description |
|---|---|
ed25519_scalarmult_base |
ed25519_scalarmult_base(scalar) -> bytes, computes encode(s·B) (scalar is an int or ≤32 bytes) |
ed25519_is_valid_publickey |
ed25519_is_valid_publickey(pub32: bytes) -> bool, determines whether the public-key encoding can be decoded |
Ed25519Error |
parameter / encoding / decoding error exception (a subclass of PPYC_ERR, default code PPYC_ERR_INVALID_ARG; ed25519_verify failure always returns False, never raises) |
12.6 Security Notes
Scalar multiplication uses a fixed 4-bit window + a masked lookup table and a 256-round fixed-length main loop, striving to eliminate
secret-dependent branches; but pure-Python big-integer arithmetic cannot guarantee true constant time. See the Ed25519 section of
security.md for details.
13. aes_gcm_siv — AES-GCM-SIV
The module purepycrypto.aes_gcm_siv implements the nonce-misuse resistant AEAD of RFC 8452:
AEAD_AES_128_GCM_SIV and AEAD_AES_256_GCM_SIV. All are imported through the purepycrypto.aes_gcm_siv submodule:
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,
)
13.1 aes128_gcm_siv_encrypt / aes128_gcm_siv_decrypt
aes128_gcm_siv_encrypt(key: bytes, nonce: bytes, plaintext: bytes,
aad: bytes = b"") -> (bytes, bytes)
aes128_gcm_siv_decrypt(key: bytes, nonce: bytes, ct: bytes, tag: bytes,
aad: bytes = b"") -> bytes
| Parameter | Type | Default | Description |
|---|---|---|---|
key |
bytes |
— | 16-byte key (key-generating key) |
nonce |
bytes |
— | 12-byte nonce |
plaintext |
bytes |
— | plaintext (encryption) |
ct |
bytes |
— | ciphertext (decryption) |
tag |
bytes |
— | 16-byte authentication tag (decryption) |
aad |
bytes |
b"" |
additional authenticated data |
Return value: encryption returns (ct, tag); decryption returns the plaintext bytes.
Example
from purepycrypto.aes_gcm_siv import aes128_gcm_siv_encrypt, aes128_gcm_siv_decrypt
import os
key = os.urandom(16); nonce = os.urandom(12)
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")
assert pt == b"hello"
Notes: when key is not 16 bytes or nonce is not 12 bytes it returns an error tuple (PPYC_ERR_INVALID_KEY_LEN / PPYC_ERR_INVALID_NONCE_LEN); authentication failure returns (PPYC_ERR_AUTH_FAILED, msg, hint).
13.2 aes256_gcm_siv_encrypt / aes256_gcm_siv_decrypt
The signature is the same as §13.1, but key must be 32 bytes (corresponding to AEAD_AES_256_GCM_SIV).
13.3 aes_gcm_siv_encrypt / aes_gcm_siv_decrypt (unified entry)
aes_gcm_siv_encrypt(key: bytes, nonce: bytes, plaintext: bytes,
aad: bytes = b"") -> (bytes, bytes)
aes_gcm_siv_decrypt(key: bytes, nonce: bytes, ct: bytes, tag: bytes,
aad: bytes = b"") -> bytes
Dispatches automatically by key length: 16 bytes → AES-128-GCM-SIV; 32 bytes → AES-256-GCM-SIV; any other length returns an error tuple (PPYC_ERR_INVALID_KEY_LEN).
Example
from purepycrypto.aes_gcm_siv import aes_gcm_siv_encrypt, aes_gcm_siv_decrypt
import os
key = os.urandom(32)
nonce = os.urandom(12)
ct, tag = aes_gcm_siv_encrypt(key, nonce, b"secret")
assert aes_gcm_siv_decrypt(key, nonce, ct, tag) == b"secret"
13.4 polyval
polyval(h: bytes, data: bytes) -> bytes
| Parameter | Type | Description |
|---|---|---|
h |
bytes |
16-byte POLYVAL key |
data |
bytes |
length must be a multiple of 16 |
Return value: bytes, a 16-byte POLYVAL digest (RFC 8452 §3).
Notes: an independent public interface, convenient for unit tests / cross-verification; the AEAD internally reuses a precomputed lookup table.
13.5 Constants
| Name | Value | Description |
|---|---|---|
TAG_LEN |
16 |
authentication tag length (bytes) |
NONCE_LEN |
12 |
nonce length (bytes) |
13.6 Security Notes
The principle of nonce-misuse resistance and the repetition limit are described in the AES-GCM-SIV section of security.md.
13.7 Cache Control (New in v3.2.0)
set_cache_enabled(enabled: bool) -> None
cache_enabled() -> bool
clear_caches() -> None
| Function | Description |
|---|---|
set_cache_enabled(bool) |
enable / disable the derived-key and POLYVAL table caches (enabled by default, performance first) |
cache_enabled() |
returns the current cache switch state |
clear_caches() |
clears the cached derived keys / table contents |
If the threat model disallows derived keys residing in memory, you can disable it by calling
set_cache_enabled(False); after disabling, large-message encryption/decryption no longer uses automatic multiprocessing, and performance drops.
from purepycrypto import set_cache_enabled, cache_enabled, clear_caches
set_cache_enabled(False)
assert cache_enabled() is False
clear_caches()
14. Exceptions and the Error System
| Name | Type | Description |
|---|---|---|
PPYC_ERR / PPYCError |
exception | fatal-error base class; carries code / message / suggestion and as_tuple() |
CryptoError |
exception | legacy name (subclass of PPYC_ERR, default code PPYC_ERR_INTERNAL) |
DecryptionError |
exception | legacy name (subclass of PPYC_ERR, default code PPYC_ERR_AUTH_FAILED) |
Ed25519Error |
exception | legacy name (subclass of PPYC_ERR, default code PPYC_ERR_INVALID_ARG) |
err / ok / is_ok / is_err / raise_ppyc / OK_TUPLE |
helpers | non-fatal error 3-tuple helpers |
ALL_ERROR_CODES / PPYC_ERR_PREFIX |
tuple / str |
all error codes / the unified prefix "PPYC_ERR_" |
PPYC_ERR_* |
str |
the 41 standard error code constants (general / arguments / key / authentication / encoding / file / environment / algorithm / CLI-TUI) |
MASK32 / MASK64 / MASK128 |
int |
bitmask constants |
POLY1305_P |
int |
Poly1305 prime 2^130 - 5 |
GHASH_R / R_CONST |
int |
GCM reduction constant |
15. Top-Level Export List
As of v3.2.0, the error-code constants, SHA-3 / SHAKE, Ed25519, and AES-GCM-SIV are all merged into the top-level exports, so you can directly
from purepycrypto import sha3_256, ed25519_sign, aes_gcm_siv_encrypt, PPYC_ERR_INVALID_KEY_LEN.
purepycrypto.__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 and all PPYC_ERR_* error-code constants
common
rand_int, rand_bytes, MASK32, MASK64, MASK128, POLY1305_P, GHASH_R, R_CONST
hash
sha256, sha512, blake2b
sha3
sha3_224, sha3_256, sha3_384, sha3_512, shake128, shake256,
hmac_sha3_256, hmac_sha3_512, sha3_batch
kdf
hmac_sha256, hmac_sha512, pbkdf2_hmac, hkdf, hkdf_extract, hkdf_expand, scrypt, argon2id
aes
AES
aes_gcm_siv
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
chacha
poly1305_mac, chacha20poly1305_encrypt, chacha20poly1305_decrypt, xchacha20poly1305_encrypt, xchacha20poly1305_decrypt
x25519
x25519, x25519_base, x25519_shared, x25519_generate_keypair
ed25519
ed25519_keygen, ed25519_publickey, ed25519_sign, ed25519_verify
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 / meta
run_tui, run_cli, main, __version__, __author__, __license__
import purepycrypto
print(purepycrypto.__version__) # 3.2.0
print(purepycrypto.__author__) # Dvs(DvsXT)
print(purepycrypto.__license__) # MIT
16. kdf2 — Hardened Key Derivation (New in v3.2.0)
The module purepycrypto.kdf2 provides more strictly validated key-derivation interfaces on top of the existing kdf (such as a minimum salt
length and Argon2 encoded strings).
| Function | Signature / Description |
|---|---|
pbkdf2 / pbkdf2_hmac |
(password, salt, iterations, dklen, hash_name="sha256", min_salt_len=8) -> bytes |
argon2id_hash / argon2i_hash / argon2d_hash |
(password, salt, t=3, m=65536, p=4, tag_length=32, secret=b"", ad=b"", version=19) -> bytes |
argon2id_verify / argon2i_verify / argon2d_verify |
(password, salt, tag, ...) -> bool |
argon2id_hash_encoded / argon2_verify_encoded |
generate / verify a standard $argon2id$... encoded string |
scrypt_simple |
(password, salt, n=16384, r=8, p=1, dklen=32, min_salt_len=8) -> bytes |
hkdf_expand_multi |
(prk, infos_lengths, hash_name="sha256") -> bytes |
# example
from purepycrypto import argon2id_hash_encoded, argon2_verify_encoded
enc = argon2id_hash_encoded(b"password", b"salt0123456789ab")
assert argon2_verify_encoded(b"password", enc) is True
17. encoding — Encoding (New in v3.2.0)
The module purepycrypto.encoding provides pure-Python encoding implementations (byte-for-byte identical to the standard library):
| Function | Description |
|---|---|
b64encode / b64decode |
Base64 (altchars may be passed; validate for validation) |
b64encode_urlsafe / b64decode_urlsafe |
Base64 URL-safe |
b64encode_nopad / b64decode_nopad |
Base64 without padding |
b32encode / b32decode (b32encode_hex / b32decode_hex) |
Base32 |
hex_encode / hex_decode (hex_encode_sep / hex_decode_sep) |
Base16 / Hex |
b58encode / b58decode |
Base58 (Bitcoin alphabet) |
b64_encode_bigint / b64_decode_bigint |
big-integer base64url |
# example
from purepycrypto import b64encode, b58encode, hex_encode
assert b64encode(b"abc") == b"YWJj"
assert hex_encode(b"\x01\x02") == "0102"
18. rand — CSPRNG Utilities (New in v3.2.0)
The module purepycrypto.rand provides cryptographically secure random (CSPRNG) utilities, all based on os.urandom / secrets:
| Function | Description |
|---|---|
random_bytes(n) |
n bytes of random data |
random_int(a, b) / random_below(n) |
uniformly random integer in an interval / in [0, n) |
random_bit() / random_bits(k) |
1 random bit / k random bits |
token_bytes / token_hex / token_urlsafe |
token bytes / hex / URL-safe string |
random_string(length, alphabet) |
random string over the specified alphabet |
random_password(length=16, upper=True, lower=True, digits=True, special=False, exclude="") |
random password |
random_uuid4() |
random UUID v4 |
random_choice(seq) / random_sample(seq, k) |
random choice / sampling |
# example
from purepycrypto import token_hex, random_password, random_uuid4
print(token_hex(4))
print(random_password(16))
print(random_uuid4())
⚠️ Windows Multiprocessing Notes (Important)
Some APIs of this library 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 message 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
# 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)
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
- Add the
if __name__ == "__main__":guard (recommended; you keep the parallel speedup) - Explicitly pass
n_workers=1to force serial (no startup overhead; actually faster for small data)
Fault tolerance note:
sha3_batchhas 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 theRuntimeErrorabove in the same situation, so be sure to add the guard.
Linux / macOS: default to
forkand usually have no such limitation; but for cross-platform consistency, it is still strongly recommended to add theif __name__ == "__main__":guard uniformly.