Files
purepycrypto/purepycrypto/common.py
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

211 lines
6.8 KiB
Python

# -*- 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]