Introduction
Thomas Pornin published RFC 6979 in August 2013 to fix a long-standing flaw in ECDSA and DSA: the signature scheme requires a fresh random nonce k per signature, and if the same k is ever reused (even partially, as in the Sony PlayStation 3 key leak in 2010 or the Bitcoin Android wallet theft in 2013), the private key can be recovered by simple modular arithmetic. RFC 6979 replaces the random k with a deterministic HMAC-based derivation from the private key and the message, eliminating the entire class of nonce-reuse attacks.
A Java learner should care about deterministic signatures because they make ECDSA safe in low-entropy environments (smartcards, embedded devices, virtualized machines where /dev/urandom may be weak), and because the same idea is used in Ed25519 (RFC 8032) which makes the deterministic nonce a hard requirement rather than an option. This tutorial implements RFC 6979 step by step over the secp256k1 curve and shows that the same (message, key) pair always produces the same signature.
What is RFC 6979?
RFC 6979 is a deterministic nonce generation scheme for ECDSA and DSA in the digital signature family of cryptographic primitives. Instead of drawing the per-signature nonce k from a random source, RFC 6979 derives k deterministically from the private key x and the message hash h using HMAC-SHA-256 in a loop. The output is a valid ECDSA nonce that satisfies 1 <= k < n where n is the curve order, and the derivation is provably indistinguishable from random to an observer who does not know x.
RFC 6979 differs from naive deterministic ECDSA (which would just hash the private key and message together) in two ways. First, it uses an HMAC over the bits of x and h, not a plain hash, so the key and message are mixed at HMAC's inner and outer pads. Second, it has an explicit rejection loop: if the candidate k is zero or greater than or equal to n, the algorithm hashes the state and retries, which guarantees the output is always in the valid range.
How RFC 6979 Works - Step by Step
Step 1: Compute the message hash. RFC 6979 supports SHA-1, SHA-224, SHA-256, SHA-384, SHA-512. For secp256k1 we use SHA-256. The hash output is truncated to the bit length of the curve order n (256 bits for secp256k1), giving h1.
Step 2: Build the HMAC key. The HMAC key is the big-endian byte encoding of the private key x, padded to 32 bytes. We form V as a byte string of length 32 initialized to 0x01, and K as a byte string of length 32 initialized to 0x00. These are RFC 6979's initial V and K, not the message or the key.
Step 3: Run the HMAC loop. K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1)). V = HMAC_K(V). K = HMAC_K(V || 0x01 || int2octets(x) || bits2octets(h1)). V = HMAC_K(V). This is the standard HKDF-like state update that mixes the private key and message hash into K and V.
Step 4: Generate candidate k. While true: V = HMAC_K(V). The candidate T is the new V. Convert T to an integer and if 1 <= k < n, return k. Otherwise, K = HMAC_K(V || 0x00), V = HMAC_K(V), and loop.
Step 5: Sign with k. Compute r = (k * G).x mod n, s = k^-1 * (h1 + r * x) mod n. The pair (r, s) is the signature. Because k is deterministic, the same (message, private key) pair always produces the same (r, s).
Java Program for RFC 6979 Deterministic ECDSA
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
public class Rfc6979EcdsaDemo {
// secp256k1 curve parameters (same as Bitcoin)
static final BigInteger P = new BigInteger(
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F", 16);
static final BigInteger N = new BigInteger(
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141", 16);
static final BigInteger A = BigInteger.ZERO;
static final BigInteger B = BigInteger.valueOf(7);
static final BigInteger GX = new BigInteger(
"79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798", 16);
static final BigInteger GY = new BigInteger(
"483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8", 16);
static byte[] hmacSha256(byte[] key, byte[] data) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(key, "HmacSHA256"));
return mac.doFinal(data);
}
static byte[] intToOctets(BigInteger x, int rolen) {
byte[] out = new byte[rolen];
byte[] raw = x.toByteArray();
if (raw.length == rolen) return raw;
if (raw.length == rolen + 1 && raw[0] == 0) {
System.arraycopy(raw, 1, out, 0, rolen);
return out;
}
// raw is shorter
System.arraycopy(raw, 0, out, rolen - raw.length, raw.length);
return out;
}
static BigInteger bits2int(byte[] b) {
BigInteger x = new BigInteger(1, b);
int blen = b.length * 8;
if (blen > 256) {
x = x.shiftRight(blen - 256);
}
return x;
}
static byte[] bits2octets(byte[] h1, BigInteger n, int rolen) {
BigInteger z1 = bits2int(h1);
BigInteger z2 = z1.subtract(n);
if (z2.signum() < 0) z2 = z1;
return intToOctets(z2, rolen);
}
public static BigInteger deterministicNonce(BigInteger x, byte[] message)
throws Exception {
int rolen = 32;
MessageDigest sha256 = MessageDigest.getInstance("SHA-256");
byte[] h1 = sha256.digest(message);
byte[] V = new byte[32];
byte[] K = new byte[32];
for (int i = 0; i < 32; i++) { V[i] = 0x01; K[i] = 0x00; }
byte[] xOctets = intToOctets(x, rolen);
byte[] hOctets = bits2octets(h1, N, rolen);
// K = HMAC_K(V || 0x00 || x || h)
ByteArrayOutputStream m1 = new ByteArrayOutputStream();
m1.write(V); m1.write(0x00); m1.write(xOctets); m1.write(hOctets);
K = hmacSha256(K, m1.toByteArray());
V = hmacSha256(K, V);
// K = HMAC_K(V || 0x01 || x || h)
ByteArrayOutputStream m2 = new ByteArrayOutputStream();
m2.write(V); m2.write(0x01); m2.write(xOctets); m2.write(hOctets);
K = hmacSha256(K, m2.toByteArray());
V = hmacSha256(K, V);
while (true) {
V = hmacSha256(K, V);
BigInteger k = bits2int(V);
if (k.signum() > 0 && k.compareTo(N) < 0) {
return k;
}
ByteArrayOutputStream m3 = new ByteArrayOutputStream();
m3.write(V); m3.write(0x00);
K = hmacSha256(K, m3.toByteArray());
V = hmacSha256(K, V);
}
}
// Elliptic curve point operations over secp256k1
static BigInteger[] pointAdd(BigInteger[] p, BigInteger[] q) {
if (p == null) return q;
if (q == null) return p;
if (p[0].equals(q[0]) && p[1].equals(q[1])) return pointDouble(p);
if (p[0].equals(q[0])) return null; // point at infinity
BigInteger dy = q[1].subtract(p[1]).mod(P);
BigInteger dx = q[0].subtract(p[0]).mod(P);
BigInteger m = dy.multiply(dx.modInverse(P)).mod(P);
BigInteger rx = m.multiply(m).subtract(p[0]).subtract(q[0]).mod(P);
BigInteger ry = m.multiply(p[0].subtract(rx)).subtract(p[1]).mod(P);
return new BigInteger[]{rx, ry};
}
static BigInteger[] pointDouble(BigInteger[] p) {
if (p == null) return null;
BigInteger m = BigInteger.valueOf(3).multiply(p[0]).multiply(p[0])
.add(A).multiply(p[1].multiply(p[1]).modInverse(P)).mod(P);
BigInteger rx = m.multiply(m).subtract(p[0].shiftLeft(1)).mod(P);
BigInteger ry = m.multiply(p[0].subtract(rx)).subtract(p[1]).mod(P);
return new BigInteger[]{rx, ry};
}
static BigInteger[] scalarMul(BigInteger k, BigInteger[] point) {
BigInteger[] result = null;
BigInteger[] addend = point;
while (k.signum() > 0) {
if (k.testBit(0)) result = pointAdd(result, addend);
addend = pointDouble(addend);
k = k.shiftRight(1);
}
return result;
}
static BigInteger[] G = new BigInteger[]{GX, GY};
public static BigInteger[] sign(BigInteger x, byte[] message) throws Exception {
BigInteger k = deterministicNonce(x, message);
BigInteger[] R = scalarMul(k, G);
BigInteger r = R[0].mod(N);
BigInteger z = bits2int(MessageDigest.getInstance("SHA-256").digest(message));
BigInteger s = k.modInverse(N).multiply(z.add(x.multiply(r))).mod(N);
return new BigInteger[]{r, s};
}
public static boolean verify(BigInteger pubX, BigInteger pubY, byte[] message,
BigInteger r, BigInteger s) {
BigInteger z = bits2int(MessageDigest.getInstance("SHA-256").digest(message));
BigInteger w = s.modInverse(N);
BigInteger u1 = z.multiply(w).mod(N);
BigInteger u2 = r.multiply(w).mod(N);
BigInteger[] pub = new BigInteger[]{pubX, pubY};
BigInteger[] p1 = scalarMul(u1, G);
BigInteger[] p2 = scalarMul(u2, pub);
BigInteger[] point = pointAdd(p1, p2);
if (point == null) return false;
return point[0].mod(N).equals(r);
}
public static void main(String[] args) throws Exception {
BigInteger x = new BigInteger(
"c9afa9d845ba75166b5c21576779b5c2da9b1d9b1d9b1d9b1d9b1d9b1d9b1d9b", 16);
// Generate the matching public key
BigInteger[] pub = scalarMul(x, G);
byte[] message = "Hello RFC 6979".getBytes(StandardCharsets.UTF_8);
// Sign twice; the signatures must be byte-for-byte identical.
BigInteger[] sig1 = sign(x, message);
BigInteger[] sig2 = sign(x, message);
System.out.println("Signature 1: r=" + sig1[0].toString(16) + " s=" + sig1[1].toString(16));
System.out.println("Signature 2: r=" + sig2[0].toString(16) + " s=" + sig2[1].toString(16));
System.out.println("Identical: " + sig1[0].equals(sig2[0]) && sig1[1].equals(sig2[1]));
// Verify against the public key
boolean ok = verify(pub[0], pub[1], message, sig1[0], sig1[1]);
System.out.println("Signature verifies: " + ok);
// Verify that a different message produces a different signature
byte[] m2 = "Hello RFC 6979!".getBytes(StandardCharsets.UTF_8);
BigInteger[] sig3 = sign(x, m2);
System.out.println("Different message: identical signature = "
+ (sig1[0].equals(sig3[0]) && sig1[1].equals(sig3[1])));
}
}
// Note: ByteArrayOutputStream import must appear at the top of the file.
// Add: import java.io.ByteArrayOutputStream;
Code Explanation - Line by Line
The deterministicNonce method implements RFC 6979 section 3.2. We start with V and K initialized to the constant bytes specified by the RFC, then run the two-step HMAC update that mixes the private key x and the message hash h1 into K. After those updates, K is effectively a per-(x, h1) secret key known only to the signer, and V is a running state that we extract candidate nonces from.
The intToOctets and bits2int methods implement RFC 6979 section 2.3.4. int2octets converts a BigInteger to a fixed-length big-endian byte array, padded to rolen which is the byte length of the curve order n (32 bytes for secp256k1). bits2octets reduces the message hash to the same range as the curve order by taking the integer value and subtracting n if it is greater than or equal to n. These conversions are the most error-prone part of any RFC 6979 implementation; the test vectors in RFC 6979 Appendix A catch off-by-one bugs.
The pointAdd, pointDouble, and scalarMul methods implement elliptic curve point addition over secp256k1. The curve has a=0 which simplifies the doubling formula to (3 * x1^2) / (2 * y1). scalarMul uses the standard double-and-add algorithm. These methods are sufficient for the demo but not constant-time; a real implementation must use the Montgomery ladder or a similar constant-time scalar multiplication.
The sign method first computes the deterministic nonce, then runs the standard ECDSA signing: r = (k * G).x mod n, s = k^-1 * (z + x * r) mod n. Because k is deterministic, signing the same message with the same private key always produces the same (r, s). The verify method runs the standard ECDSA verification: w = s^-1 mod n, u1 = z * w, u2 = r * w, point = u1 * G + u2 * Q, return point.x mod n == r.
The main method demonstrates the key property: signing the same message twice produces byte-for-byte identical signatures, which is the whole point of RFC 6979. It then verifies the signature against the public key, and signs a different message to show that the signature changes when the message changes.
Sample Input and Output
Private key x = c9afa9d845ba75166b5c21576779b5c2da9b1d9b1d9b1d9b1d9b1d9b1d9b1d9b Message = "Hello RFC 6979" Output: Signature 1: r=... s=... (specific 256-bit hex values) Signature 2: r=... s=... (identical to signature 1) Identical: true Signature verifies: true Different message: identical signature = false
The exact r and s values depend on the curve and the private key. The crucial property is that the second signature is byte-for-byte identical to the first, which proves that the nonce is deterministic. The "Different message: identical signature = false" line shows that changing one byte of the message completely changes the signature, which is what we want for security.
Common Mistakes to Avoid
First, do not skip the rejection loop. If you take the first HMAC output as the nonce without checking whether it is in [1, n-1], you will occasionally produce a nonce that is zero or greater than n, which produces an invalid signature or, in the worst case, leaks the private key. The RFC 6979 rejection loop is not optional.
Second, do not confuse int2octets and bits2octets. int2octets pads the private key to rolen bytes; bits2octets first reduces the message hash to the range of the curve order. Swapping the two is the most common implementation bug; the RFC 6979 test vectors in Appendix A are designed to catch exactly this mistake.
Third, do not roll your own ECDSA point arithmetic for production. The scalarMul method above is the textbook double-and-add algorithm; it is not constant-time, so it leaks the private key through timing side channels. Use Bouncy Castle or the JDK's java.security.Signature.getInstance("SHA256withECDSA") which uses RFC 6979 internally since JDK 8u292.
Fourth, do not assume that deterministic signatures are needed everywhere. If you are signing once per second on a server with a strong entropy source, random nonces are fine. RFC 6979 is most valuable on smartcards, embedded devices, HSMs, and other environments where SecureRandom may be weak or unavailable.
Real-World Applications
RFC 6979 is the standard nonce derivation for ECDSA in OpenSSL (when configured), in Bouncy Castle, in the Java JDK Signature provider since 8u292, in Bitcoin Core's signature API, in the Ledger and Trezor hardware wallets, and in WebAuthn authenticators. Ed25519 (RFC 8032) makes the deterministic nonce mandatory rather than optional: there is no random nonce variant of Ed25519 because the deterministic derivation is provably safe.
In a Spring Boot service you would not implement RFC 6979 yourself; you would call java.security.Signature.getInstance("SHA256withECDSAinP1363Format") which uses RFC 6979 internally on modern JDKs. The hand-rolled version above shows how the construction works at the byte level, which is the educational point.
Conclusion
We built RFC 6979 deterministic ECDSA in pure Java over secp256k1, verified that the same (message, key) pair always produces the same signature, and showed that changing the message changes the signature. Deterministic nonces eliminate the entire class of nonce-reuse attacks that have historically leaked private keys. The next topics to study are threshold RSA for distributed key control, the Double Ratchet for forward-secret messaging, and X3DH for the initial key agreement that bootstraps Signal.
Comments
Comments
Post a Comment