Introduction
Ralph Merkle introduced the Merkle signature scheme in his 1979 Ph.D. thesis "Secrecy, Authentication, and Public Key Systems" at Stanford University. The thesis proposed a way to extend Lamport's one-time signature into a many-time signature by combining N Lamport (or other OTS) keypairs into a single Merkle tree whose root is the public key. Each leaf of the tree is the hash of one OTS public key, and signing with leaf i requires revealing the i-th OTS signature plus a Merkle authentication path from leaf i to the root. The verifier re-derives the root from the OTS public key (which it reconstructs from the OTS signature) and the authentication path, and checks the re-derived root against the published public key.
For Java learners, the Merkle signature scheme is the canonical bridge between one-time signatures and stateful many-time signatures. It exercises the SHA-256 digest API, byte array manipulation, and binary tree traversal. The whole scheme fits in roughly 100 lines of Java and is the direct ancestor of the XMSS standard (RFC 8391) which uses WOTS+ leaves in a multi-tree construction for post-quantum signature security.
What is Merkle Signature Scheme?
The Merkle signature scheme (MSS) is a stateful digital signature scheme in the hash-based family. Like the Lamport signature it relies only on the preimage resistance of a cryptographic hash function, but unlike the Lamport signature it can sign many messages (up to N, where N is the number of leaves in the Merkle tree) under a single public key. The public key is just the Merkle root, which is one hash output regardless of N.
The scheme differs from Lamport in that it requires stateful signing: each leaf can be used at most once, so the signer must keep track of which leaves have been consumed. This statefulness is the main practical limitation of MSS and motivated the development of XMSS (which adds multi-tree structure to reduce the state size) and SPHINCS Plus (which uses pseudo-random leaves to make the scheme stateless). The Merkle tree is a binary tree of height h, so it has 2^h leaves and authentication paths of length h. For h = 20 the tree supports 1 million signatures and each authentication path is 20 hash values long.
The construction works as follows. Generate 2^h one-time keypairs (sk_1, pk_1), ..., sk_{2^h}, pk_{2^h}. Place the hash of each OTS public key at the corresponding leaf of a Merkle tree. Compute the tree by pairing-and-hashing upward until a single root remains. The public key is the root. To sign with leaf i, sign the message with the OTS keypair (sk_i, pk_i), then provide both the OTS signature and the OTS public key pk_i (since the verifier does not have it stored) along with the Merkle authentication path from leaf i to the root. The verifier checks the OTS signature against pk_i, hashes pk_i to get leaf i, and walks up the authentication path to re-derive the root, which must match the published public key.
How Merkle Signature Scheme Works - Step by Step
Step 1: Choose the tree height h. The number of leaves is 2^h, so this is the maximum number of signatures per public key. Common choices are h = 10 (1024 signatures per key), h = 20 (about 1 million signatures per key), and h = 25 (about 33 million signatures per key, used in some XMSS parameter sets). For our demo we use h = 2, giving 4 leaves.
Step 2: Generate 2^h one-time keypairs. For our demo we simplify each OTS keypair to a single secret sk_i and a public value pk_i = SHA-256(sk_i) (a Lamport keypair would have 2L secret values per OTS key, but we strip this down to a single value for clarity). The OTS public key is pk_i and the OTS signature on a message m is simply "reveal sk_i such that H(sk_i) = pk_i", with the message encoded into the choice of which OTS instance to use (in real MSS the message is signed by the OTS itself, but here we use the OTS-leaf-index as the message surrogate).
Step 3: Build the Merkle tree. Place leaf_i = H(pk_i) at position 2^h - 1 + i in a flat array of size 2^{h+1} - 1. For each internal node at position i (starting from the bottom up), compute tree[i] = H(tree[2i + 1] || tree[2i + 2]). The root is tree[0].
Step 4: Sign with leaf index i. Compute the OTS signature on the message (in our demo, the OTS signature is just the secret sk_i). Compute the Merkle authentication path: for each level from the leaf to the root, record the sibling hash. The signature is (OTS signature, Merkle authentication path).
Step 5: Verify. Hash the OTS signature to recover the OTS public key pk_i, then hash pk_i to get the leaf value. Walk up the authentication path: at each level, concatenate the current hash with the sibling hash (in the correct left/right order) and hash. The final hash must equal the published root. If the OTS signature is valid (which our simplified demo checks by comparing the hash of the revealed secret to the published pk_i) and the Merkle path is valid, the signature is accepted.
Java Program for Merkle One Time Signature Scheme
import java.security.MessageDigest;
import java.util.Arrays;
public class MerkleOtsDemo {
static final int LEAVES = 4; // 2^2 = 4 leaves, tree height h = 2
static byte[] sha256(byte[] data) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
return md.digest(data);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static byte[] sha256(byte[] a, byte[] b) {
byte[] combined = new byte[a.length + b.length];
System.arraycopy(a, 0, combined, 0, a.length);
System.arraycopy(b, 0, combined, a.length, b.length);
return sha256(combined);
}
static String hex(byte[] b) {
StringBuilder sb = new StringBuilder();
for (byte x : b) sb.append(String.format("%02x", x));
return sb.toString();
}
public static void main(String[] args) {
// === Generate LEAVES OTS keypairs ===
// (simplified: each OTS public key is a single SHA-256 hash, not a Lamport vector)
byte[][] sk = new byte[LEAVES][];
byte[][] pk = new byte[LEAVES][];
for (int i = 0; i < LEAVES; i++) {
// Deterministic seed for reproducible demo output
sk[i] = sha256(new byte[]{(byte) 's', (byte) i});
pk[i] = sha256(sk[i]);
}
// === Build the Merkle tree (flat array) ===
int total = 2 * LEAVES - 1;
byte[][] tree = new byte[total][];
for (int i = 0; i < LEAVES; i++) {
tree[LEAVES - 1 + i] = sha256(pk[i]); // leaf = H(pk_i)
}
for (int i = LEAVES - 2; i >= 0; i--) {
tree[i] = sha256(tree[2 * i + 1], tree[2 * i + 2]);
}
byte[] root = tree[0];
System.out.println("Merkle tree with " + LEAVES + " leaves (height "
+ (int)(Math.log(LEAVES) / Math.log(2)) + "):");
System.out.println(" Root = " + hex(root).substring(0, 16) + "...");
// === Sign with leaf index 1 (the second leaf) ===
int leafIdx = 1;
// OTS signature: reveal sk[leafIdx]
byte[] otsSignature = sk[leafIdx];
// Merkle authentication path: siblings on the way from leaf to root
int height = (int) (Math.log(LEAVES) / Math.log(2));
byte[][] authPath = new byte[height][];
int idx = LEAVES - 1 + leafIdx;
int level = 0;
while (idx > 0) {
int sib = (idx % 2 == 0) ? idx - 1 : idx + 1;
authPath[level++] = tree[sib];
idx = (idx - 1) / 2;
}
// === Verify ===
// Step 1: hash the OTS signature to recover the OTS public key pk_i
byte[] recoveredPk = sha256(otsSignature);
if (!Arrays.equals(recoveredPk, pk[leafIdx])) {
System.out.println("OTS verification failed");
return;
}
// Step 2: hash pk_i to get the leaf
byte[] current = sha256(recoveredPk);
// Step 3: walk up the authentication path
int idx2 = LEAVES - 1 + leafIdx;
for (int l = 0; l < authPath.length; l++) {
int sib = (idx2 % 2 == 0) ? idx2 - 1 : idx2 + 1;
if (sib < idx2) {
current = sha256(authPath[l], current); // sibling on left
} else {
current = sha256(current, authPath[l]); // sibling on right
}
idx2 = (idx2 - 1) / 2;
}
boolean valid = Arrays.equals(current, root);
System.out.println("Signing with leaf index " + leafIdx);
System.out.println("OTS signature = sk[" + leafIdx + "] (32 bytes)");
System.out.println("Auth path length = " + authPath.length + " sibling hashes");
System.out.println("Verified root matches? " + valid);
// === Tamper test: try to sign with a fake secret ===
byte[] fakeSig = sha256(new byte[]{(byte) 0xFF});
byte[] fakePk = sha256(fakeSig);
byte[] fakeLeaf = sha256(fakePk);
byte[] cur2 = fakeLeaf;
int idx3 = LEAVES - 1 + leafIdx;
for (int l = 0; l < authPath.length; l++) {
int sib = (idx3 % 2 == 0) ? idx3 - 1 : idx3 + 1;
if (sib < idx3) {
cur2 = sha256(authPath[l], cur2);
} else {
cur2 = sha256(cur2, authPath[l]);
}
idx3 = (idx3 - 1) / 2;
}
System.out.println("Fake signature accepted? "
+ Arrays.equals(cur2, root));
}
}
Code Explanation - Line by Line
The constant LEAVES = 4 fixes the tree size at 4 leaves, giving height 2. The sha256 function is overloaded to accept either a single byte array or two byte arrays; the two-argument version concatenates them before hashing, which is the standard Merkle tree pairing operation. The hex helper formats a byte array as a lowercase hex string for display.
The key generation loop creates LEAVES OTS keypairs. Each sk[i] is the SHA-256 of a deterministic seed (so the demo output is reproducible); each pk[i] is the SHA-256 of sk[i]. In real MSS, each pk[i] would be a Lamport-style vector of 2L hashes; we strip this down to a single hash for clarity.
The tree-building loop uses a flat array of size 2*LEAVES - 1 (the standard layout for a complete binary tree). Leaves occupy positions LEAVES - 1 through 2*LEAVES - 2, and internal node i has children at 2i + 1 and 2i + 2. The loop fills internal nodes from the bottom up. The root is at position 0.
The authentication path computation walks from the chosen leaf (at index LEAVES - 1 + leafIdx) up to the root, recording the sibling hash at each level. The sibling index is idx - 1 if idx is even (left child) or idx + 1 if idx is odd (right child). The parent is at (idx - 1) / 2. This produces an authentication path of length equal to the tree height (2 in our demo).
The verification loop performs the inverse operation: starting from the leaf hash, it walks up the authentication path, concatenating with the sibling hash in the correct left/right order (sibling on the left if the current index is even, on the right if odd). The final hash must equal the published root. The tamper test attempts to sign with a fake secret; because the fake secret does not match any leaf, the re-derived root does not match and verification fails.
Sample Input and Output
Merkle tree with 4 leaves (height 2): Root = (32-byte SHA-256 root hash) Signing with leaf index 1 OTS signature = sk[1] (32 bytes) Auth path length = 2 sibling hashes Verified root matches? true Fake signature accepted? false
The output confirms the Merkle signature scheme works end to end. The root is a single 32-byte hash regardless of the tree size (a major advantage over publishing all OTS public keys directly). The legitimate signature on leaf 1 verifies because the reconstructed root matches the published root. The fake signature (signing with a different secret sk that does not correspond to leaf 1) reconstructs a different root and is rejected.
Common Mistakes to Avoid
1. Forgetting to include the OTS public key in the signature. In real MSS the verifier does not know which OTS public key is being used (since the public key is just the Merkle root), so the signature must include the OTS public key along with the OTS signature and the Merkle authentication path. Omitting the OTS public key prevents the verifier from reconstructing the leaf hash. Our demo sidesteps this by hard-coding the OTS public keys in the verifier, but real implementations must transmit the OTS public key.
2. Confusing left and right sibling order in the authentication path. When concatenating two hashes for the Merkle pairing, the order matters: H(sibling || current) if the sibling is on the left, H(current || sibling) if the sibling is on the right. Reversing the order produces a different hash and silently breaks verification. The standard fix is to record a "direction bit" per level of the authentication path indicating whether the sibling is on the left or the right.
3. Reusing the same OTS leaf for two signatures. Each OTS keypair can be used exactly once; using the same leaf for two messages reveals enough of the OTS secret to forge signatures on other messages. Real MSS implementations maintain a leaf counter (or a bitmap of used leaves) and increment after each signature; failing to increment is a critical security bug.
4. Choosing a tree height h that is too small for the application lifetime. Each leaf is consumed once, so the tree supports at most 2^h signatures. If you need to sign more messages than 2^h, you must generate a new keypair, which invalidates the existing public key. Choosing h too small forces expensive rekeying; choosing h too large wastes storage for the leaf counter and the unused OTS secrets.
Real-World Applications
The Merkle signature scheme is the foundation of the XMSS standard (RFC 8391, published in 2018). XMSS uses WOTS+ leaves in a Merkle tree to support 2^h signatures per keypair; typical parameters are h = 20 (about 1 million signatures) with SHA-256, giving signatures of about 2.5 KB. XMSS is implemented in the Bouncy Castle Java cryptography library as org.bouncycastle.pqc.crypto.xmss.XMSSSigner and is the standardized hash-based signature for DNSSEC root-signing ceremonies and for long-term document archival.
The German Federal Office for Information Security (BSI) recommends XMSS as the preferred post-quantum signature scheme for long-term-quantum-safe document signing, because the scheme has a tight security reduction to the second-preimage resistance of the underlying hash function and supports stateful operation that prevents key reuse.
The Open Quantum Safe (liboqs) project ships XMSS reference implementations for benchmarking and experimentation. Researchers use these to evaluate post-quantum signature performance on resource-constrained IoT devices, where the small verification cost of hash-based signatures (no big-integer arithmetic, only SHA-256) is an advantage over lattice-based signatures.
Bitcoin's Simple Payment Verification (SPV) protocol uses a Merkle tree to authenticate transactions in a block, though this is a different use (data integrity, not digital signatures). The Merkle tree structure originated in Ralph Merkle's 1979 thesis and is one of the most widely deployed data structures in modern cryptography, used in Git commit graphs, BitTorrent piece verification, Apache Cassandra's anti-entropy repair, and Certificate Transparency logs.
Conclusion
Merkle's signature scheme is the bridge from one-time Lamport signatures to many-time hash-based signatures. Our Java program demonstrated OTS keypair generation, Merkle tree construction, authentication path derivation, and verifier root reconstruction in roughly 100 lines. Next, study the Winternitz OTS (which reduces per-signature size by chaining hashes), the multi-tree XMSS construction (which scales to 2^60 signatures per keypair with multi-level Merkle trees), and the SPHINCS Plus hypertree (which makes the scheme stateless by using pseudo-random leaves).
Comments
Comments
Post a Comment