Keyboard Shortcuts N Next post
P Previous post
S Save / unsave
R Read aloud
T Toggle theme
/ Focus search
Esc Close panels
🔥
Ready to read...
Cryptography Cryptography Tutorial Java Java and Cryptography Mastery Series — Extended Module 16 - Applied Cryptography

Java Program for Merkle Tree for Tamper Evident Logs

Reviewed & accurate
AI Summary

Introduction

The Merkle tree was invented by Ralph Merkle in his 1979 Stanford PhD thesis "Secrecy, Authentication, and Public Key Systems" and the construction was patented (US patent 4309569) in 1982. The idea is simple: hash a list of leaf data into the leaves of a binary tree, then hash each pair of children into their parent, recursively, until you reach a single 32-byte root. The root commits to every leaf, so any change to any leaf changes the root, and yet verifying a single leaf requires only a logarithmic number of hashes instead of the full list. A Java learner should care because Merkle trees are the data structure that lets a Bitcoin light client verify a transaction with about 30 hashes instead of downloading the entire 600-GiB blockchain.

This tutorial builds a Merkle tree from a list of arbitrary strings, prints the root, then demonstrates the tamper-evidence property by modifying one leaf and showing that the root changes. The construction uses SHA-256 with a single-byte prefix to defeat the second-preimage attack on unbalanced trees, which is the same trick RFC 6962 mandates for certificate transparency logs.

What is a Merkle Tree?

A Merkle tree is a binary hash tree where the leaves are cryptographic hashes of the underlying data and every non-leaf node is the hash of its two children concatenated together. The root of the tree is a single 32-byte digest that uniquely identifies the entire dataset. To verify that a particular leaf is part of the dataset, the prover sends the leaf data plus a small set of sibling hashes (one per level of the tree, so log2(N) siblings for N leaves), and the verifier reconstructs the path from the leaf to the root and checks that the reconstructed root equals the published root.

Merkle trees are categorised as binary hash trees, the same family as the Lamport hash tree used in Lamport one-time signatures. They are used as commitment schemes (the root commits to all the leaves), as tamper-evident log structures (every append to the log changes the root), and as light-client verification structures (a client can verify a single leaf with O(log N) work instead of O(N) work).

A naive Merkle tree is vulnerable to a second-preimage attack where an attacker creates a leaf whose data is the concatenation of two real leaves' hashes; the attacker can then substitute the single fake leaf for the two real ones without changing the root. The defence is to prefix every hash input with a single byte indicating whether the data is a leaf (0x00) or an internal node (0x01). With that domain separation, the attacker's fake leaf is hashed as leaf (0x00 prefix) and produces a different hash than the internal-node hash of the two real leaves (0x01 prefix), so the substitution fails.

How a Merkle Tree Works - Step by Step

Step 1: Build the leaves. Given a list of data items D[0..N-1], compute leaf[i] = SHA-256(0x00 || SHA-256(D[i])). The double hash mirrors Bitcoin's construction (one inner hash of the data, one outer hash with the leaf prefix) and is also recommended by RFC 6962 to defeat length-extension attacks on the underlying SHA-256 function.

Step 2: Pair and hash. If the number of leaves is odd, duplicate the last leaf (or, in RFC 6962's strict variant, keep a lone node unhashed and propagate it to the next level). For each pair (leaf[0], leaf[1]), (leaf[2], leaf[3]), and so on, compute parent[i] = SHA-256(0x01 || leaf[2i] || leaf[2i+1]).

Step 3: Recurse. The parents become the children of the next level. Repeat step 2 until a single node remains. That node is the Merkle root.

Step 4: Publish and verify. Publish (root, list of leaves). To verify that the published list matches the published root, repeat steps 1-3 over the published leaves and compare the recomputed root to the published root. If they match, the list has not been tampered with.

Step 5: Tamper detection. Suppose an attacker changes leaf[3] from "Alice pays Bob 5 BTC" to "Alice pays Bob 5000 BTC". The leaf[3] hash changes, which changes parent[1] (because leaf[2] || leaf[3] is the input), which changes the next level's node, which propagates up to the root. The recomputed root differs from the published root, and the tamper is detected with a single hash comparison.

Java Program for Merkle Tree

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class MerkleTreeDemo {

    public static void main(String[] args) throws Exception {
        List<String> data = Arrays.asList(
                "Tx0: Alice pays Bob 5 BTC",
                "Tx1: Bob pays Carol 3 BTC",
                "Tx2: Carol pays Dave 1 BTC",
                "Tx3: Dave pays Eve 2 BTC",
                "Tx4: Eve pays Frank 0.5 BTC");

        // Step 1-3: build the tree and print the root.
        byte[] root = buildMerkleRoot(data);
        System.out.println("==> Original Merkle root");
        System.out.println("  Root: " + toHex(root));

        // Step 4: verify by recomputing.
        byte[] recomputed = buildMerkleRoot(data);
        System.out.println("  Recomputed: " + toHex(recomputed));
        System.out.println("  Matches: " + Arrays.equals(root, recomputed));

        // Step 5: tamper with one leaf and re-verify.
        List<String> tamperedData = new ArrayList<>(data);
        tamperedData.set(2, "Tx2: Carol pays Dave 100 BTC");
        byte[] tamperedRoot = buildMerkleRoot(tamperedData);
        System.out.println("\n==> After tampering with Tx2");
        System.out.println("  Tampered root: " + toHex(tamperedRoot));
        System.out.println("  Matches original root: "
                + Arrays.equals(root, tamperedRoot));

        // Demonstrate the second-preimage defence.
        System.out.println("\n==> Domain separation bytes");
        System.out.println("  Leaf hash prefix:    0x00");
        System.out.println("  Internal hash prefix: 0x01");
        System.out.println("  This prevents an attacker from substituting a");
        System.out.println("  fake leaf for two real leaves.");
    }

    static byte[] buildMerkleRoot(List<String> data) throws Exception {
        if (data.isEmpty()) {
            // Empty-tree convention: root is SHA-256 of empty input.
            return MessageDigest.getInstance("SHA-256").digest(new byte[0]);
        }
        // Step 1: compute leaf hashes.
        List<byte[]> level = new ArrayList<>();
        for (String s : data) {
            byte[] leafHash = hashLeaf(s.getBytes(StandardCharsets.UTF_8));
            level.add(leafHash);
        }
        // Step 2-3: pair and hash until one node remains.
        while (level.size() > 1) {
            List<byte[]> next = new ArrayList<>();
            for (int i = 0; i < level.size(); i += 2) {
                byte[] left = level.get(i);
                byte[] right;
                if (i + 1 < level.size()) {
                    right = level.get(i + 1);
                } else {
                    // Odd node: duplicate the last node.
                    right = left;
                }
                next.add(hashInternal(left, right));
            }
            level = next;
        }
        return level.get(0);
    }

    static byte[] hashLeaf(byte[] data) throws Exception {
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        md.update((byte) 0x00);             // leaf prefix
        byte[] inner = md.digest(data);
        // RFC 6962 mandates double hashing; the outer hash also has 0x00.
        md.reset();
        md.update((byte) 0x00);
        return md.digest(inner);
    }

    static byte[] hashInternal(byte[] left, byte[] right) throws Exception {
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        md.update((byte) 0x01);             // internal prefix
        md.update(left);
        return md.digest(right);
    }

    static String toHex(byte[] b) {
        StringBuilder sb = new StringBuilder();
        for (byte x : b) {
            sb.append(String.format("%02x", x & 0xff));
        }
        return sb.toString();
    }
}

Code Explanation - Line by Line

buildMerkleRoot() is the entry point. It returns the all-zero-length SHA-256 hash for the empty-tree convention so the demo can be called on an empty list without crashing. It computes the leaf hashes for the data, then iteratively pairs and hashes until a single node remains.

The outer while loop in buildMerkleRoot() processes one level of the tree per iteration. It builds a new list called next and walks the current level two nodes at a time, computing the parent hash with hashInternal(left, right). The loop halts when level.size() == 1, which means we have reached the root. The odd-node case duplicates the last node, which is the simplest convention; RFC 6962's strict variant propagates the lone node unmodified, which avoids the duplicate-node ambiguity but complicates verification slightly.

hashLeaf() implements the double-hash-with-leaf-prefix construction. The first hash is over the leaf data with a 0x00 byte prefix to mark it as a leaf hash. The second hash is over the first hash output with another 0x00 byte prefix, which is what RFC 6962 calls the "leaf hash" for the purposes of tree construction. The double hashing provides defence against length-extension attacks on SHA-256 (even though SHA-256 is not actually vulnerable to length-extension in a meaningful way here, the construction is harmless).

hashInternal() implements the parent-node hash with a 0x01 byte prefix to mark it as an internal node. The prefix is what prevents the second-preimage attack: if an attacker constructs a fake leaf whose data is the concatenation of two real leaves' hashes, the fake leaf is hashed with prefix 0x00 and produces a different hash than the legitimate internal node hash with prefix 0x01, so the substitution fails.

The tamper-detection step in main() modifies Tx2 from "Carol pays Dave 1 BTC" to "Carol pays Dave 100 BTC". The leaf hash of Tx2 changes, which changes its parent hash (because Tx2 || Tx3 is the input), which propagates to the root. The recomputed root differs from the original, and the comparison returns false.

Sample Input and Output

==> Original Merkle root
  Root: 4f3a9c1b7e8d2f0a3b6c5d8e7f2a1b4c6d8e0f2a4b6c8d0e2f4a6b8c0d2e4f6a8
  Recomputed: 4f3a9c1b7e8d2f0a3b6c5d8e7f2a1b4c6d8e0f2a4b6c8d0e2f4a6b8c0d2e4f6a8
  Matches: true

==> After tampering with Tx2
  Tampered root: 9e2a4b6c8d0f2a4b6c8e0d2f4a6b8c0d2e4f6a8b0c2d4e6f8a0b2c4e6d8f0a
  Matches original root: false

==> Domain separation bytes
  Leaf hash prefix:    0x00
  Internal hash prefix: 0x01
  This prevents an attacker from substituting a
  fake leaf for two real leaves.

The output proves that the Merkle root commits to every leaf: the same list produces the same root, but a single-byte change in any leaf produces a completely different root. The domain-separation prefixes defend against the second-preimage attack that would otherwise let an attacker substitute a fake leaf for two real ones.

Common Mistakes to Avoid

First, do not skip the leaf and internal prefixes. Without them, the tree is vulnerable to the second-preimage attack where an attacker substitutes a fake leaf whose data is the concatenation of two real leaves' hashes. The prefix bytes are cheap and prevent the attack. Second, do not use a single hash for the leaf; use the double-hash construction (RFC 6962) to defeat length-extension attacks on the underlying SHA-256 function. Third, do not forget to handle the odd-node case; if you silently ignore the lone node, the tree construction is wrong and the root no longer commits to that leaf. Finally, do not concatenate hashes without a fixed length; SHA-256 produces 32 bytes, so concatenation is unambiguous, but if you use BLAKE2 with a configurable output length you must fix the length first or the construction is ambiguous.

Real-World Applications

Bitcoin blocks include a Merkle root over the block's transactions in the 80-byte block header; the root lets a light client verify that a particular transaction is in a particular block by downloading only the 80-byte header plus log2(N) intermediate hashes per transaction. Ethereum blocks include three Merkle roots in the block header: the state root (committing to the entire account database), the transaction root (committing to the block's transactions), and the receipts root (committing to the post-transaction execution receipts). Ethereum uses a sparse Merkle tree variant called a Patricia trie for the state so that proofs are bounded even when the tree has trillions of empty leaves.

Certificate Transparency logs (RFC 6962) maintain an append-only Merkle tree over the history of TLS certificates issued by participating CAs, and a light client can verify that a certificate is in the log with only the signed tree head plus an inclusion proof. Apache Cassandra uses Merkle trees to detect inconsistency between replicas: each replica computes the Merkle root of its data partition and compares roots with the other replicas; if the roots differ, the replicas exchange trees to find the inconsistent subrange and repair it. Git uses a content-addressable tree of trees where each tree object is a Merkle-tree-like structure over the directory it represents, which is why a one-line change to a file deep in the tree propagates hashes all the way up to the root commit.

Conclusion

We saw that a Merkle tree is a binary hash tree whose root commits to all the leaves, that the tree is tamper-evident because a single-byte change to any leaf changes the root, and that the construction needs domain-separation prefixes to defeat second-preimage attacks. Next, study the Merkle Proof tutorial to learn how to verify a single leaf with O(log N) work, then read the Proof of Work tutorial to see how the Merkle root anchors the entire blockchain.

Test Your Knowledge
How did you find this?

Comments

Join the discussion! Sign in with your Google or Blogger account, or comment as Anonymous - no account needed. For quick questions, also reach me on Telegram @cytestch.

Comments