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.
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.
Walk through how ECDSA signing and verification work at a high level, focusing on the role of the per-message nonce k. Why must k be unpredictable and unique for every signature, what goes wrong if it is reused or partially leaks, and how does deterministic nonce generation (RFC 6979) address that risk?
Sample Answer
Direct answer
ECDSA (Elliptic Curve Digital Signature Algorithm) signs a message by picking a fresh, secret per-message value called a nonce k (a number used once), turning it into a point on the elliptic curve, and combining it algebraically with the private key and the message hash. Verification redoes an equivalent computation using only the public key and checks that the results line up. The nonce k must be unpredictable and unique for every signature because it is algebraically tangled together with the private key in the signing equation: if k repeats across two signatures, or if even a few bits of it leak, an attacker can solve directly for the private key. RFC 6979 removes the dependency on a trustworthy random-number generator by deriving k deterministically, but still unpredictably to anyone who doesn't hold the private key.
Structured elaboration
Setup. The curve has a fixed base point G of prime order n. The private key d is a random integer in [1, n-1]; the public key is Q = d times G.
Signing, given private key d and message hash z = H(m):
R=k⋅G r=Rxmodn s=k−1(z+r⋅d)modn(if r = 0 or s = 0, discard k and pick a new one). The signature is the pair (r, s).
Verification, given the public key Q:
w=s−1modn,u1=zwmodn,u2=rwmodn X=u1⋅G+u2⋅QThe signature is valid only if X's x-coordinate, reduced mod n, equals r.
Why k has to be unpredictable and unique. The s equation contains both k and the private key d, linearly. If the same k is reused for two different messages, subtracting the two signing equations cancels the term that involves d and leaves a simple equation in k alone, which any attacker can solve, and then d falls out immediately. Even partial leakage of k (a handful of bits per signature, from a side channel or a biased random-number generator) is still dangerous. Each signature that leaks a few bits of its k hands the attacker one noisy, partial clue about the same unknown private key d; stack enough of those clues from enough signatures and recovering d becomes exactly what's called, in cryptography, the hidden number problem: recovering one hidden secret number from many partial, imperfect hints about it, where each hint is an equation with a small unknown error term rather than an exact value. Lattice-based attacks, techniques that arrange all of those noisy equations as a grid of integer vectors and search that grid for the one unusually short vector hiding inside it, are the standard tool for solving the hidden number problem in practice: given enough signatures with enough leaked bits, they can reconstruct k, and from there d, directly.
Real-world consequences. Sony's PlayStation 3 firmware signing (disclosed 2010) reused a single fixed k for every signature, letting researchers recover Sony's private signing key outright. A 2013 bug in Android's random-number generator caused some Bitcoin wallet apps to reuse or produce weak nonces, which attackers used to steal funds directly off signatures visible on the public blockchain. Neither case required breaking any hard math problem, only exploiting a nonce that wasn't actually unpredictable.
RFC 6979. Instead of "pick k randomly," RFC 6979 derives k deterministically from the private key d and the message hash using an HMAC (Hash-based Message Authentication Code) based construction, specifically an HMAC-DRBG, a deterministic random bit generator built from HMAC. k is still unique per (d, m) pair and unpredictable to anyone without d, but there is no external random-number generator involved, which closes off an entire historical class of nonce failures without weakening unpredictability from an attacker's point of view.
Worked example
To make the mechanism concrete, here is a full toy run on a small, hand-checkable curve (NOT a real or secure curve, purely for following the arithmetic): y squared = x cubed + 5x + 3, taken mod 23, with base point G = (11, 3) and curve order n = 23 (n happens to be prime here, so every non-identity point generates the whole group).
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 = 23, 5, 3
n = 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 = 7
Q = ec_mul(d, G, a, p)
k = 4
z = 15
r, s = sign(d, k, z)
print('public key Q = d*G =', Q)
print('signature (r, s) =', (r, s))
print('verifies against original message?', verify(Q, z, r, s))
print('verifies against a tampered message (z=16)?', verify(Q, 16, r, s))
Output:
public key Q = d*G = (9, 8)
signature (r, s) = (10, 4)
verifies against original message? True
verifies against a tampered message (z=16)? False
A real deployment uses a curve like secp256r1, with n roughly a 256-bit prime, not n=23; the toy curve exists purely so every step above can be followed by hand.
Trade-offs and pitfalls
- Never hand-roll nonce generation. Use a vetted library that defaults to RFC 6979 (or an equivalent audited construction) rather than "just call the system random-number generator and hope."
- Deterministic nonces close the RNG-failure class of bugs, but they open a narrower one: if a fault-injection attack (voltage or clock glitching during signing) can force the SAME (d, m) pair to be signed twice under a fault, differential fault analysis can sometimes still extract d, because the nonce is guaranteed to repeat by design.
- A correct, unique nonce is necessary but not sufficient. If the signing implementation's modular inverse or scalar multiplication takes variable time depending on secret bits, k or d can still leak through a timing or power side channel (real examples: the Minerva and TPM-Fail disclosures, 2019 to 2020), independent of whether the nonce itself was generated correctly.
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.
A protocol uses the same hash function for several different purposes, say deriving a key, computing a MAC, and generating a commitment. What could go wrong if you don't domain-separate these uses, and how would you fix it? Give two concrete examples of mistakes this causes.
Sample Answer
Direct answer
A cryptographic hash function (a deterministic function mapping arbitrary-length input to a fixed-length output, chosen so it is hard to invert or to find two inputs with the same output) carries no built-in notion of "what it was called for." If the same hash function, on the same or overlapping input material, is used for a key derivation, a MAC (message authentication code, a keyed tag proving both integrity and that the sender held a shared secret), and a commitment (a value that binds you to a choice now without revealing it, verified later), then a value computed for one purpose can be replayed, confused with, or engineered to collide with a value expected for another purpose. The fix is domain separation: tag every hash invocation with an explicit, purpose-specific label (a prefix byte, an HKDF info string, or a distinct derived key) so outputs from different roles are provably independent of each other.
Structured elaboration
- Why it breaks: a hash output by itself is just bytes. If role A's computation and role B's computation can ever be fed the same input, they produce the same output, and anything that treats "the output" as proof of role B now also accepts a value that was really produced for role A.
- Domain-separation mechanisms, roughly in order of how directly they fix the problem:
- A fixed domain-tag byte or string prepended to every hash input, unique per role (
H(0x01 || x)for key derivation vsH(0x02 || x)for a MAC). - A real key-derivation function (KDF, a function that turns one keying secret into one or more independent-looking derived keys) such as HKDF, where each derived key/value uses a distinct
infolabel instead of ad hoc concatenation. - Distinct keys per purpose (an HMAC key used only for authentication, never reused as input keying material for a KDF).
- A fixed domain-tag byte or string prepended to every hash input, unique per role (
- A second, easy-to-miss requirement: domain separation only closes the "which role" ambiguity. It does not by itself close a "where do the fields end" ambiguity when you concatenate several variable-length fields before hashing; that needs length-prefixing or fixed-width encoding, and both problems tend to appear together in the same ad hoc protocol.
Worked example
Mistake 1, reusing one computation for two roles: a protocol computes tag = H(secret || message) as a MAC, authenticating that the holder of secret approved message. The same team later needs a commitment scheme and, to save code, publishes commitment = H(secret || message) as "proof the message was fixed in advance." Because tag and commitment are literally the same computation, publishing the commitment leaks a valid MAC tag for message: anyone who now sees commitment and message can replay commitment as the MAC, since it is bit-for-bit the value the MAC check expects. Fix: derive two independent values, e.g. tag = HMAC(K_mac, message) and commitment = HMAC(K_commit, message), where K_mac and K_commit come from a KDF fed distinct info labels ("mac" vs "commit"), so knowing one output tells you nothing about the other.
Mistake 2, concatenation ambiguity masquerading as a hash-role confusion: a system derives a session subkey as K' = H(K || "session-key") and separately computes a per-request MAC over structured fields as MAC = H(K || field1 || field2), with no length-prefixing and no domain tag distinguishing the two computations. An attacker who controls field1 in the MAC path can set field1 = "session-key" and force field2 to be empty (many APIs happily accept an empty trailing field), so the MAC computation becomes H(K || "session-key"), i.e. exactly the subkey-derivation computation. The attacker never learns K, but they now hold K' (the session subkey), obtained purely by requesting a MAC over attacker-chosen fields. Fix: length-prefix every field so "session-key" as literal field content can never line up with a concatenation boundary, and put a fixed domain-tag byte first in every hash call in the protocol (0x01 for key derivation, 0x02 for MAC), defined centrally in the spec so a future feature cannot silently reuse an existing tag.
Trade-offs and pitfalls
- Domain separation only helps if applied everywhere, consistently, including features added later; leaving it as convention rather than a spec-level, centrally enforced rule is how it gets skipped once.
- A domain tag placed at the very start of the input matters for Merkle-Damgard-style hashes (SHA-256, SHA-1, a family of hash constructions that process input in fixed-size blocks through a repeated compression step): tying the tag to the first hashed block, rather than appending it at the end, keeps the tag inseparable from everything that follows, which matters once you also consider length-extension-style manipulation of hash inputs.
- Do not treat "add a prefix" and "length-prefix the fields" as the same fix: the first stops cross-role confusion, the second stops within-role field-boundary confusion, and a protocol missing either one is still exploitable.
Write the RFC 6979 deterministic nonce generator (HMAC-DRBG) for ECDSA in Python. Implement a function rfc6979_generate_k(hash_bytes: bytes, x: int, q: int) -> int that outputs deterministic k in the range [1, q-1]. Follow the algorithm steps: initialize V and K, perform the HMAC loops, and iterate until k is in range. You may assume hashlib and hmac are available; focus on correct HMAC sequence rather than optimizations.
Sample Answer
Approach
RFC 6979 replaces ECDSA's usual random per-signature nonce k with a DETERMINISTIC one, derived from the private key x, the curve order q, and the message hash via an HMAC-DRBG (HMAC-based deterministic random bit generator: a construction that turns HMAC, a keyed hash-based message authentication code, into a pseudorandom byte stream by repeatedly re-keying and re-hashing an internal state). Determinism removes the "did the random-number generator produce a good k" failure mode entirely, since the same (x, message) pair always yields the same k, and a broken or predictable OS random source can no longer leak or bias the nonce. The construction follows RFC 6979 section 3.2 steps a through h: seed an HMAC key K and value V, run two priming HMAC rounds mixing in the private key and message hash, then loop generating candidate k values from V until one falls in the valid range [1, q-1].
Implementation
import hmac
import hashlib
def rfc6979_generate_k(hash_bytes: bytes, x: int, q: int) -> int:
"""RFC 6979 deterministic k generation (HMAC-DRBG), section 3.2, steps a-h."""
qlen = q.bit_length()
rolen = (qlen + 7) // 8
hlen = hashlib.sha256().digest_size
def bits2int(b: bytes) -> int:
v = int.from_bytes(b, "big")
excess = len(b) * 8 - qlen
if excess > 0:
v >>= excess
return v
def int2octets(v: int) -> bytes:
return v.to_bytes(rolen, "big")
def bits2octets(b: bytes) -> bytes:
z1 = bits2int(b)
z2 = z1 - q if z1 >= q else z1
if z2 < 0:
z2 = z1
return int2octets(z2 % q)
# a. h1 = H(m) is passed in directly as hash_bytes
h1 = hash_bytes
# b. V = 0x01 0x01 ... (hlen bytes)
V = b"\x01" * hlen
# c. K = 0x00 0x00 ... (hlen bytes)
K = b"\x00" * hlen
# d. K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1))
K = hmac.new(K, V + b"\x00" + int2octets(x) + bits2octets(h1), hashlib.sha256).digest()
# e. V = HMAC_K(V)
V = hmac.new(K, V, hashlib.sha256).digest()
# f. K = HMAC_K(V || 0x01 || int2octets(x) || bits2octets(h1))
K = hmac.new(K, V + b"\x01" + int2octets(x) + bits2octets(h1), hashlib.sha256).digest()
# g. V = HMAC_K(V)
V = hmac.new(K, V, hashlib.sha256).digest()
# h. generation loop
while True:
T = b""
while len(T) < rolen:
V = hmac.new(K, V, hashlib.sha256).digest()
T += V
k = bits2int(T)
if 1 <= k < q:
return k
K = hmac.new(K, V + b"\x00", hashlib.sha256).digest()
V = hmac.new(K, V, hashlib.sha256).digest()
if __name__ == "__main__":
# NIST P-256 order and RFC 6979 A.2.5 "sample" test vector
q = 0xFFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551
x = 0xC9AFA9D845BA75166B5C215767B1D6934E50C3DB36E89B127B8A622B120F6721 % q
msg = b"sample"
h1 = hashlib.sha256(msg).digest()
k = rfc6979_generate_k(h1, x, q)
print("q =", hex(q))
print("x =", hex(x))
print("H(msg) =", h1.hex())
print("k =", hex(k))
# cross-check against the independent `ecdsa` library's RFC 6979 implementation
from ecdsa.rfc6979 import generate_k
from ecdsa.curves import NIST256p
k_ref = generate_k(NIST256p.order, x, hashlib.sha256, h1)
print("k_ref =", hex(k_ref))
print("match =", k == k_ref)
Output (verified against NIST P-256's order and the RFC 6979 Appendix A.2.5 "sample" test vector, cross-checked against the independent ecdsa library's own RFC 6979 implementation):
q = 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551
x = 0xc9afa9d845ba75166b5c215767b1d6934e50c3db36e89b127b8a622b120f6721
H(msg) = af2bdbe1aa9b6ec1e2ade1d694f41fc71a831d0268e9891562113d8a62add1bf
k = 0xa6e3c57dd01abe90086538398355dd4c3b17aa873382b0f24d6129493d8aad60
k_ref = 0xa6e3c57dd01abe90086538398355dd4c3b17aa873382b0f24d6129493d8aad60
match = True
Key points
bits2inttruncates a hash or intermediate value down to the bit-length ofq(qlen), NOT its byte-length; this distinction matters becauseqfor most named curves is not an exact multiple of 8 bits, and getting this wrong silently produces a different (still in-range, still "valid-looking")kthat will not match any reference implementation or test vector.int2octets/bits2octetshandle converting between integers and fixed-length byte strings usingrolen = ceil(qlen / 8), andbits2octetsadditionally reduces the hash value moduloqbefore re-encoding it, per the RFC.- The two priming rounds (steps d through g) mix
int2octets(x)(the private key, fixed-length encoded) andbits2octets(h1)(the message hash, reduced and encoded) into the running HMAC key/value pair(K, V), first tagged with a0x00byte, then with0x01, before the actual generation loop begins. - The generation loop (step h) repeatedly computes
V = HMAC_K(V)to fill an output buffer at leastrolenbytes long, converts that buffer back to an integer viabits2int, and accepts it only if it lands in[1, q-1]; on rejection it reseedsKandVand tries again, though rejection is astronomically rare for real curve sizes.
Complexity
Each candidate k costs a small constant number of HMAC-SHA256 calls (2 priming calls plus roughly 1 call per 32 bytes of output needed per attempt), independent of the private key's value; the loop is expected to terminate in a single iteration for essentially all practical q, since the rejection probability per attempt is on the order of 1 - q/2^qlen, which is negligible for standard curves. Space is O(1): only K, V, and the small fixed-size accumulator buffer are held at once.
Edge cases
qlennot a multiple of 8 (true for several named curves):bits2intmust right-shift by the exact excess bit count, not round to a byte boundary, or the result silently disagrees with every reference implementation while still "looking" like a validk.- A generated candidate
kthat lands outside[1, q-1]on the first attempt (the algorithm handles this by design via the reseed-and-retry loop in step h, rather than treating it as an error). x = 0orx >= q: RFC 6979 assumes a valid private key is supplied; a defensive implementation should reject an out-of-rangexbefore generating, since silently reducing it would derive akfor the wrong effective key.
Unlock Full Question Bank
Get access to all Cryptographic Hashing and Digital Signatures interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.