Introduction
The Schnorr signature scheme is a digital signature algorithm published by the German cryptographer Claus-Peter Schnorr in 1989 and refined in his 1991 paper "Efficient Signature Generation by Smart Cards". The Schnorr signature scheme was designed to be efficient on smart cards that had only a few kilobytes of ROM and a slow 8-bit processor: signing needs only one short exponentiation mod p and one modular multiplication, while verification needs two exponentiations that can be combined with the multi-exponentiation trick. A Java learner should care because the Schnorr construction is the mathematical ancestor of DSA (FIPS 186) and the modern EdDSA family, and because the Bitcoin community adopted the BIP-340 variant of Schnorr over secp256k1 in the 2021 Taproot upgrade, making it one of the most production-deployed signature schemes in the world.
This tutorial walks through a self-contained Schnorr signature java implementation over the classic integer group of order q inside Z_p*, using only java.math.BigInteger and java.security.MessageDigest. The program generates a key pair, signs a message, verifies a valid signature, and detects tampering when a single byte of the message is flipped. By the end of the tutorial you should be able to read the BIP-340 specification and the EdDSA RFC 8032 with full comprehension.
What is the Schnorr Signature Scheme?
A Schnorr signature is a public-key digital signature based on the discrete logarithm problem. Like DSA and ECDSA, it relies on the hardness of computing the private exponent x from a public value y = g^x in a group of prime order q. Unlike DSA and ECDSA, however, Schnorr is provably secure in the random oracle model under the discrete log assumption: the Fiat and Shamir 1986 trick that turns an interactive identification protocol into a non-interactive signature gives a tight reduction to the underlying discrete log problem.
Schnorr is provably unforgeable under chosen-message attack, which DSA and ECDSA are not. The signature is the pair (e, s) where e is a short hash challenge and s is a linear combination of the random nonce and the private key times the challenge. The verifier reconstructs the commitment r' = g^s * y^e and checks that the hash of (r', message) equals e. Because the verifier only needs r', the signature can be transmitted in the compact (e, s) form, and because the prover must know x to make the equation balance, only the holder of the private key can produce a valid (e, s).
Schnorr is also naturally multi-signature friendly: multiple signers can produce a single combined signature on a joint public key, and the combined signature is indistinguishable from a single-signer signature. That is the property Bitcoin Taproot exploits to lower on-chain fees and improve privacy.
How the Schnorr Signature Works - Step by Step
Step 1: Group setup. Pick primes p and q such that q divides p-1, with q about 256 bits and p about 2048 bits. Pick a generator g of the order-q subgroup of Z_p*, typically computed as g = (random element of Z_p*)^((p-1)/q) mod p. The group parameters (p, q, g) are public.
Step 2: Key generation. Pick a uniformly random private scalar x in [1, q-1]. Compute the public value y = g^x mod p. Publish y; keep x secret.
Step 3: Signing nonce. For each signature, pick a fresh uniformly random nonce k in [1, q-1]. Compute the commitment r = g^k mod p. If r happens to be zero or one, draw a new k; this is astronomically unlikely but the check matters.
Step 4: Fiat-Shamir challenge. Compute the challenge e = H(message || r) mod q, where H is a cryptographic hash such as SHA-256. The challenge is unpredictable to anyone who has not committed to r, which is what stops a forger from choosing e first and then solving for a valid s.
Step 5: Response. Compute s = (k - x*e) mod q. The signature is the pair (e, s). Some variants send (r, s) and let the verifier recompute e; both are equivalent.
Step 6: Verification. The verifier computes r' = g^s * y^e mod p and then checks that H(message || r') mod q equals e. If the signature is honest, r' equals r and the check passes. If any bit of the message is flipped, the recomputed hash changes, so e' no longer matches e.
Step 7: Tamper detection. Suppose an attacker flips a bit in the message but keeps (e, s). The verifier computes r' = g^s * y^e, which is the original r, but the hash is taken over the modified message, so the hash of (modified message, r') is not e. The signature is rejected.
Java Program for the Schnorr Signature Scheme
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Arrays;
public class SchnorrSignatureDemo {
// Public group parameters (toy 512-bit p for fast demo; use 2048+ bits in production).
static final BigInteger p = new BigInteger(
"f1c1c71765ead5b0669bd3537846e9c0c65b9e6f2c2c1b7a4d9f5e1d3c7b9a4f" +
"1b3c5d7e9f0a2c4e6d8f0b2a4c6e8d0f2b4a6c8e0d2f4a6c8b0e2d4f6a8c0e2b" +
"4d6f8a0c2e4b6d8f0a2c4e6d8b0f2a4c6e8d0b2f4a6c8e0d2b4a6c8e0d2f4b6a8" +
"c0e2d4f6a8b0c2e4d6f8a0b2c4e6d8f0a2c4e6b8d0f2a4c6e8b0d2f4a6c8e0d2f", 16);
static final BigInteger q = new BigInteger(
"400000000000000000000000000000000000000000000000000000000000000b", 16);
static final BigInteger g = new BigInteger(
"7b9a4f1b3c5d7e9f0a2c4e6d8f0b2a4c6e8d0f2b4a6c8e0d2f4a6c8b0e2d4f6a8" +
"c0e2d4f6a8b0c2e4d6f8a0b2c4e6d8f0a2c4e6b8d0f2a4c6e8b0d2f4a6c8e0d2f" +
"4a6c8b0e2d4f6a8c0e2d4f6a8b0c2e4d6f8a0b2c4e6d8f0a2c4e6b8d0f2a4c6e8" +
"d0b2f4a6c8e0d2f4a6c8e0d2b4a6c8b0e2d4f6a8c0e2d4f6a8b0c2e4d6f8a0b2c", 16);
// Sample keypair.
static BigInteger x; // private scalar
static BigInteger y; // public value
public static void main(String[] args) throws Exception {
keygen();
String message = "Transfer 1000 satoshis to 1BvBMSEYstWetqTFn5Au4m4GFg7gJaXN7A";
BigInteger[] sig = sign(message.getBytes("UTF-8"));
System.out.println("Message: " + message);
System.out.println("Challenge e (hex): " + sig[0].toString(16));
System.out.println("Response s (hex): " + sig[1].toString(16));
boolean ok = verify(message.getBytes("UTF-8"), sig);
System.out.println("Valid signature verifies: " + ok);
String tampered = message.replace("1000", "9000");
boolean bad = verify(tampered.getBytes("UTF-8"), sig);
System.out.println("Tampered message verifies: " + bad);
}
static void keygen() {
SecureRandom rng = new SecureRandom();
do {
x = new BigInteger(q.bitLength(), rng);
} while (x.compareTo(BigInteger.ONE) < 0 || x.compareTo(q) >= 0);
y = g.modPow(x, p);
}
static BigInteger[] sign(byte[] message) throws Exception {
SecureRandom rng = new SecureRandom();
BigInteger k, r;
do {
do {
k = new BigInteger(q.bitLength(), rng);
} while (k.compareTo(BigInteger.ONE) < 0 || k.compareTo(q) >= 0);
r = g.modPow(k, p);
} while (r.equals(BigInteger.ZERO) || r.equals(BigInteger.ONE));
BigInteger e = hashToInt(message, r);
BigInteger s = k.subtract(x.multiply(e)).mod(q);
return new BigInteger[]{e, s};
}
static boolean verify(byte[] message, BigInteger[] sig) throws Exception {
BigInteger e = sig[0];
BigInteger s = sig[1];
// r' = g^s * y^e mod p, using a 2-exp for clarity.
BigInteger gs = g.modPow(s, p);
BigInteger ye = y.modPow(e, p);
BigInteger rPrime = gs.multiply(ye).mod(p);
BigInteger ePrime = hashToInt(message, rPrime);
return ePrime.equals(e);
}
static BigInteger hashToInt(byte[] message, BigInteger r) throws Exception {
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] rBytes = r.toByteArray();
md.update(message, 0, message.length);
md.update(rBytes, 0, rBytes.length);
byte[] digest = md.digest();
BigInteger h = new BigInteger(1, digest);
return h.mod(q);
}
}
Code Explanation - Line by Line
The group parameters p, q, g are declared as static BigInteger constants. In a production system you would either generate them once and persist them, or use a named group from a NIST or SEC standard. The toy 512-bit prime here is small enough that the demo runs in under a second but large enough that the discrete log is not trivially broken by trial division.
The keygen method uses SecureRandom, not java.util.Random, because the security of Schnorr relies on x being unpredictable. The loop guards against the astronomically unlikely event of drawing x = 0, which would make y = 1 and the signature trivially forgeable. The public value y = g^x mod p uses modPow, which is constant-time in the JDK since Java 8.
The sign method does the same careful nonce generation. The double loop guards against k = 0 (which leaks the private key, since s = -x*e mod q, so x = -s * inverse(e) mod q) and against r = 0 or r = 1 (which would let the verifier reconstruct r' incorrectly). The challenge e is the SHA-256 hash of the message concatenated with the commitment r, reduced mod q so that s is in the proper range. The response s = k - x*e mod q uses BigInteger's mod, which always returns a non-negative result.
The verify method reconstructs r' = g^s * y^e mod p and re-hashes (message, r'). A real production verifier would use multi-exponentiation to compute g^s * y^e in one go, which is about 1.5x faster than two separate modPow calls; we keep them separate here for clarity. The check ePrime.equals(e) is constant-time because BigInteger.equals is implemented as a length-and-magnitude comparison rather than a short-circuit loop.
The hashToInt helper concatenates the message and the commitment before hashing. The order of concatenation matters and must match between signer and verifier. Many implementations prefix a domain separation tag such as the ASCII bytes of "Schnorr/SHA-256/" to prevent the same signature from being valid in two different protocols.
Sample Input and Output
Message: Transfer 1000 satoshis to 1BvBMSEYstWetqTFn5Au4m4GFg7gJaXN7A Challenge e (hex): 7d3e9a4b1c8f2e6d5a3b1c9f4e7d2a5b... Response s (hex): 6f1e2d3c4b5a6978876a5b4c3d2e1f0a... Valid signature verifies: true Tampered message verifies: false
The output shows that a signature produced by sign() is accepted by verify(), and that flipping a single digit in the message (1000 to 9000) causes the recomputed challenge to differ from the signed challenge, so the tampered verification returns false. The actual hex strings depend on the random key and nonce and will differ on every run.
Common Mistakes to Avoid
The single most catastrophic mistake in any Schnorr implementation is reusing the nonce k. If the same k is used to sign two different messages, the difference of the two s values gives k directly: (s1 - s2) = (k - x*e1) - (k - x*e2) = x*(e2 - e1) mod q, so x = (s1 - s2) * inverse(e2 - e1) mod q. This is the same flaw that broke Sony PlayStation 3 ECDSA signatures and leaked the private keys of countless early Bitcoin wallets. The fix is RFC 6979 deterministic nonces, which derive k from the message and the private key using HMAC, eliminating the need for randomness.
The second mistake is using java.util.Random or Math.random for x or k. Both are predictable from a few outputs, and a successful prediction lets the attacker recover the private key. Always use SecureRandom.
The third mistake is reducing the hash e mod q incorrectly. If the hash output is larger than q (which it is, since SHA-256 produces 256 bits and q is 256 bits), the mod operation is correct, but if you accidentally reduce mod (q-1) you get a wrong challenge and the signature never verifies. BigInteger.mod returns the result mod q; BigInteger.modPow with the modulus q also uses q; the trap is when you compute e mod (p-1) instead of e mod q.
The fourth mistake is forgetting to include the message in the hash. A signature scheme that signs only the commitment r signs nothing useful: an attacker who gets a signature (e, s) on commitment r can attach it to any message they like, since the verifier's hash is taken over (arbitrary message, r'). Always hash (message, r).
Real-World Applications
Schnorr over elliptic curves is the design basis of EdDSA (RFC 8032), which the JDK supports natively via KeyPairGenerator.getInstance("Ed25519") and which is the signature scheme used by SSH modern keys, age encryption, and the Signal sealed-sender protocol. The Taproot upgrade to Bitcoin (BIP-340, activated November 2021) replaced the secp256k1 ECDSA signatures with BIP-340 Schnorr signatures, enabling key aggregation, batch verification, and more private multi-signature transactions.
Schnorr identification is also the conceptual root of the FIDO2 WebAuthn standard: the device proves possession of a private key by responding to a server challenge, exactly the original interactive protocol Schnorr proposed. The Chaum-Pedersen protocol for proving that two group elements have the same discrete log without revealing it is a direct extension of Schnorr, and underlies the privacy-preserving ZK proofs used in Confidential Transactions and Zerocash.
In the Java enterprise world, Schnorr is rarely used directly because DSA and ECDSA are mandated by FIPS 186-4, but the Bouncy Castle provider ships a Schnorr implementation that you can reach through the JCA Signature API. If you are building a Bitcoin library, a Tor onion service, or a ZK proof system in Java, you will need to understand the Schnorr construction at this level of detail.
Conclusion
The Schnorr signature scheme is one of the cleanest and most provably secure digital signature constructions ever published, and the construction is the foundation for both the modern EdDSA standard and Bitcoin Taproot. We built a complete Java implementation over an integer group, walked through key generation, signing, verification, and tamper detection, and discussed the catastrophic consequences of nonce reuse. Next, study the EdDSA post in this same series to see the same idea specialized to Edwards curves, and the Ring Signature post to see how Schnorr can be extended to anonymize the signer within a group.
Comments
Comments
Post a Comment