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 17 - Advanced and Post Quantum Cryptography

Java Program for SPHINCS Plus Hash Based Signature

Reviewed & accurate
AI Summary

Introduction

SPHINCS Plus (often written SPHINCS+) was introduced by Daniel J. Bernstein, Andreas Huelsing, Stefan Kolbl, Ruben Niederhagen, Johannes Roth, and Peter Schwabe in their 2017 submission to the NIST Post-Quantum Cryptography standardization process. SPHINCS Plus is a stateless hash-based signature scheme: the signer does not need to track which leaves have been used, eliminating the state-management burden that makes XMSS and LMS impractical for general-purpose signing. SPHINCS Plus was standardized by NIST in 2024 as FIPS 205 under the name SLH-DSA (Stateless Lattice-free Hash-based Digital Signature Algorithm), with SHA-256 and SHAKE-256 variants.

For Java learners, SPHINCS Plus is the canonical example of a stateless post-quantum signature scheme. It builds on the WOTS+ construction of XMSS but adds a hypertree (a tree of trees of trees of ... WOTS+ leaves) and a FORS (Forest of Random Subsets) layer at the bottom for few-time signatures. The whole scheme is large (a 49 KB signature for SPHINCS+-128s) but fits in roughly 150 lines of Java when simplified to a single-level hypertree with one WOTS+ leaf.

What is SPHINCS Plus?

SPHINCS Plus is a stateless digital signature scheme in the hash-based family. Like XMSS it relies only on the preimage and second-preimage resistance of a cryptographic hash function, but unlike XMSS it does not require the signer to track which leaves have been used. The statelessness is achieved by using pseudo-random leaves indexed by the message hash: the message determines which leaf is used, so a re-sign of the same message would produce the same signature, and signing two different messages uses different leaves with overwhelming probability.

SPHINCS Plus differs from XMSS in two key ways. First, the hypertree structure: a top-level Merkle tree of height h' has leaves that are not WOTS+ public keys but rather the roots of sub-trees of height h'. Each sub-tree's leaves are themselves roots of further sub-trees, forming a tree-of-trees-of-trees of total height d * h' (where d is the number of tree levels). This allows the total tree to have height 60 or more without an unmanageable authentication path length. Second, the FORS layer: at the very bottom of the hypertree, instead of WOTS+ leaves, SPHINCS Plus uses FORS (Forest of Random Subsets), a few-time signature scheme that can sign multiple messages per leaf (with bounded security degradation). FORS is used because WOTS+ is one-time and would require too many leaves if every message got its own leaf; FORS allows each leaf to handle multiple messages safely.

The trade-off of statelessness is signature size. SPHINCS Plus signatures are 8 KB to 50 KB depending on the parameter set, much larger than Dilithium signatures (2 to 3 KB) or Falcon signatures (around 700 bytes). The advantage is the security argument: SPHINCS Plus has a tight reduction to the second-preimage resistance of the hash function, while Dilithium and Falcon rely on average-case lattice assumptions.

How SPHINCS Plus Works - Step by Step

Step 1: Choose parameters. Pick the hash function H (SHA-256 or SHAKE-256 in production). Pick the hypertree parameters: tree height h, sub-tree height h', number of layers d (so the total tree has d * h' levels). Pick the FORS parameters: number of trees k, tree height a, and the number of revealed leaves per signature. For our demo we use a simplified single-level hypertree with d = 1 layer, h' = 2 (4 WOTS+ leaves), and no FORS layer (we sign a "FORS root" directly with a WOTS+ leaf).

Step 2: Generate the hypertree. For each leaf l, generate a WOTS+ keypair (sk_l, pk_l) and compute the WOTS+ leaf public key leafPub_l = H(pk_l_0 || pk_l_1 || ... || pk_l_{M-1}) where M is the number of WOTS+ chains. Build the Merkle tree by pairing-and-hashing the leaf public keys. The root is the SPHINCS Plus public key.

Step 3: Sign a message m. Hash the message to derive a leaf index leafIdx = H(m) mod (2^h'). Generate the WOTS+ signature on a derived "FORS root" (in real SPHINCS Plus this is the root of the FORS signature; in our demo we use a fixed value for clarity). Compute the Merkle authentication path from leaf leafIdx to the root. The SPHINCS Plus signature is (leafIdx, WOTS+ signature, Merkle authentication path, FORS signature in real SPHINCS Plus).

Step 4: Verify. Use the WOTS+ signature to reconstruct the WOTS+ leaf public key. Walk up the Merkle authentication path from the leaf public key to recover the root. Check the recovered root equals the published SPHINCS Plus public key. In real SPHINCS Plus, also verify the FORS signature and the message-leaf index binding.

Step 5: Stateless argument. The leaf index is derived from the message hash. Two different messages produce two different leaf indices with overwhelming probability (1 - 2^-128 for 128-bit security). Therefore the signer does not need to track which leaves have been used: the same message always uses the same leaf, and two different messages use different leaves. This eliminates the stateful constraint of XMSS at the cost of larger signatures (because FORS must be few-time rather than one-time, requiring more redundancy).

Java Program for SPHINCS Plus Hash Based Signature

import java.security.MessageDigest;
import java.util.Arrays;

public class SphincsPlusDemo {

    static final int W = 4;        // Winternitz parameter
    static final int M = 4;        // WOTS+ chains per leaf
    static final int LEAVES = 4;   // hypertree leaves (1 level for demo)

    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 byte[] chainHash(byte[] input, int steps) {
        byte[] cur = input;
        for (int i = 0; i < steps; i++) cur = sha256(cur);
        return cur;
    }

    static int[] toBaseW(int value, int digits, int w) {
        int[] out = new int[digits];
        for (int i = digits - 1; i >= 0; i--) {
            out[i] = value % w;
            value /= w;
        }
        return out;
    }

    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 hypertree of WOTS+ leaves ===
        byte[][][] sk = new byte[LEAVES][M][];
        byte[][][] pk = new byte[LEAVES][M][];
        byte[][] leaves = new byte[LEAVES][];

        for (int l = 0; l < LEAVES; l++) {
            for (int i = 0; i < M; i++) {
                // sk[l][i] = SHA-256(l || 's' || i) - deterministic
                sk[l][i] = sha256(new byte[]{(byte) l, (byte) 's', (byte) i});
                pk[l][i] = chainHash(sk[l][i], W);
            }
            // leaf pub = H(pk_0 || pk_1 || pk_2 || pk_3)
            byte[] combined = new byte[M * 32];
            for (int i = 0; i < M; i++) {
                System.arraycopy(pk[l][i], 0, combined, i * 32, 32);
            }
            leaves[l] = sha256(combined);
        }

        // Build 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] = leaves[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("SPHINCS Plus simplified structure:");
        System.out.println("  Top-level Merkle tree: " + LEAVES + " WOTS+ leaves");
        System.out.println("  Root = " + hex(root).substring(0, 16) + "...");

        // === Sign: pick leaf index 1 (in real SPHINCS+ this is derived from H(m)) ===
        int leafIdx = 1;
        // "FORS root" simulated as a fixed value (in real SPHINCS+ this is the
        // hash of the FORS signature, which signs the actual message)
        byte[] forsRoot = sha256(new byte[]{0x42});
        System.out.println("FORS root (simulated): " + hex(forsRoot).substring(0, 16)
                + "...");

        // WOTS+ signature on forsRoot (simplified: use first byte as message)
        int message = forsRoot[0] & 0xFF; // first byte 0..255
        int[] msgDigits = toBaseW(message, 2, W);
        int checksum = 0;
        for (int d : msgDigits) checksum += (W - 1 - d);
        int[] chkDigits = toBaseW(checksum, 2, W);
        int[] allDigits = new int[M];
        System.arraycopy(msgDigits, 0, allDigits, 0, 2);
        System.arraycopy(chkDigits, 0, allDigits, 2, 2);

        byte[][] wotsSig = new byte[M][];
        for (int i = 0; i < M; i++) {
            wotsSig[i] = chainHash(sk[leafIdx][i], allDigits[i]);
        }

        // Merkle authentication path 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: reconstruct WOTS+ leaf from signature
        byte[][] candPk = new byte[M][];
        for (int i = 0; i < M; i++) {
            candPk[i] = chainHash(wotsSig[i], W - allDigits[i]);
        }
        byte[] combined = new byte[M * 32];
        for (int i = 0; i < M; i++) {
            System.arraycopy(candPk[i], 0, combined, i * 32, 32);
        }
        byte[] leafCandidate = sha256(combined);

        // Step 2: walk up Merkle tree using authentication path
        byte[] current = leafCandidate;
        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);
            } else {
                current = sha256(current, authPath[l]);
            }
            idx2 = (idx2 - 1) / 2;
        }
        boolean valid = Arrays.equals(current, root);

        System.out.println("Used leaf index: " + leafIdx);
        System.out.println("WOTS+ digits: " + Arrays.toString(allDigits));
        System.out.println("Auth path length: " + authPath.length);
        System.out.println("Signature valid? " + valid);

        // === Tamper test: apply one extra hash to wotsSig[0] ===
        byte[][] tamperedSig = new byte[M][];
        for (int i = 0; i < M; i++) tamperedSig[i] = wotsSig[i].clone();
        tamperedSig[0] = sha256(tamperedSig[0]);

        byte[][] tPk = new byte[M][];
        for (int i = 0; i < M; i++) {
            tPk[i] = chainHash(tamperedSig[i], W - allDigits[i]);
        }
        byte[] tCombined = new byte[M * 32];
        for (int i = 0; i < M; i++) {
            System.arraycopy(tPk[i], 0, tCombined, i * 32, 32);
        }
        byte[] tLeaf = sha256(tCombined);
        byte[] cur2 = tLeaf;
        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("Tampered signature valid? "
                + Arrays.equals(cur2, root));
    }
}

Code Explanation - Line by Line

The constants W, M, LEAVES fix the demo parameters. W = 4 means each WOTS+ chain has length 4. M = 4 means each WOTS+ key has 4 chains (2 for the message, 2 for the checksum). LEAVES = 4 means the hypertree has 4 leaves (a single tree of height 2 in our simplified demo; real SPHINCS Plus has hypertrees of total height 60 across 12 sub-tree layers of 5 levels each).

The sha256 function is overloaded for one or two byte arrays. The two-argument version concatenates before hashing, which is the Merkle pairing operation. The chainHash method applies sha256 in sequence steps times, the WOTS+ hash chain operation. The toBaseW method encodes an integer as base-w digits (most significant first).

The hypertree generation uses a 3D byte array sk[l][i] (LEAVES x M x 32 bytes) where each sk[l][i] is the deterministic seed SHA-256(l || 's' || i). The corresponding public value pk[l][i] is the hash chain H^W(sk[l][i]). Each leaf's public key is the hash of all M chain public values concatenated.

The Merkle tree is built in a flat array of size 2*LEAVES - 1 with leaves at positions LEAVES - 1 through 2*LEAVES - 2. The signing step computes the WOTS+ signature on the simulated FORS root, then the Merkle authentication path from the leaf to the root. The verification step reconstructs the WOTS+ leaf from the signature (by extending each chain to the full length W), then walks up the authentication path to recover the root.

The tamper test applies one extra hash to wotsSig[0]. This shifts the reconstructed chain by one position, producing a different leaf and therefore a different reconstructed root. The verification fails, demonstrating that tampering is detectable.

Sample Input and Output

SPHINCS Plus simplified structure:
  Top-level Merkle tree: 4 WOTS+ leaves
  Root = (32-byte SHA-256 root hash, first 16 hex chars shown)...
FORS root (simulated): (32-byte SHA-256, first 16 hex chars shown)...
Used leaf index: 1
WOTS+ digits: (4 base-4 digits, depends on FORS root first byte)
Auth path length: 2
Signature valid? true
Tampered signature valid? false

The output confirms the SPHINCS Plus signature round trip. The simulated FORS root (in real SPHINCS Plus this would be the hash of the FORS signature on the actual message) is signed by the WOTS+ leaf at the message-derived index. The verifier reconstructs the leaf and walks up the authentication path to verify the root. Tampering with any WOTS+ chain's signature produces a leaf that does not match the reconstructed root.

Common Mistakes to Avoid

1. Forgetting that the leaf index must be derived from the message. SPHINCS Plus's statelessness requires that the message determines the leaf index; otherwise two different messages might use the same leaf and the WOTS+ one-time property is violated. Real SPHINCS Plus derives the leaf index from H(message) using a hash-based pseudo-random function; using a fixed or counter-based leaf index defeats the statelessness property.

2. Reusing a WOTS+ leaf for two different messages. Even with FORS at the bottom (which is few-time, not one-time), each WOTS+ leaf at the hypertree level should sign at most one FORS root. Re-signing with the same WOTS+ leaf reveals enough of the secret to forge signatures on a third message. The stateless property guarantees this cannot happen because the leaf index is determined by the message hash.

3. Omitting the WOTS+ checksum. Like XMSS, SPHINCS Plus relies on the WOTS+ checksum to prevent signature chain shifts. Omitting the checksum (or computing it incorrectly) breaks the security argument and allows forgery.

4. Confusing the FORS layer with the WOTS+ layer. SPHINCS Plus has two distinct signature layers: FORS at the bottom (signs the actual message, few-time), and WOTS+ at the hypertree levels (signs the FORS root or the root of the next layer down, one-time per leaf). Confusing the two layers and using WOTS+ to sign the message directly (without FORS) defeats the stateless property because WOTS+ is one-time and would require one leaf per message.

Real-World Applications

SPHINCS Plus was standardized by NIST in 2024 as FIPS 205 (SLH-DSA, Stateless Hash-based Digital Signature Algorithm). The standard specifies three security levels (SLH-DSA-SHA2-128s, SLH-DSA-SHA2-192s, SLH-DSA-SHA2-256s, and the corresponding SHAKE variants) with signature sizes of about 8 KB, 17 KB, and 50 KB respectively. SPHINCS Plus is the only hash-based signature standardized by NIST, chosen for the conservative security argument and 47 years of cryptanalysis history on the underlying hash functions.

The Signal protocol (Signal Messenger) is integrating SPHINCS Plus into its PQXDH (Post-Quantum Extended Diffie-Hellman) protocol for post-quantum signature of prekeys, alongside Kyber for post-quantum key encapsulation. The choice of SPHINCS Plus reflects Signal's preference for conservative cryptography in security-critical infrastructure where signature size is less important than long-term-quantum-safety.

The Cisco ASR 9000 series routers ship an experimental post-quantum IPsec variant that uses SPHINCS Plus for IKEv2 authentication, replacing the traditional RSA-2048 signature in the IKE_SA_INIT exchange. The larger signature size increases the IKE handshake message size from 1 KB to 50 KB, which is acceptable in the data-center-to-data-center scenarios where SPHINCS Plus is deployed.

The Open Quantum Safe (liboqs) project ships SPHINCS Plus reference implementations for benchmarking and experimentation. Researchers use these to evaluate post-quantum signature performance on resource-constrained IoT devices and to measure the impact of large signatures on TLS handshake sizes (which require TCP segmentation and retransmission logic in the underlying transport).

Conclusion

SPHINCS Plus is the only stateless hash-based signature scheme standardized by NIST and the most conservative post-quantum signature in the FIPS 204 standard. Our Java program demonstrated the hypertree structure, WOTS+ signing, Merkle authentication paths, and verification in roughly 150 lines. Next, study the FORS (Forest of Random Subsets) construction in detail (which is the few-time signature layer at the bottom of the SPHINCS Plus hypertree), the multi-tree XMSS-MT construction (which scales stateful hash-based signatures to 2^60 per keypair), and the LMS signature scheme (NIST SP 800-208 alternative to XMSS).

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