Files
purepycrypto/purepycrypto/tests/test_rand_verify.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

294 lines
10 KiB
Python

# -*- coding: utf-8 -*-
"""Independent review of purepycrypto.rand (new module in v3.2.0).
Verification strategy (**independent of the module's own tests**):
* uniformity: ``random_int(0,9)`` / ``random_below(n)`` each sampled 100k times,
frequency deviation +/-5% (small n) and chi-square statistic < critical value;
* range correctness / boundaries (n=0/1, a==b, seq length 1, k=0);
* error returns (negative length, a>b, empty alphabet, empty seq ...) are err tuples;
* uniqueness: 1000 uuid4 / token_hex(16) / random_bytes(16) with no duplicates;
* basic randomness comparison against os.urandom;
* static check: this module must not use the non-cryptographic ``random`` module.
"""
import os
import re
import sys
import pytest
_HERE = os.path.dirname(os.path.abspath(__file__))
_PKG_PARENT = os.path.dirname(_HERE)
if _PKG_PARENT not in sys.path:
sys.path.insert(0, _PKG_PARENT)
from purepycrypto import rand as R # noqa: E402
from purepycrypto._ppyc_error import PPYC_ERR_PREFIX # noqa: E402
def _is_err(v):
return (isinstance(v, tuple) and len(v) == 3
and isinstance(v[0], str) and v[0].startswith(PPYC_ERR_PREFIX))
def _chi2(counts, expected):
return sum((c - expected) ** 2 / expected for c in counts)
#: chi-square critical value at 0.001 significance (df -> critical value)
_CHI2_CRIT = {2: 13.82, 6: 22.46, 9: 27.88, 255: 330.6}
# ======================================================================
# 1. Uniformity statistics
# ======================================================================
def test_random_int_0_9_uniform():
N = 100_000
counts = [0] * 10
for _ in range(N):
v = R.random_int(0, 9)
assert isinstance(v, int) and 0 <= v <= 9
counts[v] += 1
exp = N / 10
# each value frequency within +/-5%
for c in counts:
assert abs(c - exp) <= 0.05 * exp, counts
# chi-square test (df=9, p=0.001 critical value 27.88)
assert _chi2(counts, exp) < _CHI2_CRIT[9], counts
@pytest.mark.parametrize("n,N", [(3, 100_000), (7, 100_000), (10, 100_000), (256, 200_000)])
def test_random_below_uniform(n, N):
counts = [0] * n
for _ in range(N):
v = R.random_below(n)
assert isinstance(v, int) and 0 <= v < n
counts[v] += 1
exp = N / n
# per-value +/-5% for small n (single bins have too few samples for large n, so use chi-square only)
if n <= 10:
for c in counts:
assert abs(c - exp) <= 0.05 * exp, (n, counts)
assert _chi2(counts, exp) < _CHI2_CRIT[n - 1], (n, counts)
def test_random_int_range_and_mean():
vals = [R.random_int(-5, 5) for _ in range(20000)]
assert all(-5 <= v <= 5 for v in vals)
mean = sum(vals) / len(vals)
assert abs(mean - 0.0) < 0.25, mean # expected mean 0
# ======================================================================
# 2. Range / boundaries
# ======================================================================
def test_boundaries():
assert R.random_below(1) == 0
assert all(R.random_below(1) == 0 for _ in range(100))
assert R.random_int(7, 7) == 7
assert R.random_int(0, 0) == 0
assert R.random_bits(0) == 0
assert R.random_string(0, "abc") == ""
assert R.random_bytes(0) == b""
assert R.random_bit() in (0, 1)
@pytest.mark.parametrize("k", [1, 7, 8, 9, 16, 64, 128, 256])
def test_random_bits_range(k):
for _ in range(500):
v = R.random_bits(k)
assert isinstance(v, int) and 0 <= v < (1 << k)
def test_random_bytes_length_and_type():
for n in [0, 1, 16, 32, 1024]:
b = R.random_bytes(n)
assert isinstance(b, bytes) and len(b) == n
# ======================================================================
# 3. Error returns (err tuple, never raises)
# ======================================================================
def test_error_returns():
# negative / non-integer length
assert _is_err(R.random_bytes(-1))
assert _is_err(R.random_bytes("x"))
assert _is_err(R.random_bytes(1.5))
assert _is_err(R.random_bytes(True)) # bool does not count as int
# n < 1
assert _is_err(R.random_below(0))
assert _is_err(R.random_below(-5))
assert _is_err(R.random_below(2.0))
# a > b
assert _is_err(R.random_int(5, 1))
assert _is_err(R.random_int("a", 3))
# random_bits negative
assert _is_err(R.random_bits(-1))
# random_string
assert _is_err(R.random_string(-1, "ab"))
assert _is_err(R.random_string(5, ""))
assert _is_err(R.random_string(5, 123))
assert _is_err(R.random_string("x", "ab"))
# random_password
assert _is_err(R.random_password(0))
assert _is_err(R.random_password(-3))
assert _is_err(R.random_password("x"))
assert _is_err(R.random_password(8, upper=False, lower=False, digits=False, special=False))
assert _is_err(R.random_password(8, exclude=123))
assert _is_err(R.random_password(8, lower=True, upper=False, digits=False,
exclude="abcdefghijklmnopqrstuvwxyz"))
# token_*
assert _is_err(R.token_hex(-1))
assert _is_err(R.token_bytes(-1))
assert _is_err(R.token_urlsafe("x"))
# choice / sample
assert _is_err(R.random_choice([]))
assert _is_err(R.random_choice(123))
assert _is_err(R.random_sample([], 1))
assert _is_err(R.random_sample([1, 2], 5))
assert _is_err(R.random_sample([1, 2], -1))
assert _is_err(R.random_sample([1, 2], "x"))
def test_err_tuple_shape():
r = R.random_bytes(-1)
assert isinstance(r, tuple) and len(r) == 3
assert all(isinstance(x, str) for x in r)
assert r[0].startswith("PPYC_ERR_")
# ======================================================================
# 4. Token / string / password
# ======================================================================
def test_token_hex():
t = R.token_hex(16)
assert isinstance(t, str) and len(t) == 32
assert re.fullmatch(r"[0-9a-f]{32}", t)
assert len(R.token_hex()) == 64 # 32 bytes by default
assert R.token_hex(0) == ""
def test_token_bytes_and_urlsafe():
assert len(R.token_bytes()) == 32
assert len(R.token_bytes(8)) == 8 and isinstance(R.token_bytes(8), bytes)
u = R.token_urlsafe(16)
assert isinstance(u, str)
assert re.fullmatch(r"[A-Za-z0-9\-_]+", u)
assert "=" not in u
def test_random_string():
s = R.random_string(200, "abc")
assert len(s) == 200 and set(s) <= set("abc")
s2 = R.random_string(50, "0123456789")
assert set(s2) <= set("0123456789")
def test_random_password_strength():
pw = R.random_password(20, upper=True, lower=True, digits=True, special=True)
assert len(pw) == 20
assert any(c.isupper() for c in pw)
assert any(c.islower() for c in pw)
assert any(c.isdigit() for c in pw)
assert any(not c.isalnum() for c in pw)
# symbols-only category
pw2 = R.random_password(10, upper=False, lower=False, digits=False, special=True)
assert len(pw2) == 10 and all(not c.isalnum() for c in pw2)
# exclude takes effect
pw3 = R.random_password(50, exclude="abcABC")
assert not (set(pw3) & set("abcABC"))
# short length (pin style, digits only)
pw4 = R.random_password(6, upper=False, lower=False, digits=True)
assert len(pw4) == 6 and pw4.isdigit()
# ======================================================================
# 5. Uniqueness
# ======================================================================
def test_uniqueness_uuid4():
us = [R.random_uuid4() for _ in range(1000)]
assert len(set(us)) == 1000
def test_uniqueness_token_hex():
ts = [R.token_hex(16) for _ in range(1000)]
assert len(set(ts)) == 1000
def test_uniqueness_random_bytes():
bs = [R.random_bytes(16) for _ in range(1000)]
assert len(set(bs)) == 1000
def test_uuid4_format():
for _ in range(200):
u = R.random_uuid4()
m = re.fullmatch(
r"([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})",
u)
assert m, u
# version nibble = 4
assert u[14] == "4"
# variant nibble in 8,9,a,b
assert u[19] in "89ab"
# ======================================================================
# 6. Randomness comparison against os.urandom
# ======================================================================
def test_differs_from_os_urandom():
assert R.random_bytes(32) != os.urandom(32)
assert R.random_bytes(32) != R.random_bytes(32)
a = R.random_bytes(64)
b = R.random_bytes(64)
assert a != b and os.urandom(64) != a
# ======================================================================
# 7. choice / sample
# ======================================================================
def test_random_choice():
seq = [10, 20, 30, 40]
vals = {R.random_choice(seq) for _ in range(500)}
assert vals <= set(seq)
assert R.random_choice("abc") in "abc"
assert R.random_choice(range(5)) in range(5)
assert R.random_choice((1,)) == 1
def test_random_sample():
seq = list(range(20))
out = R.random_sample(seq, 5)
assert len(out) == 5
assert len(set(out)) == 5
assert set(out) <= set(seq)
assert R.random_sample(seq, 0) == []
assert sorted(R.random_sample(seq, 20)) == seq # k == n is a full permutation
# coverage: repeated sampling should cover different elements
seen = set()
for _ in range(50):
seen |= set(R.random_sample(seq, 3))
assert len(seen) > 10
# ======================================================================
# 8. Static check: must not use the non-cryptographic random module
# ======================================================================
def test_no_insecure_random_import():
text = open(R.__file__, encoding="utf-8").read()
assert not re.search(r"(?m)^\s*import\s+random\b", text)
assert not re.search(r"(?m)^\s*from\s+random\s+import\b", text)
assert not re.search(r"\brandom\.(random|randint|randrange|choice|shuffle|sample|getrandbits)\b", text)
def test_uses_os_urandom():
text = open(R.__file__, encoding="utf-8").read()
assert "os.urandom" in text