Matching Primitives to Security Requirements
Start from the requirement, not the algorithm: who may read, who may change, who may prove authorship. Map each need to a hash, MAC, authenticated cipher, signature or key exchange, and see each one succeed and fail in runnable Python.
Contentsand lesson path
On this page
- Why it matters
- Write the requirement before the algorithm
- See each primitive succeed and fail
- Integrity is not freshness: replay protection
- Check your understanding
- Apply it
- Review prompt
Lessons of Applied Cryptography
- Matching Primitives to Security Requirements Concept · 20 min
- Authenticated Encryption and Signatures in Code Worked example · 25 min
- Password Storage That Survives a Database Leak Lab · 25 min
- Key Lifecycle and Envelope Encryption Concept · 20 min
- Spotting Crypto Misuse and Planning for Post-Quantum Worked example · 20 min
- Applied Cryptography Check Knowledge check · 8 questions
What you will learn
- Select the right primitive (authenticated encryption, hash, MAC, digital signature or key exchange) for a stated security requirement and justify the choice.
01. Why it matters
Most cryptographic failures in real systems are not broken algorithms. They are correct algorithms used for the wrong job. A team "protects" a file by publishing its SHA-256 hash next to it, and an attacker who can change the file can change the hash too. Another team encrypts a cookie with AES so that users cannot edit it, but the mode they chose does not detect edits, so a user flips bits and becomes an administrator. A third signs webhooks with a key that every customer also holds, so any customer can forge messages for every other customer.
Each of these teams picked a real primitive. A primitive is a basic cryptographic building block, such as a hash function or a cipher. What went wrong was the match between the primitive and the requirement. This lesson gives you a habit that prevents that: before you choose an algorithm, write down what must stay true, who must be able to do something and, just as important, who must not. The primitive then follows almost mechanically.
You will use the Python package cryptography (pyca/cryptography), version 50.0.2, with Python 3.12. It is maintained, widely reviewed and wraps OpenSSL. The rule throughout the skill is the same: use a well-known library and its high-level APIs, and never invent your own scheme.
02. Write the requirement before the algorithm
Security requirements for data usually reduce to a few properties. Confidentiality means only intended parties can read the data. Integrity means a change to the data is detected. Authenticity means you know who produced the data. Non-repudiation is a stronger form of authenticity: a third party can be convinced that one specific key holder produced the data, because nobody else could have. Forward secrecy is a property of sessions: if a long-term key leaks later, recordings of old sessions stay unreadable.
The second half of every requirement is about keys, because keys decide who can do what. Ask three questions. Who must be able to create valid data? Who must be able to check it? Can those two groups share a secret, or must checking be possible without the power to create?
Here is how the answers point to a primitive:
- Hash (SHA-256, SHA-3): no key at all. Anyone can compute it, so it detects accidental change, or deliberate change only when the hash itself reaches you over a channel you already trust.
- MAC, a message authentication code (HMAC-SHA256): one shared secret key. Everyone who holds the key can both create and check tags, so it gives integrity and authenticity between parties that trust each other.
- Authenticated encryption, also called AEAD (AES-256-GCM, ChaCha20-Poly1305): one shared key that gives confidentiality and integrity together. Modern code should reach for this instead of a plain cipher.
- Digital signature (Ed25519, ECDSA P-256, RSA-PSS): a private key creates, a public key checks. Checking does not give the power to create, so many parties can verify and only one can sign. This is the only option here that gives non-repudiation.
- Key exchange (X25519, ECDH P-256): two parties each combine their own private key with the other side's public key and reach the same shared secret, which never crosses the network. With fresh keys per session, it gives forward secrecy. Compare RSA key transport, where one side encrypts a random session key to the other side's long-term RSA key: whoever obtains that RSA private key later can decrypt every recorded session, so it has no forward secrecy.
Two supporting tools appear everywhere. A CSPRNG, a cryptographically secure random number generator, produces keys, nonces and tokens that an attacker cannot predict; in Python that is secrets or os.urandom, never the random module. A KDF, a key derivation function such as HKDF, turns a shared secret into one or more keys of the right length and purpose.
03. See each primitive succeed and fail
The script below takes one payment order and an attacker's forged version of it, and runs both through each primitive. Watch which checks the attacker can pass. Set up a folder and a virtual environment first.
mkdir crypto-tour && cd crypto-tour
uv venv --python 3.12 .venv && source .venv/bin/activate
uv pip install "cryptography==50.0.2""""One requirement, one primitive: a tour with pyca/cryptography."""
import hashlib
import hmac
import os
from cryptography.exceptions import InvalidSignature, InvalidTag
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
order = b"pay 40 GBP to account 1234"
forged = b"pay 4000 GBP to account 6666"
def hash_check(message: bytes, digest: str) -> bool:
return hashlib.sha256(message).hexdigest() == digest
# 1. Hash: anyone can compute it, so an attacker sends a new hash with the forgery.
print("1 hash forged order + recomputed hash accepted:",
hash_check(forged, hashlib.sha256(forged).hexdigest()))
# 2. MAC: only holders of the shared key can produce a valid tag.
mac_key = os.urandom(32)
tag = hmac.new(mac_key, order, hashlib.sha256).digest()
guess = hmac.new(os.urandom(32), forged, hashlib.sha256).digest() # attacker lacks key
print("2 hmac real tag valid:",
hmac.compare_digest(tag, hmac.new(mac_key, order, hashlib.sha256).digest()))
print("2 hmac forged tag valid:",
hmac.compare_digest(guess, hmac.new(mac_key, forged, hashlib.sha256).digest()))
# 3. Signature: the private key signs, anyone with the public key verifies.
signing_key = Ed25519PrivateKey.generate()
public_key = signing_key.public_key()
signature = signing_key.sign(order)
public_key.verify(signature, order) # raises if invalid
print("3 sign genuine order verifies with the public key: True")
try:
public_key.verify(signature, forged)
except InvalidSignature:
print("3 sign forged order rejected: InvalidSignature")
# 4. AEAD: secrecy and tamper detection under one shared key.
aead_key = AESGCM.generate_key(bit_length=256)
nonce = os.urandom(12)
box = AESGCM(aead_key).encrypt(nonce, order, b"orders-v1")
flipped = bytes([box[0] ^ 1]) + box[1:]
try:
AESGCM(aead_key).decrypt(nonce, flipped, b"orders-v1")
except InvalidTag:
print("4 aead one flipped bit rejected: InvalidTag")
print("4 aead ciphertext is plaintext + 16-byte tag:", len(box) == len(order) + 16)
# 5. Key exchange: two parties derive the same key without sending it.
alice, bob = X25519PrivateKey.generate(), X25519PrivateKey.generate()
alice_shared = alice.exchange(bob.public_key())
bob_shared = bob.exchange(alice.public_key())
def session_key(shared: bytes) -> bytes:
return HKDF(algorithm=hashes.SHA256(), length=32, salt=None,
info=b"demo session v1").derive(shared)
print("5 x25519 both sides derive the same key:",
session_key(alice_shared) == session_key(bob_shared))python primitives.py1 hash forged order + recomputed hash accepted: True
2 hmac real tag valid: True
2 hmac forged tag valid: False
3 sign genuine order verifies with the public key: True
3 sign forged order rejected: InvalidSignature
4 aead one flipped bit rejected: InvalidTag
4 aead ciphertext is plaintext + 16-byte tag: True
5 x25519 both sides derive the same key: TrueLine 1 is the lesson of the opening story. The receiver computed SHA-256 correctly, but the attacker sent a new hash with the forged order, and nothing tied the hash to anyone. Line 2 shows the fix when both sides can share a secret: without mac_key, the attacker's tag does not match. Note hmac.compare_digest, which compares in constant time so that response timing does not leak how many bytes matched.
Line 3 is different in kind. The verifier only holds public_key. It can check the order but could never have produced the signature, which is why signatures suit software updates, signed documents and tokens that many services verify. Line 4 shows that AES-GCM output is the ciphertext plus a 16-byte authentication tag; change one bit and decryption refuses to return anything. Line 5 shows two parties reaching the same session key, after passing the raw X25519 output through HKDF, as the pyca documentation recommends.
One caution about line 5. A bare key exchange tells you that you share a key with someone, not with whom. An attacker in the middle can run one exchange with each side. Real protocols such as TLS 1.3 therefore sign the exchange with a long-term key, which is how the requirement "talk privately to the real server" combines two primitives.
04. Integrity is not freshness: replay protection
A valid MAC or signature proves a message is genuine. It does not prove the message is new. If an attacker records a genuine "payment succeeded" webhook, sending the same bytes again produces a genuine tag again. Defending against this is called replay protection, and it needs something in the signed data that changes: a timestamp checked against a short window, a unique message id remembered for at least that window, or a counter that must always increase. Protocols often combine two of them, because each has a weakness on its own: timestamps allow replays inside the window, and id caches are lost when an in-memory store restarts.
"""Verify a signed webhook and refuse replays (HMAC + timestamp + event id)."""
import hashlib
import hmac
SECRET = b"whsec-lab-only-not-a-real-secret"
TOLERANCE = 300 # seconds a message stays acceptable
seen_ids: set[str] = set() # production: a shared store with expiry, e.g. Redis
def sign(event_id: str, ts: int, body: bytes) -> str:
msg = f"{event_id}.{ts}.".encode() + body
return hmac.new(SECRET, msg, hashlib.sha256).hexdigest()
def verify(event_id: str, ts: int, body: bytes, sig: str, now: int) -> str:
if not hmac.compare_digest(sign(event_id, ts, body), sig):
return "reject: bad signature"
if abs(now - ts) > TOLERANCE:
return "reject: timestamp outside window"
if event_id in seen_ids:
return "reject: replayed event id"
seen_ids.add(event_id)
return "accept"
now = 1_790_000_000
body = b'{"type":"payment.succeeded","amount":4000}'
sig = sign("evt_001", now - 20, body)
print("fresh message ->", verify("evt_001", now - 20, body, sig, now))
print("same again ->", verify("evt_001", now - 20, body, sig, now + 5))
print("tampered body ->", verify("evt_001", now - 20, body.replace(b"4000", b"9000"),
sig, now))
old = sign("evt_002", now - 3600, body)
print("an hour old ->", verify("evt_002", now - 3600, body, old, now))python webhook.pyfresh message -> accept
same again -> reject: replayed event id
tampered body -> reject: bad signature
an hour old -> reject: timestamp outside windowThe order of checks matters. The signature is checked first, so unauthenticated input never reaches the id store, and an attacker cannot fill that store with junk ids. The timestamp and the event id are inside the signed message, so the attacker cannot move an old message into the window by editing its timestamp. The now value is fixed so the output is the same on every machine; a real receiver uses the current time and tolerates a little clock difference.
05. Check your understanding
06. Apply it
The skill project is a small file-encryption CLI. Before writing any code for it, write a one-page requirements table: one row per thing the CLI protects (file contents, file names, the master key, user passwords), and for each row the property needed, who creates, who checks, and the primitive you choose. Keep the table; you will extend it with key management in Key Lifecycle and Envelope Encryption.
07. Review prompt
Without looking back, write the three key questions you ask before choosing a primitive. Then explain in two sentences why a MAC cannot give non-repudiation but a signature can, and name two ways to stop a valid signed message from being replayed.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.