Cryptographic Hashing and Digital Signatures Questions
Cryptographic hash functions (collision resistance, preimage resistance), message authentication codes, and digital-signature schemes. Covers HMAC, signature verification, and how hashing underpins integrity, commitments, and authentication. Distinct from non-cryptographic hashing used in data structures.
A service signs messages built by concatenating fields without separators, say user || timestamp || amount. Demonstrate how two different sets of field values could produce the exact same concatenated string (and therefore the same signature), then propose a fix. What would you actually change about how these messages get serialized before signing, and what backward-compatibility issues would your fix create?
Sample Answer
Direct answer
Concatenating fields without separators throws away the boundary information between them, so the same byte string can come from more than one set of field values. Move a digit from the front of timestamp into the back of user and the concatenation is identical, which means the signature over it is identical too, even though the two field sets mean different things. The fix is to make the message a canonical, self-delimiting encoding before it is signed, most simply by length-prefixing every field, and the real cost of shipping that fix is a coordinated cutover with old signatures and old verifiers in the system at the same time.
Structured elaboration
Why the ambiguity exists. user || timestamp || amount with no separators is not really one message; it is three fields glued together with the split points thrown away. A verifier that reconstructs the signed bytes from parsed (user, timestamp, amount) values assumes there's exactly one way to split the string back into those three fields, but nothing in the byte string enforces that. Any two field sets that concatenate to the same string produce the same signature, because the signature was only ever over the concatenation, never over the field structure.
The fix. Replace the bare concatenation with a canonical, unambiguous serialization before signing. The standard tool is length-prefixing: encode each field as len(field) || field (for example a fixed-width 4-byte big-endian length followed by the field bytes) and concatenate those framed fields instead of the raw ones. Because the length is bound to the field, no rearrangement of byte boundaries can produce the same framed string from a different set of field values. Equivalent alternatives are a canonical structured encoding (protobuf, CBOR (Concise Binary Object Representation, a compact binary JSON-like encoding), or JSON with a fixed key order and no field values that can contain the delimiter) or a fixed-width encoding, if the field domains are bounded (a Unix timestamp always fits a fixed number of digits, for instance).
Backward compatibility. Changing the wire format breaks verification for anything already relying on the old bare concatenation. In practice this needs: an explicit scheme-version byte or field carried alongside the signature (so verifiers can tell old-format signatures from new-format ones and apply the matching canonicalization), a dual-verify window where the service accepts both formats while clients and stored signatures migrate, and an expiry date after which the old, ambiguous format is rejected outright. Anything that pre-signed messages under the old scheme (queued jobs, long-lived tokens, offline-signed batches) has to be re-signed or grandfathered explicitly rather than silently reinterpreted, because reinterpreting old bytes under the new canonicalization rules is exactly the kind of parsing ambiguity this fix is trying to eliminate.
Worked example
Two field sets that collide under the naive scheme:
Set A: user="bob", timestamp="1699999999", amount="50"
Set B: user="bob1", timestamp="699999999", amount="50"
import hmac, hashlib
KEY = b"pinned-demo-key"
def sign(user, timestamp, amount):
message = user + timestamp + amount
return message, hmac.new(KEY, message.encode(), hashlib.sha256).hexdigest()
concat_a, sig_a = sign("bob", "1699999999", "50")
concat_b, sig_b = sign("bob1", "699999999", "50")
print("concat_a == concat_b:", concat_a == concat_b, " sig_a == sig_b:", sig_a == sig_b)
print("sig_a:", sig_a)
def sign_fixed(user, timestamp, amount):
def framed(field):
b = field.encode()
return len(b).to_bytes(4, "big") + b
message = framed(user) + framed(timestamp) + framed(amount)
return message, hmac.new(KEY, message, hashlib.sha256).hexdigest()
fixed_a = sign_fixed("bob", "1699999999", "50")
fixed_b = sign_fixed("bob1", "699999999", "50")
print("framed_a == framed_b:", fixed_a[0] == fixed_b[0], " sig_a == sig_b (fixed):", fixed_a[1] == fixed_b[1])
print("sig_a (fixed):", fixed_a[1])
print("sig_b (fixed):", fixed_b[1])
Running this prints concat_a == concat_b: True sig_a == sig_b: True: concat_a and concat_b are both the literal string "bob169999999950", and the HMAC (Hash-based Message Authentication Code, a keyed construction that turns a hash function into a tag only someone holding the secret key can produce) over them is bit-for-bit identical, 7fdf7a5e9f5a0c17391868dc99f7d4e59733e01f508be32f9c136b9f62200475 in both cases. Applying the length-prefix fix flips both results to False: the framed messages differ (the length prefix on "bob" versus "bob1" diverges immediately), and the two signatures come out different, e6c2dcc3ce33b7eb3403189d7b8451905a8b53568145d06d2efa4e0494609c24 versus 2e4a6a43def8267dfb655fe02e3618d5a76d483773b7cb6f7b2c3eca923c229e.
Trade-offs and pitfalls
Length-prefixing is cheap and fully general but is not the only valid fix: a structured, canonical encoding buys the same guarantee and often better tooling support (schema validation, cross-language libraries), at the cost of a heavier format. A single separator character (like |) is a tempting shortcut but only works if the field values are guaranteed never to contain that character; if user can ever include a pipe, you have reinvented the same ambiguity one layer down. The migration is the part most teams underestimate: it is easy to fix the signer and forget that every downstream verifier, cached signature, or replayable message needs to agree on which format it is looking at, and a silent format-detection heuristic (guessing whether a message is old or new style) reintroduces exactly the kind of ambiguity you were trying to remove.
What is a Merkle tree, and how does a Merkle proof let you verify that a single leaf belongs to a committed root without holding the whole dataset? Name two real-world systems that rely on this structure and explain what they'd lose without it.
Sample Answer
Direct answer
A Merkle tree is a binary tree in which every leaf is the hash of one data record and every internal node is the hash of its two children, so a single hash at the top, the root, commits to the entire dataset at once. A Merkle proof lets you prove that one specific leaf belongs under a given root by revealing only the sibling hashes along the path from that leaf up to the root, a number that grows logarithmically with the dataset size, letting a verifier recompute the same root without ever seeing the rest of the data.
Structured elaboration
Building the tree. Each leaf is leaf_i = H(data_i). Each parent is H(left_child || right_child). This repeats level by level until a single root remains. Real systems tag which KIND of thing is being hashed, for instance leaf = H(0x00 || data) and internal node = H(0x01 || left || right), so an attacker can't pass an internal node's hash off as if it were itself a valid leaf. Skipping this domain separation opens a real, if narrow, forgery.
Producing and checking a proof. To prove leaf_i is included, the prover supplies leaf_i's data plus exactly one sibling hash per level on the path up to the root, never the whole tree. The verifier recomputes the hash bottom-up using the supplied siblings and checks that the final result equals the trusted root.
Why the proof is logarithmic in size. A tree with n leaves has depth roughly log base 2 of n, and the proof needs exactly one sibling hash per level, so both proof size and verification cost grow with the LOG of the dataset size, not linearly with it.
Odd leaf counts. An unbalanced level, for example five leaves at the bottom, needs an explicit, specified rule, commonly duplicating the last node upward. This isn't a cosmetic detail: the exact rule must be fixed and applied consistently, since an ambiguous or inconsistently-implemented rule is itself a source of proof-forgery bugs.
Worked example
import hashlib
def H(data: bytes) -> bytes:
return hashlib.sha256(data).digest()
def leaf_hash(data: bytes) -> bytes:
return H(b'\x00' + data)
def node_hash(left: bytes, right: bytes) -> bytes:
return H(b'\x01' + left + right)
def build_tree(leaves_data):
level = [leaf_hash(d) for d in leaves_data]
levels = [level]
while len(level) > 1:
if len(level) % 2 == 1:
level = level + [level[-1]]
level = [node_hash(level[i], level[i+1]) for i in range(0, len(level), 2)]
levels.append(level)
return levels
def proof_for(levels, index):
proof = []
for level in levels[:-1]:
if index % 2 == 1:
proof.append(('L', level[index - 1]))
else:
sib = index + 1 if index + 1 < len(level) else index
proof.append(('R', level[sib]))
index //= 2
return proof
def verify_proof(leaf_data, proof, root):
h = leaf_hash(leaf_data)
for side, sib in proof:
h = node_hash(sib, h) if side == 'L' else node_hash(h, sib)
return h == root
records = [b'txn-A: alice pays bob 10', b'txn-B: bob pays carol 5',
b'txn-C: carol pays dave 2', b'txn-D: dave pays alice 7',
b'txn-E: alice pays carol 1'] # odd count, exercises the duplicate-last-leaf rule
levels = build_tree(records)
root = levels[-1][0]
print('root =', root.hex())
target = 2
proof = proof_for(levels, target)
print('proof for leaf', target, 'has', len(proof), 'sibling hashes')
print('proof verifies?', verify_proof(records[target], proof, root))
print('tamper check (wrong content) verifies?', verify_proof(b'txn-C: carol pays dave 999', proof, root))
Output:
root = 0cf284c5f722737591a9b62df8a344ce1e6cc04630455eea27e54fe193ae7010
proof for leaf 2 has 3 sibling hashes
proof verifies? True
tamper check (wrong content) verifies? False
Five records need ceil(log2 5) = 3 sibling hashes per proof, matching what the code returns, and a proof over tampered content correctly fails.
Real-world systems and what they'd lose without this structure. Git's object model is content-addressed, and commits chain through hashes of trees, which are themselves Merkle-like structures over the repository's file layout. Without it, git would have no cheap way to know exactly which subtrees changed between two commits or to verify history's integrity without re-hashing the entire repository on every check. Certificate Transparency logs, the public append-only logs of every issued TLS certificate, use Merkle trees so any monitor can get a compact proof that a specific certificate is definitely in the public log, and a compact proof that the log grew consistently without being silently rewritten, without downloading the entire log. Without Merkle structure, auditing the whole Certificate Transparency ecosystem would require trusting each log operator outright or downloading everything ever logged for every single check.
Trade-offs and pitfalls
- Leaf and internal-node domain separation, the tagging shown above, is not decoration. Without it, an attacker can sometimes pass a two-child internal node's hash off as if it were itself a valid leaf, a second-preimage-style forgery against a naive, untagged tree.
- Sparse Merkle trees and Merkle Patricia tries trade away this simple structure for efficient non-membership proofs and key-value semantics, at real added implementation complexity. Reach for them only when you actually need to prove something is absent, not merely present.
- Proof size depends on a leaf's depth, so a pathologically unbalanced tree can make some proofs much larger than the ceil(log2 n) siblings a balanced tree would need; tree construction should keep the tree reasonably balanced.
In Python using the 'cryptography' library, write a function sign_message_rsa_pss(private_pem: bytes, message: bytes) -> bytes that computes SHA-256 over the message and returns an RSA-PSS signature. Also provide a short verification snippet showing how to verify the signature. Focus on correct padding parameters and hash selection; you may omit file I/O and error handling boilerplate.
Sample Answer
Approach
Use the cryptography library's high-level sign and verify methods with RSA-PSS (Probabilistic Signature Scheme) padding and SHA-256 (part of the SHA, Secure Hash Algorithm, family), letting the library handle the actual RSA and hash math internally. The three parameters that must match exactly between signer and verifier are the message-hash algorithm (SHA-256), the mask-generation function's hash (MGF1 using SHA-256, matching the message hash is the standard convention), and the salt length (here, set equal to the hash's own digest size, 32 bytes, a common recommended default).
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import padding, rsa
def sign_message_rsa_pss(private_pem: bytes, message: bytes) -> bytes:
private_key = serialization.load_pem_private_key(private_pem, password=None)
return private_key.sign(
message,
padding.PSS(
mgf=padding.MGF1(hashes.SHA256()),
salt_length=hashes.SHA256().digest_size, # 32 bytes
),
hashes.SHA256(),
)
def verify_message_rsa_pss(public_pem: bytes, message: bytes, signature: bytes) -> bool:
public_key = serialization.load_pem_public_key(public_pem)
try:
public_key.verify(
signature, message,
padding.PSS(
mgf=padding.MGF1(hashes.SHA256()),
salt_length=hashes.SHA256().digest_size,
),
hashes.SHA256(),
)
return True
except Exception:
return False
if __name__ == '__main__':
key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
priv_pem = key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.NoEncryption())
pub_pem = key.public_key().public_bytes(serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo)
message = b"transfer 100 credits to account 42"
sig = sign_message_rsa_pss(priv_pem, message)
print("signature length (bytes):", len(sig))
print("verify(correct message) :", verify_message_rsa_pss(pub_pem, message, sig))
print("verify(tampered message) :", verify_message_rsa_pss(pub_pem, message + b"!", sig))
Output:
signature length (bytes): 256
verify(correct message) : True
verify(tampered message) : False
Key points
- RSA-PSS is a RANDOMIZED padding scheme (a random salt is mixed in through the mask-generation function), unlike the older, deterministic PKCS#1 v1.5 padding; randomization gives PSS a stronger, more modern security proof, and it's the currently recommended RSA signature padding for new systems.
- The private key is loaded once from PEM bytes, and
.sign()returns raw signature bytes directly. Verification loads the PUBLIC key and calls.verify(), which RAISES an exception on failure rather than returning a boolean; swallowing that exception incorrectly, or treating "no exception" as the only success signal without confirming verify was actually called, is a common integration mistake. - Constant-time verification is handled internally by the library, not something the caller needs to implement, unlike a hand-rolled MAC (Message Authentication Code) comparison; never hand-implement RSA padding.
Complexity
RSA sign and verify cost is dominated by modular exponentiation over the key's modulus. For a fixed key size this cost doesn't depend on message length beyond the initial hashing pass, since the message is compressed to a fixed-size digest before any RSA math happens; signing (the private-key operation, using the full-size exponent) is meaningfully more expensive than verifying (the public-key operation, which typically uses a small exponent such as 65537).
Edge cases
- A message longer than the modulus is a non-issue here, unlike raw RSA encryption of long data, precisely because the message is hashed to a fixed size before being signed.
- A passphrase-protected private key needs that passphrase passed to
password=instead ofNone; the shown code assumes an unencrypted key. - Verifying with the WRONG public key fails closed, by raising, not by returning False silently; calling code must catch that exception path explicitly rather than assuming a boolean return.
- PSS's randomized salt means signing the SAME message twice with the SAME key produces two DIFFERENT valid signature byte strings. This is expected and correct, not a bug; don't assume signature reproducibility for any purpose that needs it, such as content-addressing.
You're building a cache-key generator for a CDN, and a teammate suggests reusing the same fast hash function for hashing user passwords too, to keep the codebase simple. How would you respond, and what's the real boundary between a general-purpose hash like MurmurHash and a cryptographic hash function? Give three situations where a non-cryptographic hash is perfectly fine and three where using one would be a serious mistake.
Sample Answer
Direct answer
I'd push back on reusing the same fast hash for both cache keys and passwords: speed is exactly the property you want for a cache key generator and exactly the property you must NOT want for password hashing, because speed is what lets an attacker try billions of password guesses per second against a stolen database. The real boundary isn't "cryptographic hashes are better," it's whether an adversary controls or benefits from the input or the output. A general-purpose hash like MurmurHash is optimized assuming no adversary is present; a cryptographic hash like SHA-256 (part of the SHA, Secure Hash Algorithm, family) is built assuming a motivated one is.
Structured elaboration
Definitions. MurmurHash is a family of non-cryptographic hash functions designed for speed and a good, even distribution of outputs, originally built for hash tables and checksums. A cryptographic hash function additionally has to survive an adversary who is actively trying to break it: preimage resistance (given a digest, you can't find an input that produces it), second-preimage resistance (given one input, you can't find a different input with the same digest), and collision resistance (you can't find any two distinct inputs, of your own choosing, that produce the same digest). MurmurHash provides none of these against a motivated attacker; SHA-256 is designed and studied specifically to provide all three.
Three situations where a non-cryptographic hash is perfectly fine (no adversary, or a collision only costs a little accuracy, not security):
- In-process hash tables or maps keyed by data the caller controls internally, not data supplied over a network by an untrusted party.
- Probabilistic data structures such as Bloom filters or HyperLogLog, used for approximate counting, where an occasional collision only slightly degrades accuracy rather than breaking a security property.
- Sharding or partitioning keys for a cache or a distributed system, where the goal is even distribution across nodes, not resistance to a deliberate adversary (with the caveat below about attacker-supplied keys).
Three situations where using one would be a serious mistake:
- Password storage. A fast hash lets an attacker who steals the password database try enormous numbers of candidate passwords per second offline; a password hash needs to be deliberately slow and memory-hard instead, using a KDF (key derivation function) such as bcrypt, scrypt, Argon2, or PBKDF2.
- Message authentication or integrity checks against an adversary, such as verifying a downloaded file or a signed API request. Collision and preimage resistance are exactly what stop forgery here, and MurmurHash offers neither.
- Any hash table exposed to attacker-controlled keys over a network, such as a web server hashing request parameters into an internal table. A known non-cryptographic hash lets an attacker craft many inputs that collide on purpose, degrading the table toward a linked list and causing an algorithmic-complexity denial-of-service, sometimes called hash flooding.
Worked example
The clearest way to see the password-hashing mistake in concrete numbers is to look at what a KDF's iteration count actually buys you, since that number multiplies attacker cost directly and doesn't depend on wall-clock benchmarking. Suppose a team configures PBKDF2, one of the KDFs named above, with, as one illustrative configuration, N = 100,000 iterations, versus hashing the password once with a fast hash like SHA-256:
- Fast hash (1 iteration): testing a 10,000,000-entry common-password wordlist against a stolen digest costs 10,000,000 hash evaluations.
- KDF at N = 100,000 iterations: the SAME wordlist costs 10,000,000 times 100,000 = 1,000,000,000,000 (one trillion) hash evaluations, because every single guess now has to pay the full iteration count, not just one hash call.
That multiplier applies uniformly whether the attacker has one laptop or a warehouse of GPUs; it's a property of the KDF's design, not of any particular attacker's hardware. A fast hash like MurmurHash has no equivalent knob at all: it was never designed to be slow, so there is no "iteration count" to raise.
Trade-offs and pitfalls
- "Non-cryptographic" doesn't mean "insecure everywhere," it means "not designed for an adversarial threat model." Using SHA-256 for a purely internal hash table works correctly but burns CPU cycles for no security benefit, which is a legitimate but different critique from the password-hashing mistake above.
- Watch for the middle ground: a hash-flood-resistant non-cryptographic hash, such as SipHash, exists specifically because "just use a full cryptographic hash for indexing" is often overkill. SipHash is fast AND keyed, which is the real fix for hash-flooding, not full collision resistance.
- Document the boundary explicitly in code and API naming, rather than relying on tribal knowledge. Naming functions distinctly, for example hash_for_indexing() versus hash_for_password_storage(), prevents exactly this kind of accidental reuse from recurring later.
Walk through how you'd implement signature verification for a client-server API using JSON Web Signatures (JWS). What are the concrete ways this commonly goes wrong in production code, and how would you guard against algorithm confusion, replay of an old but validly-signed request, and any subtleties around exactly what bytes get hashed and signed?
Sample Answer
Direct answer
I'd build a JWS (JSON Web Signature) verifier around three rules: never let the token's own header choose the verification algorithm, always check the signature against the exact bytes that were transmitted rather than a re-parsed version, and always check freshness separately from validity, since a signature only proves who signed something and that it wasn't altered, not that it's still supposed to be accepted right now. Production JWS bugs cluster around exactly the places where the verifier trusts something the ATTACKER controls: the algorithm name in the header, a stale but validly-signed token being replayed, or ambiguity about which bytes were actually hashed and signed.
Structured elaboration
Glossary. JWS (JSON Web Signature) is a standard for representing a signed JSON payload as a compact, base64url-encoded string in the form header.payload.signature. JWT (JSON Web Token) is the common special case where the payload holds a set of identity or authorization claims.
Algorithm confusion. The JWS header includes an "alg" field that the TOKEN ITSELF supplies. If a verifier is configured to accept multiple algorithms and blindly uses whichever one the token names, an attacker can often exploit the gap between an asymmetric and a symmetric algorithm specifically. For example, a server that verifies RS256 tokens (RSA signatures, asymmetric) using a public key, but is ALSO configured to accept HS256 (HMAC, Hash-based Message Authentication Code, a symmetric construction) using that SAME key value as the verification argument, lets an attacker who merely knows the public key, which is intentionally public, forge an HS256-"signed" token: HMAC only needs some shared secret bytes, and the public key's own PEM string works fine as one. The fix is to pin exactly one expected algorithm per verification context and never let the token select it.
Replay of an old but validly-signed request. A signature proves who signed something and that it wasn't altered; it says nothing about WHEN it's still valid to accept. The mitigation is to embed and check an expiry claim and an issued-at claim with a small allowed clock-skew window, plus a unique nonce or token identifier tracked server-side in a short-lived store, so a given token can't be replayed a second time within its own validity window.
Exactly what bytes get hashed and signed. JWS signs the base64url-encoded header and payload CONCATENATED WITH A LITERAL PERIOD CHARACTER, not the raw, re-parsed JSON object. If a verifier re-serializes the JSON, for instance re-encoding fields in a different key order or with different whitespace, before checking the signature, instead of checking it against the exact bytes that were transmitted, it can accept a token whose claims were subtly altered after signing, provided the alteration happens to normalize back to something matching after re-serialization.
Worked example
Here is the algorithm-confusion attack end to end, using a real RSA keypair and a real JWS library, showing a vulnerable verifier accept a forged token and a correctly pinned verifier reject it.
import json, hmac, hashlib, base64
import jwt
from cryptography.hazmat.primitives import serialization, hashes
from cryptography.hazmat.primitives.asymmetric import rsa, padding
def b64u(data: bytes) -> str:
return base64.urlsafe_b64encode(data).rstrip(b'=').decode()
def b64u_decode(s: str) -> bytes:
return base64.urlsafe_b64decode(s + '=' * (-len(s) % 4))
# server: RSA keypair, signs with RS256, publishes the PUBLIC key (e.g. via a JWKS endpoint)
key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
priv_pem = key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.NoEncryption())
pub_pem = key.public_key().public_bytes(serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo)
legit_token = jwt.encode({"sub": "alice", "role": "user"}, priv_pem, algorithm="RS256")
# VULNERABLE verifier: trusts the token's own "alg" header, reuses the SAME key bytes either way
def vulnerable_verify(token: str, verification_key: bytes):
header_b64, payload_b64, sig_b64 = token.split('.')
header = json.loads(b64u_decode(header_b64))
signing_input = f"{header_b64}.{payload_b64}".encode()
sig = b64u_decode(sig_b64)
if header["alg"] == "HS256":
expected = hmac.new(verification_key, signing_input, hashlib.sha256).digest()
if not hmac.compare_digest(expected, sig):
raise ValueError("bad HS256 signature")
elif header["alg"] == "RS256":
pub = serialization.load_pem_public_key(verification_key)
pub.verify(sig, signing_input, padding.PKCS1v15(), hashes.SHA256())
else:
raise ValueError("unsupported alg")
return json.loads(b64u_decode(payload_b64))
print("legit RS256 token verifies:", vulnerable_verify(legit_token, pub_pem)["role"] == "user")
# attacker: no private key, but the public key IS public by design; forge an HS256 token
# using the public-key PEM bytes as the HMAC secret
header = {"alg": "HS256", "typ": "JWT"}
payload = {"sub": "alice", "role": "admin"}
signing_input = f"{b64u(json.dumps(header, separators=(',', ':')).encode())}.{b64u(json.dumps(payload, separators=(',', ':')).encode())}"
forged_sig = hmac.new(pub_pem, signing_input.encode(), hashlib.sha256).digest()
forged_token = f"{signing_input}.{b64u(forged_sig)}"
try:
result = vulnerable_verify(forged_token, pub_pem)
print("FORGED token accepted by vulnerable verifier! role =", result["role"])
except Exception as e:
print("forged token rejected:", e)
# FIXED verifier: pins ONE expected algorithm; PyJWT also independently refuses to use a
# PEM-shaped key for HS256, a defense added specifically against this bug class
def fixed_verify(token):
return jwt.decode(token, pub_pem, algorithms=["RS256"])
try:
fixed_verify(forged_token)
print("FIXED verifier: forgery accepted (BUG)")
except jwt.InvalidTokenError as e:
print("FIXED verifier correctly rejects the forged token:", type(e).__name__)
Output:
legit RS256 token verifies: True
FORGED token accepted by vulnerable verifier! role = admin
FIXED verifier correctly rejects the forged token: InvalidAlgorithmError
The vulnerable verifier escalates the attacker from "user" to "admin" using only the public key, which was never secret in the first place. Pinning the algorithm closes the hole entirely. Worth noting: PyJWT itself independently refuses to use a PEM-shaped key as an HMAC secret, a guard added specifically because this exact bug class was common enough in real deployments to justify hardening the library itself.
Trade-offs and pitfalls
- "Accept multiple algorithms for flexibility" is almost always the wrong trade. Pin one algorithm per key or context; if you genuinely need to rotate algorithms, select a specific known key-and-algorithm pair via a key identifier looked up from a server-side allowlist, never from attacker-supplied header content alone.
- A replay window sized to be "generous for clock skew" is a real, live trade-off: too tight and legitimate clients with slightly-off clocks get rejected, too loose and a captured token stays exploitable for longer. There's no universally correct number; size it to your actually observed clock drift plus a safety margin, and prefer short-lived tokens over a large skew window.
- Signing the raw transmitted bytes exactly, rather than a re-serialized or re-parsed version, avoids a whole class of canonicalization-mismatch bugs, but requires the client, server, and any intermediary to agree on byte-for-byte fidelity in transit; don't let a proxy "prettify" JSON along the way.
Unlock Full Question Bank
Get access to all 8 Cryptographic Hashing and Digital Signatures interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.