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.
What is signature malleability, and why does it matter for systems like blockchains, multi-signature protocols, or anything that derives a transaction identifier from the signature itself? Show concretely how an attacker could take a valid ECDSA signature (r, s) and produce a second, different-looking signature that still verifies for the exact same message.
Sample Answer
Direct answer
Signature malleability means a valid signature can be transformed into a DIFFERENT byte string that still verifies successfully for the exact same message and key, breaking the assumption that one message and one key implies one canonical signature. For ECDSA (Elliptic Curve Digital Signature Algorithm) specifically, given any valid signature (r, s), the pair (r, n minus s), where n is the curve's order, is ALSO a valid signature for the identical message. The verification equation only ever depends on s through quantities that come out the same for s and its negation modulo n.
Structured elaboration
Deriving why (r, n - s) also verifies. ECDSA verification recovers a point X = u1 times G plus u2 times Q, where u1 = z times s inverse mod n and u2 = r times s inverse mod n, and accepts if X's x-coordinate mod n equals r. Flipping s to n - s is the same as flipping its sign modulo n, since (n - s) is congruent to -s (mod n). Modular inverse distributes over negation:
(n−s)−1≡−(s−1)(modn)That negates BOTH u1 and u2 together, which negates the resulting point X itself: scalar-multiplying a point by a negative amount reflects it, flipping only its y-coordinate and leaving its x-coordinate unchanged. Since verification only checks X's x-coordinate against r, the check passes identically for s and for n - s.
Why it matters for systems that derive an identifier from the signature. If a system computes something like a transaction identifier as a hash of the signature bytes themselves, an attacker, or even an honest but uncoordinated relayer, can flip s to n - s, producing a DIFFERENT valid signature for the IDENTICAL, unmodified transaction. That changes the derived identifier without changing anything the signer actually authorized, breaking any assumption that this identifier uniquely names one authorized action, which historically mattered for tracking unconfirmed transactions before they were finalized.
Multi-signature protocols. Combining or aggregating multiple parties' signatures often assumes each party contributes exactly one canonical value. A malleable component lets one party, or an outside relayer, silently substitute an equally-valid variant, complicating aggregation logic and, in some protocol designs, opening the door to more subtle rogue-key or substitution issues if malleability isn't explicitly accounted for in the protocol's own security proof.
Worked example
Using the same small, hand-checkable toy curve as a basic ECDSA walk-through (NOT a real or secure curve): y squared = x cubed + 5x + 3, mod 23, base point G = (11, 3), curve order n = 23.
def ec_add(P, Q, a, p):
if P is None: return Q
if Q is None: return P
x1, y1 = P; x2, y2 = Q
if x1 == x2 and (y1 + y2) % p == 0:
return None
if P == Q:
lam = (3*x1*x1 + a) * pow(2*y1, -1, p) % p
else:
lam = (y2 - y1) * pow((x2 - x1) % p, -1, p) % p
x3 = (lam*lam - x1 - x2) % p
y3 = (lam*(x1 - x3) - y1) % p
return (x3, y3)
def ec_mul(k, P, a, p):
R, Q = None, P
while k > 0:
if k & 1: R = ec_add(R, Q, a, p)
Q = ec_add(Q, Q, a, p)
k >>= 1
return R
p, a, b, n = 23, 5, 3, 23
G = (11, 3)
def sign(d, k, z):
R = ec_mul(k, G, a, p)
r = R[0] % n
s = (pow(k, -1, n) * (z + r * d)) % n
return r, s
def verify(Q, z, r, s):
w = pow(s, -1, n)
u1, u2 = (z * w) % n, (r * w) % n
X = ec_add(ec_mul(u1, G, a, p), ec_mul(u2, Q, a, p), a, p)
return X is not None and X[0] % n == r
d, k, z = 7, 4, 15
Q = ec_mul(d, G, a, p)
r, s = sign(d, k, z)
s_prime = (n - s) % n
print('original signature (r, s) =', (r, s), ' verifies?', verify(Q, z, r, s))
print("malleated signature (r, s') =", (r, s_prime), ' verifies?', verify(Q, z, r, s_prime))
print('s + s_prime mod n == 0 ?', (s + s_prime) % n == 0)
print('low-S canonical rule would keep s =', min(s, s_prime), 'and reject s =', max(s, s_prime))
Output:
original signature (r, s) = (10, 4) verifies? True
malleated signature (r, s') = (10, 19) verifies? True
s + s_prime mod n == 0 ? True
low-S canonical rule would keep s = 4 and reject s = 19
Both (10, 4) and (10, 19) verify successfully for the identical message, using the identical public key, exactly as the algebra above predicts.
Trade-offs and pitfalls
- The standard mitigation is NOT changing the signature algorithm itself, but enforcing a canonical form at the protocol or application layer: require s to be at most n divided by 2 (the low-S rule) and reject any signature where s is larger, cutting the two malleable variants down to exactly one canonical choice. Bitcoin adopted exactly this rule as its practical fix.
- Malleability is not a way to steal funds or forge a NEW authorization; the attacker still needs an already-valid signature to mutate. It's a way to create a cosmetically different but equally valid encoding of an EXISTING authorization, a narrower but still protocol-breaking issue depending on what assumptions were built on top of "the signature bytes are stable."
- EdDSA and Schnorr-style signatures were designed with a canonical, unique encoding in mind specifically to avoid this class of issue by construction, rather than requiring an external convention like "always pick low-S" bolted on afterward, a real design-maturity difference from ECDSA.
- RSA signatures have their own, distinct historical malleability and forgery concerns under older, now-deprecated padding schemes; malleability isn't a single universal property, it's scheme-specific and must be checked per algorithm.
Compare SHA-256, SHA-3, and BLAKE2 for a new cloud service that needs fast content hashing and occasional authenticated signing. Walk through the internal design differences that matter for your choice, how they affect performance in software and hardware, and which one you'd pick and why.
Sample Answer
Direct answer
For a cloud service that needs fast content hashing with occasional authenticated signing, I'd pick BLAKE2 as the primary workhorse: it's designed specifically for high software throughput and offers a native keyed mode that covers the occasional-signing need without a separate wrapper construction. SHA-256 (part of the SHA, Secure Hash Algorithm, family) stays valuable where hardware acceleration or broad interoperability matters more than raw software speed, and SHA-3 is worth reaching for specifically when structural diversity from SHA-2 is itself a requirement, not just a nice-to-have.
Structured elaboration
Internal design. SHA-256 is a Merkle-Damgard construction using Davies-Meyer compression (each step runs the running state through a block-cipher-like function keyed by that message block, then XORs, or "feeds forward," the original input state back into the result; that feed-forward is specifically what turns an otherwise-invertible cipher-like step into a one-way compression function): a sequential running state, processed block by block, with the final state as the output. This is exactly the structure that makes plain H(secret || message) vulnerable to length-extension unless wrapped in HMAC (Hash-based Message Authentication Code). SHA-3 (Keccak) is a completely different family, built on a sponge construction: input is absorbed into a large internal state, then output is squeezed back out; because the digest doesn't reveal the FULL internal state, SHA-3 doesn't have the length-extension weakness by construction, independent of any external MAC wrapper. BLAKE2 descends from BLAKE, a SHA-3 competition finalist, and uses an ARX (add-rotate-xor) permutation in the spirit of ChaCha, layered with an explicit block counter and optional salt and personalization inputs that also close the length-extension weakness structurally, by a different route than SHA-3's.
Performance in software versus hardware. SHA-256 benefits enormously from dedicated hardware acceleration available on many modern CPUs, and is extremely fast when that hardware path exists, but is comparatively slower in pure software on hardware lacking it. SHA-3's sponge permutation suits hardware implementations well (compact circuits, flexible security and speed trade-offs via its rate and capacity split, where "rate" is the portion of the sponge's fixed-width internal state that gets absorbed from input and squeezed out as output each round, controlling speed, and "capacity" is the remaining portion that input and output never touch and that holds the security margin, so widening the rate speeds things up while widening the capacity strengthens security, each at the other's expense), but tends to be the slowest of the three in general-purpose software absent dedicated hardware. BLAKE2 was explicitly designed to outperform SHA-256 in pure software on ordinary CPUs, using fewer, SIMD-friendly operations per byte, without requiring any special hardware support.
Security posture. All three currently have no practically exploitable collision or preimage attacks; their cryptanalytic status is "actively studied and currently unbroken," not "mathematically proven safe forever." SHA-3's structural break from Merkle-Damgard is often cited as valuable algorithmic diversity: SHA-2 and SHA-3 don't share the same internal design, so a future attack targeting one family's specific weaknesses wouldn't automatically threaten the other, a real operational hedge for infrastructure that wants to survive a hypothetical break in one family without a full re-architecture.
Signature-relevance for this scenario. Since the scenario needs occasional authenticated signing too, BLAKE2's native keyed mode gives a fast, standardized way to do keyed hashing directly, without strictly requiring a separate HMAC wrapper (an HMAC-BLAKE2 construction also exists and works fine if a standard MAC construction is specifically required by policy). Both SHA-256 and SHA-3 rely on HMAC, or for SHA-3 the standardized KMAC construction, for keyed use; BLAKE2's built-in support is a genuine, primitive-level convenience the other two don't offer natively.
Worked example
import hashlib
msg = b'content-hash-me-2026'
print('SHA-256 :', hashlib.sha256(msg).hexdigest())
print('SHA3-256 :', hashlib.sha3_256(msg).hexdigest())
print('BLAKE2b :', hashlib.blake2b(msg, digest_size=32).hexdigest())
print('BLAKE2b keyed (native MAC mode):', hashlib.blake2b(msg, digest_size=32, key=b'shared-key').hexdigest())
Output:
SHA-256 : f270702f24908a9f078e6c6c57d5813acb794f78f960718848c1902aca9b32ff
SHA3-256 : 0c931d3ab755f76c1b435f6a3c004e567f353cf7f8b704862cfef485e5a3ab6e
BLAKE2b : ce9e18779d6cd1178190f63152108419941372837aaadc67c65d8197897ebe43
BLAKE2b keyed (native MAC mode): 6b59f08957a0f0be63eeb6c16e5ed20c8295ca7aa3b9bba5f688880d6a73968a
All three algorithms are available directly from the same standard library, each producing a distinct 256-bit (32-byte, 64 hex character) digest for the identical input, and BLAKE2's keyed call above demonstrates its native MAC-like mode with no separate construction layered on top. Digest-size comparison across common variants: SHA-256 and SHA3-256 both fix their output at 256 bits; BLAKE2b supports up to 512 bits (optimized for 64-bit platforms) and BLAKE2s supports up to 256 bits (optimized for 8- to 32-bit platforms), so BLAKE2 also offers size flexibility the other two don't.
Trade-offs and pitfalls
- Migrating everything to BLAKE2 purely for speed can hurt interoperability: many external systems, compliance regimes, and existing certificate or signature ecosystems specifically expect SHA-256, so "fastest in software" isn't the only axis that matters once other parties must independently verify your hashes.
- SHA-3's extra safety margin from being structurally different from SHA-2 is a hedge against a specific, so-far-hypothetical risk. Don't pay a real performance cost today for a purely hypothetical future benefit unless your risk tolerance specifically calls for that diversification, such as a long-lived archival signing scheme.
- Keyed BLAKE2 is convenient, but many auditors or compliance frameworks specifically expect a named, standardized MAC construction, HMAC or KMAC, with its own established security proof pedigree. Native keying is a real engineering convenience, not automatically a drop-in replacement for a specifically-mandated construction in a regulated context.
Describe chosen-prefix collision attacks and the techniques that made them feasible against legacy hash functions (for example, MD5). Explain how such attacks enabled forging X.509 certificates in the past and why modern hash designs and policy changes mitigate these attacks. Are there any remaining practical risks for today's hashes?
Sample Answer
Direct answer
A chosen-prefix collision attack lets an attacker pick two different, attacker-chosen prefixes P1 and P2 (for example, an innocuous X.509 certificate body, the standard structured format browsers and servers use for public-key certificates, and a rogue certificate belonging to a Certificate Authority, or CA, the trusted party whose signature is what makes a certificate valid) and then find suffixes T1, T2 such that H(P1 || T1) = H(P2 || T2). That is strictly stronger than a classic identical-prefix collision, where both messages must already agree on their leading bytes. Against MD5 this was demonstrated practically in 2007 to 2009 (Marc Stevens, Alex Sotirov, and collaborators) and used in December 2008 to forge a rogue intermediate CA certificate that chained to a trusted root, because CAs of that era signed certificates whose to-be-signed bytes an attacker could predict well enough to engineer. Modern hash design (SHA-256 and SHA-3, both part of the Secure Hash Algorithm family standardized by the National Institute of Standards and Technology) and policy changes (banning MD5 and later SHA-1 for certificate signing, plus Certificate Transparency) closed that specific exploitation path, but the underlying attack class is not extinct wherever a weak hash still gets trusted.
Structured elaboration
What made it feasible. Three ingredients, layered:
- A differential-cryptanalysis attack on MD5's compression function (built on Xiaoyun Wang's 2004-2005 collision-finding work) that finds a "near-collision" message-block pair: two input blocks that, applied to two SIMILAR internal states, drive those states to a controlled, small bit-difference rather than an identical one.
- Because P1 != P2, the internal chaining state after hashing each prefix (the running "state" a Merkle-Damgard hash carries block to block) starts out different for the two messages. The attacker appends a "birthday block" to each prefix independently and searches, using the plain birthday bound (any pair of blocks that land the two states within the near-collision differential's reach will do, so this step is a birthday search, not a differential one), until the two states are close enough for step 1's near-collision block to finish the job.
- Applying the near-collision block pair from step 1 forces the two states to become bit-for-bit identical. From that point on, a Merkle-Damgard hash's future output depends only on the current chaining state and the remaining input, so the attacker appends any SHARED common suffix to both messages and both final hashes match exactly.
Certificate forgery mechanics. CAs at the time generated to-be-signed certificate bytes containing fields the requester could predict (serial number, validity window) closely enough to construct two candidate bodies in parallel: one for a domain the attacker legitimately controlled, which the CA would sign, and one that was secretly a rogue intermediate-CA certificate, engineered via the steps above to hash to the same MD5 value. The CA's signature over the "innocent" certificate was therefore mathematically also a valid signature over the rogue one, letting the attacker mint trusted certificates for any domain.
Why modern hashes and policy mitigate this. SHA-256 has a much larger internal state and, as of today, no published differential path efficient enough to drive the birthday-alignment step; its collision resistance sits near the full 2^128 birthday bound with no known shortcut. On the policy side: the CA/Browser Forum and root programs banned MD5 for certificate signing (2009-2012) and later SHA-1 (2016-2017); Certificate Transparency (public, append-only, cryptographically verifiable logs of every certificate a CA issues, backed by the same kind of Merkle tree used for tamper-evident audit logs and inclusion proofs) means a forged certificate either never appears in a log, and modern browsers refuse to trust unlogged certificates, or it appears and becomes visible to anyone monitoring their own domain's log entries.
Worked example
Building an actual MD5 chosen-prefix collision from scratch is not something to hand-roll in an interview or a short worked example: it requires a purpose-built differential-path search tool (Stevens' "hashclash"), and the practical 2008 demonstration ran on a cluster of roughly 200 PlayStation 3 game consoles (chosen for their cheap floating-point throughput) for about a day of computation. What is reproducible without specialized tooling is the shape of the exploit: pad each prefix to a whole number of hash blocks, birthday-search for near-colliding states across the two prefixes independently, apply the crafted differential block to force identical states, then concatenate the identical shared suffix. Once the states match, md5(P1_padded + collision_block1 + shared_suffix) == md5(P2_padded + collision_block2 + shared_suffix) follows directly from how a Merkle-Damgard hash chains state to state; no further cryptanalysis is needed after that point.
Trade-offs and pitfalls
Remaining practical risk is concentrated in three places. First, legacy or embedded systems (old firmware update mechanisms, stale VPN stacks, some code-signing chains that never migrated) may still generate or verify MD5- or even SHA-1-based signatures, where this exact forgery class still applies if the artifact is still trusted by anything. Second, SHA-1 itself gained a practical chosen-prefix attack in 2020 (Leurent and Peyrin, "SHAmbles"), so a system that "upgraded" from MD5 to SHA-1 and stopped there is not actually safe against a resourced attacker today. Third, chosen-prefix cryptanalysis is a general attack class against any hash whose compression function admits an efficient differential path, not an MD5-specific curiosity, which is why crypto-agility (the ability to swap the hash algorithm without a system rewrite) is a standing mitigation, not a one-time fix. A common wrong turn is conflating "collision resistance is broken" with "preimage resistance is broken": MD5's preimage resistance is still largely intact, so you cannot reverse a single MD5 hash back to an input, but you absolutely cannot rely on MD5 anywhere collision resistance is load-bearing, such as certificate or code signing.
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 ECDSA, two signatures (r, s1) and (r, s2) use the same ephemeral nonce k for different messages m1 and m2 producing message hashes z1 and z2. Derive algebraically how to recover k and the private key d from r, s1, s2, z1, z2 and curve order n. Explain each algebraic step and discuss corner cases such as s1 == s2 or r == 0.
Sample Answer
Direct answer
When the same nonce k is reused across two ECDSA (Elliptic Curve Digital Signature Algorithm) signatures on different messages, the two signing equations share the same k and therefore the same r, which collapses into a two-equation, two-unknown linear system in k and the private key d. A few lines of modular algebra, no guessing or brute force required, recover both exactly.
Structured elaboration
Setup. Both signatures were produced with the same private key d and the same reused nonce k, on message hashes z1 and z2:
s1=k−1(z1+rd)modn,s2=k−1(z2+rd)modnBoth share the same r because r comes only from k times the base point G, and k is identical in both signatures.
Step 1: recover k by eliminating d. Subtract the two equations:
s1−s2=k−1(z1−z2)modnRearranged:
k=(z1−z2)(s1−s2)−1modnThe rd term cancels exactly because it is identical in both equations, leaving k as the only unknown.
Step 2: recover d from k. Substitute k back into either original equation. From s1 = k^{-1}(z1 + rd) mod n, multiply both sides by k:
ks1=z1+rdmodn d=(ks1−z1)r−1modnCorner cases.
- s1 = s2: subtracting gives 0 = k^{-1}(z1 - z2) mod n, which forces z1 = z2 mod n (since k^{-1} is never 0). If the two messages are genuinely different but happen to hash to the same value mod n, that's an extremely unlikely, separate red flag about the hash function itself; if it's literally the same message signed twice, this pair alone reveals nothing new, since there's no second independent equation to combine with the first.
- r = 0: a well-formed ECDSA implementation never emits r = 0; the signing algorithm mandates picking a fresh k whenever the computed r is 0. Seeing r = 0 in the wild signals a broken or tampered implementation, not a signature worth running this derivation on.
- Invertibility: (s1 - s2) and r both need to be invertible mod n for the two division steps above. Since n is prime for every standard curve, any nonzero residue is invertible, so the only real failure case is the s1 = s2 case already covered.
Worked example
Using the same small, hand-checkable toy curve as a basic ECDSA walk-through (NOT a real or secure curve): y squared = x cubed + 5x + 3, mod 23, base point G = (11, 3), curve order n = 23.
def ec_add(P, Q, a, p):
if P is None: return Q
if Q is None: return P
x1, y1 = P; x2, y2 = Q
if x1 == x2 and (y1 + y2) % p == 0:
return None
if P == Q:
lam = (3*x1*x1 + a) * pow(2*y1, -1, p) % p
else:
lam = (y2 - y1) * pow((x2 - x1) % p, -1, p) % p
x3 = (lam*lam - x1 - x2) % p
y3 = (lam*(x1 - x3) - y1) % p
return (x3, y3)
def ec_mul(k, P, a, p):
R, Q = None, P
while k > 0:
if k & 1: R = ec_add(R, Q, a, p)
Q = ec_add(Q, Q, a, p)
k >>= 1
return R
p, a, b, n = 23, 5, 3, 23
G = (11, 3)
def sign(d, k, z):
R = ec_mul(k, G, a, p)
r = R[0] % n
s = (pow(k, -1, n) * (z + r * d)) % n
return r, s
d = 7
Q = ec_mul(d, G, a, p)
k = 4
z1, z2 = 15, 3
r1, s1 = sign(d, k, z1)
r2, s2 = sign(d, k, z2)
print('(r1, s1) =', (r1, s1), ' for z1 =', z1)
print('(r2, s2) =', (r2, s2), ' for z2 =', z2)
print('r1 == r2 (the reuse tell)?', r1 == r2)
r = r1
k_rec = ((z1 - z2) * pow((s1 - s2) % n, -1, n)) % n
d_rec = ((k_rec * s1 - z1) * pow(r, -1, n)) % n
print('recovered k =', k_rec, '(true k =', k, ')')
print('recovered d =', d_rec, '(true d =', d, ')')
print('recovered public key matches?', ec_mul(d_rec, G, a, p) == Q)
Output:
(r1, s1) = (10, 4) for z1 = 15
(r2, s2) = (10, 1) for z2 = 3
r1 == r2 (the reuse tell)? True
recovered k = 4 (true k = 4 )
recovered d = 7 (true d = 7 )
recovered public key matches? True
By hand: (s1 - s2) mod 23 = 3, whose inverse mod 23 is 8 (3 times 8 = 24 = 1 mod 23), so k = (15-3) times 8 mod 23 = 96 mod 23 = 4, matching. Then d = (4 times 4 - 15) times inverse of 10 mod 23; inverse of 10 mod 23 is 7 (10 times 7 = 70 = 1 mod 23), so d = 1 times 7 = 7, matching.
Trade-offs and pitfalls
- This is exactly the bug behind the 2010 Sony PlayStation 3 firmware-signing key recovery and behind numerous 2013 Bitcoin and Android wallet thefts, where a broken or weak random-number generator reused nonces across transaction signatures. This is not a theoretical curiosity; it has repeatedly caused real private-key loss in production systems.
- Detecting reuse at scale is cheap: since r depends only on k, not on the message, any two signatures from the SAME public key sharing an r value are an instant red flag. A monitoring system can index signatures by (public key, r) and alert on any collision without touching private key material at all.
- The fix is deterministic nonce generation, RFC 6979, or an equivalent audited signing library. Never hand-roll nonce generation, and never reuse a nonce across signing calls even for testing purposes.
Unlock Full Question Bank
Get access to all 35 Cryptographic Hashing and Digital Signatures interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.