← Back to section · Tutorials & Labs
Property Tests for Crypto Code: Round-Trips, Tamper Detection and Randomness Sanity Checks
The scariest crypto bugs do not crash — they compute wrongly in silence: decryption returns garbage without complaint, or tampered ciphertext sails through. This tutorial writes assertion-only property tests for AES-GCM encryption — round-trip consistency, detection of any single-bit flip, different ciphertexts for the same plaintext, guaranteed failure under a wrong key — and explains why properties suit crypto code better than examples.
What this tutorial aims to do
Ordinary business code usually fails loudly when it is wrong; crypto code often fails in silence. Get the nonce generation wrong and encryption still runs; accidentally bypass the authentication-tag check and tampered ciphertext still “decrypts” successfully. Such bugs are invisible to the eye, because the wrong output looks exactly like the right output — both are incomprehensible bytes. This tutorial takes a different approach: test properties, not examples. A property is a universal statement that must hold for all inputs, such as “decrypting an encryption of any plaintext must restore it” or “altering any single bit of the ciphertext must make decryption fail”. We write a set of assertion-only property tests for AES-GCM from the cryptography library, with no test framework required; once the thinking is clear, the same tests move naturally into pytest for bulk runs.
First, an implementation worth testing
Before testing there must be an implementation worth testing. Below is a minimal but complete AES-GCM wrapper: a 32-byte key, a fresh 12-byte nonce from secrets on every encryption, the output formatted as nonce concatenated with the authenticated ciphertext, and decryption slicing the nonce back off before calling decrypt, where tampering surfaces as an InvalidTag exception from the library. It uses the AESGCM class from cryptography.hazmat.primitives.ciphers.aead, whose interface contract is a recommended 12-byte nonce and a third encrypt argument for additional authenticated data, which may be None.
import secrets
from cryptography.exceptions import InvalidTag
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
def encrypt(key: bytes, plaintext: bytes) -> bytes:
nonce = secrets.token_bytes(12) # fresh random nonce every time
return nonce + AESGCM(key).encrypt(nonce, plaintext, None)
def decrypt(key: bytes, blob: bytes) -> bytes:
nonce, ciphertext = blob[:12], blob[12:]
return AESGCM(key).decrypt(nonce, ciphertext, None)
KEY = AESGCM.generate_key(bit_length=256)
Three core properties
Property one, round-trip consistency: for any plaintext — the empty string, a single byte, long text, raw binary — decrypting its encryption must restore it byte for byte. Do not test only one or two friendly examples; deliberately construct boundary samples, because empty input most readily exposes length-handling bugs and inputs that exactly fill a block boundary most readily expose padding-class errors. Property two, tampering is always detected: flip every bit of the ciphertext (including the nonce region and the tag region) one at a time, and decryption must raise InvalidTag every single time; in practice, iterate over all byte positions and XOR each with the two masks 0x01 and 0x80 — a few hundred decryptions cost nothing. Property three, key isolation and unpredictability: decryption under a wrong key must fail, and encrypting the same plaintext twice under the same key must produce different ciphertexts, because the nonce is freshly random each time — this property stands guard specifically against nonce hard-coding and counter wraparound, the classic beginner errors.
def test_roundtrip():
samples = [b"", b"a", b"hello world", bytes(range(256)), b"x" * 10000]
for pt in samples:
assert decrypt(KEY, encrypt(KEY, pt)) == pt
def test_tamper_always_detected():
blob = encrypt(KEY, b"transfer 100 coins")
for i in range(len(blob)):
for mask in (0x01, 0x80):
mutated = bytearray(blob)
mutated[i] ^= mask
try:
decrypt(KEY, bytes(mutated))
except InvalidTag:
continue
raise AssertionError(f"tampering at byte {i} went undetected")
def test_wrong_key_and_fresh_nonce():
blob = encrypt(KEY, b"same plaintext")
other_key = AESGCM.generate_key(bit_length=256)
try:
decrypt(other_key, blob)
raise AssertionError("a wrong key somehow decrypted successfully")
except InvalidTag:
pass
assert encrypt(KEY, b"same plaintext") != encrypt(KEY, b"same plaintext")
test_roundtrip(); test_tamper_always_detected(); test_wrong_key_and_fresh_nonce()
print("all property tests passed")
What randomness sanity checks can and cannot do
You can add a layer of statistical sanity checks over random outputs: generate ten thousand tokens and assert they are all distinct; count how often each value from 0 to 255 appears in a long random byte string and assert that none is missing or wildly overrepresented. Such checks catch a class of real, historical beginner accidents — a random source accidentally wired to a counter, a hard-coded seed, bytes truncated by mistake. But the boundary must be stated plainly: sanity checks can only detect “obviously not random”; they can never prove “cryptographically unpredictable”. Data from an ordinary pseudorandom generator passes every statistical test with ease while still letting an attacker reconstruct its state from the output. The checks are therefore regression sentries: they stop a future edit from wiring the random source wrongly, and they do not certify security. Real randomness assurance comes from the discipline of the earlier tutorial — draw only from the operating system’s cryptographically secure source — and testing’s job here is merely to keep that discipline from being broken by accident.
Property tests are not only for symmetric encryption
The same thinking transfers to the code of the earlier tutorials, and it is worth naming each. The property of key exchange is “both sides necessarily compute the same secret”: generate two X25519 key pairs, assert that Alice’s exchange output equals Bob’s byte for byte, then assert that swapping in a third party’s public key necessarily changes the result — this test catches mispaired public keys and reversed serialization byte order, the subtle errors, at the first moment. The property of a hybrid KEM is “decapsulation necessarily restores the encapsulated secret, and flipping one bit of the ciphertext necessarily changes the decapsulated secret”: ML-KEM does not raise on a tampered ciphertext but returns a different secret (implicit rejection), so the assertion must change from “must throw” to “must be unequal” — writing the algorithm’s actual semantics into the test is precisely the value of the property approach. The property of password hashing is “the same password hashed twice necessarily differs (the salt is working), the correct password necessarily passes, and a wrong one is necessarily rejected”. The property of signature verification is “flipping one bit of the signature necessarily fails, and verifying against a different message necessarily fails”. Gather these properties into one test file and you hold a safety net spanning every cryptographic primitive you use; refactor internals only after running the net — performance tuning and interface polish earn their turn only once it passes.
Making property tests a habit
Finally, the methodology. When testing crypto code, list the properties before writing cases: almost every “must” and “must never” sentence in an algorithm specification translates directly into a property test — integrity becomes tamper detection, confidentiality becomes wrong-key failure and ciphertext unpredictability, usability becomes round-trip consistency. Rerun the whole property suite whenever you add a feature, bump a library version or touch a line of parameter handling; the tests are fast and dependency-free, the cheapest regression line you can hold. One more caution: passing property tests shows the implementation violates none of these properties; it says nothing about flaws in your protocol design — a key exchange without peer authentication is a design-layer problem no property test can catch. Tests guard the implementation, review guards the design, and neither line is optional.
Tags: PythonProperty TestingAES-GCMTesting