Files
purepycrypto/purepycrypto/rsa.py
T
dvs 5dfdd87c06 Release v3.2.1: performance overhaul (1.96x geometric-mean speed-up)
Pure-Python, zero-dependency speed-up across every hot path. No public API,
error-semantics or security change.

Measured (interleaved A/B min-of-N, idle 16-core, 1 KiB payload):
  Base64 decode      21.98x
  Base58 encode       8.01x
  ChaCha20-Poly1305   3.54x
  XChaCha20-Poly1305  3.28x
  Base64 encode       2.98x
  AES-256-GCM (enc)   2.25x   (dec) 2.26x
  AES-GCM-SIV enc     2.06x
  AES-256 CTR/ECB/CBC 2.01x / 1.96x / 1.88x
  AES single block    1.87x
  Poly1305 MAC        1.41x
  Ed25519 sign        1.41x
  X25519 base         1.19x
  BLAKE2b / SHA3-512 / SHAKE128  1.34x / 1.33x / 1.30x
  => 24 improved, 3 unchanged, 0 regressed.

Techniques (all pure Python):
  - code-generated, fully unrolled AES round function and Keccak-f[1600]
  - big-integer bulk operations for GHASH, POLYVAL, buffer XOR, Base64 pack
  - precomputed lookup tables (AES T-tables, GHASH/POLYVAL 4-bit windows)
  - branch-free constant-time selection in Ed25519 scan and X25519 ladder
  - lazy modular reduction in X25519 field arithmetic
  - batched Base58/Base64 processing
  - inlined inner loops in AEAD assembly and the SHA-2 message schedule

Verification:
  - full test suite: 639 passed, 1 skipped, 0 failed
  - all FIPS / RFC / NIST vectors reproduce byte-for-byte
  - differential probe of 1266 deterministic inputs: identical
    (one unreachable private-helper edge case, no caller can reach it)
  - public API signature comparison: 0 removals, 0 changes
  - independent security regression suite: 35 / 35

Also adds docs/benchmark.md, bench/benchmark.py and the v3.2.1 documentation.
2026-09-27 11:37:33 +08:00

819 lines
28 KiB
Python

# -*- 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,
_xor_bytes_fast,
)
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).
"""
# Python >= 3.8 exposes the extended-Euclid inverse as a C-implemented built-in
# (`pow(x, -1, m)`), which is markedly faster than the pure-Python extended_gcd()
# above for the multi-thousand-bit moduli used by RSA. Values and error
# semantics are unchanged (same canonical representative in [0, m)).
try:
return pow(a % m, -1, m) % m
except ValueError:
g, _x, _ = extended_gcd(a % m, m)
raise PPYC_ERR(PPYC_ERR_INVALID_ARG,
f"{a} has no multiplicative inverse modulo {m} (gcd={g})",
"make sure a and m are coprime")
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:
"""Draw a random `bits`-bit prime (BPSW + 4 random Miller-Rabin rounds).
The two top bits of the candidate are forced to 1, i.e. the prime is drawn
from ``[0.75 * 2^(bits-1), 2^bits)`` -- this is exactly the range FIPS 186-4
(B.3.1) prescribes for the RSA factors (`sqrt(2)*2^(n/2-1) <= p < 2^(n/2)`),
and it is what OpenSSL does as well. The practical consequence is that the
product of two such primes is *guaranteed* to have exactly ``2*bits`` bits, so
rsa_keygen() no longer has to throw away ~38% of the generated pairs
(P((1+u)(1+v) < 2) = 2*ln2 - 1 = 0.386 for uniform u, v in [0,1)) and never
re-runs the search. Security-wise this merely restricts the sample space to
the standard FIPS range; the prime still carries ~bits-1 bits of entropy.
"""
urandom = os.urandom
isqrt = math.isqrt
while True:
base = int.from_bytes(urandom(bits // 8), "big")
base |= (1 << (bits - 1)) | (1 << (bits - 2)) | 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:
import multiprocessing as mp # lazy: keeps the module import cheap
with mp.Pool(2) as pool:
p, q = pool.map(_gen_worker, [bits_half, bits_half])
except (OSError, RuntimeError, ImportError, AttributeError, ValueError):
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 = _xor_bytes_fast(DB, dbMask)
seedMask = mgf1(maskedDB, h_len, hash_func, h_len)
maskedSeed = _xor_bytes_fast(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 = _xor_bytes_fast(maskedSeed, seedMask)
dbMask = mgf1(seed, k - h_len - 1, hash_func, h_len)
DB = _xor_bytes_fast(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(_xor_bytes_fast(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 = _xor_bytes_fast(bytes(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_re = None # (r^e mod n), kept in sync with _blind_r
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)
# r^e mod n is carried along instead of being recomputed on every
# blind(): unblind() squares r, and (r^2)^e = (r^e)^2, so the
# cached value can be updated with a single squaring -- the blinding
# factors themselves (and therefore the blinding) are unchanged.
self._blind_re = pow(r, self.e, 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
self._blind_re = None
def blind(self, c: int) -> int:
r = self._blind_r
if r is None:
self._init_blinding()
r = self._blind_r
re = self._blind_re
if re is None: # defensive: keep the cache consistent
re = pow(r, self.e, self.n)
self._blind_re = re
return (c * re) % 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._blind_re = (self._blind_re * self._blind_re) % self.n
self._maybe_reset_blinding()
return m
def _crt_decrypt_raw(self, c: int) -> int:
# CRT private-key exponentiation: two half-size modular exponentiations with Python's
# built-in pow() (C implementation). Mathematically identical to the previous pure-Python
# Montgomery pow() (m_i = c^d_i mod n_i), but several times faster.
_pow = pow
p = self.p
q = self.q
m1 = _pow(c, self.dp, p)
m2 = _pow(c, self.dq, q)
h = (self.q_inv * (m1 - m2)) % p
return m2 + h * 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")
# s = m^d mod n. Use CRT (two half-size exponentiations) together with RSA blinding
# (decrypt_blinded), which is several times faster than a single full-size pow(m, d, n)
# and additionally hardens against timing attacks. Result value is identical.
sig = priv.decrypt_blinded(m)
except PPYC_ERR as e:
return e.as_tuple()
return sig.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)