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 Interview Questions Java Java and Cryptography Interview Series Module 26 - Authentication Protocols and Modern Crypto

Java Program for Cryptocurrency Wallet BIP32 HD Wallet from Scratch

Reviewed & accurate
AI Summary

Introduction

A Hierarchical Deterministic (HD) wallet, standardised as Bitcoin Improvement Proposal 32 (BIP-32, Pieter Wuille, February 2012) with the recovery mnemonic standard BIP-39 (Marek Palatinus, Pavol Rusnak, March 2013) and the address format BIP-44 (Marek Palatinus, Pavol Rusnak, October 2014), is the foundation of every modern cryptocurrency wallet - from Bitcoin Core's wallet to MetaMask, Trust Wallet, Electrum, and Ledger Live. The crypto wallet basics java topic is foundational because one seed phrase generates billions of addresses deterministically, the same seed restores the full wallet on any compatible device, and the derivation paths (m/44'/0'/0'/0/0 for Bitcoin mainnet, m/44'/60'/0'/0/0 for Ethereum mainnet) are the addressing scheme every blockchain developer must understand.

For a Java learner, the crypto wallet basics java topic is the difference between "I have a Bitcoin address" and "I have a 12-word seed that deterministically produces all my addresses": the seed is the master secret, the derivation paths are the addressing tree, and the CKD (Child Key Derivation) function is the HMAC-SHA512-based recursive key generation that lets a wallet derive unlimited keys without storing them. This tutorial implements BIP-32 from scratch on the secp256k1 curve using pure JDK BigInteger math and javax.crypto.Mac for HMAC-SHA512.

What is Crypto Wallet Basics?

A cryptocurrency wallet is a key manager: it generates, stores, and uses ECDSA keypairs on the secp256k1 curve (Bitcoin) or secp256r1 curve (Ethereum's EIP-212 derivation chain), signs transactions, and derives addresses deterministically. The category of an HD wallet is hierarchical key derivation, a strict superset of single-key wallets; an HD wallet generates a tree of keys from a single seed using HMAC-SHA512 and elliptic-curve scalar arithmetic. The defining trait of BIP-32 is determinism: the same seed produces the same tree, so a 12-word mnemonic (BIP-39) is a portable backup of the entire wallet.

The distinguishing trait versus a random keypool (Bitcoin Core's original wallet pre-BIP-32): a random keypool requires a backup after every key generation; a BIP-32 HD wallet requires one backup of the seed at wallet creation. The trade-off is that any compromise of the seed compromises every derived key - a property mitigated by hardened derivation (BIP-32 path indices >= 2^31) which breaks the derivation chain at each hardened node, requiring the parent private key (not just the parent public key + chain code) to derive children.

How Crypto Wallet Basics Works - Step by Step

Step 1: Seed. Generate a 128-to-256-bit random seed S. (BIP-39 derives S from a mnemonic phrase plus an optional passphrase via PBKDF2-HMAC-SHA512 with 2048 iterations; we skip BIP-39 for this tutorial and use a direct random 32-byte seed to keep the code focused on BIP-32.)

Step 2: Master key. Compute I = HMAC-SHA512(key="Bitcoin seed", data=S). The left 32 bytes (I_L) are the master private key k_m; the right 32 bytes (I_R) are the master chain code c_m. Both are required for child derivation; the chain code adds 256 bits of HMAC keying material so leaking the master private key alone does not allow child derivation.

Step 3: Child key derivation (normal). For child index i in [0, 2^31-1]: I = HMAC-SHA512(key=c_parent, data=ser256(K_parent) || ser32(i)) where K_parent is the compressed public key (33 bytes) corresponding to k_parent. The left 32 bytes are added (as a private key) to k_parent: k_child = (parse256(I_L) + k_parent) mod n where n is the secp256k1 group order. The right 32 bytes are c_child. Normal derivation lets an observer with the parent's extended public key (public key + chain code) derive all non-hardened children - a property called "extended public key leakage" that hardened derivation was created to prevent.

Step 4: Child key derivation (hardened). For child index i in [2^31, 2^32-1]: I = HMAC-SHA512(key=c_parent, data=0x00 || ser256(k_parent) || ser32(i)). Hardened derivation uses the parent's private key directly (with a 0x00 prefix), so an attacker with a parent's extended public key + chain code cannot derive the hardened children - the derivation chain is broken at hardened nodes. This is why BIP-44 paths look like m/44'/0'/0'/0/0: the first three levels (purpose, coin type, account) are hardened; the last two (external/internal chain, address index) are normal so a watch-only wallet can derive addresses without the parent private key.

Step 5: Address. For Bitcoin, the address is Base58Check(0x00 || RIPEMD160(SHA256(compressed_pubkey))). For Ethereum, the address is the last 20 bytes of Keccak-256(uncompressed_pubkey_without_0x04_prefix). The Java JDK does not ship RIPEMD-160 or Keccak-256; for this tutorial we use the SHA-256 of the public key as a stand-in and note the substitution explicitly in the prose.

Step 6: Derivation path. BIP-44 paths look like m/44'/0'/0'/0/0 - m is the master, 44 is the purpose (BIP-44), 0 is the coin type (Bitcoin mainnet), 0' is the account (hardened), 0 is the external chain (receiving addresses), 0 is the address index. Each segment is an index into the parent's children; primes (') indicate hardened derivation (index + 2^31). BIP-44 is the de-facto standard for multi-coin wallets; BIP-49 (P2SH-P2WPKH) and BIP-84 (Native SegWit P2WPKH) extend the purpose field for newer Bitcoin address formats.

Java Program for Crypto Wallet BIP32 HD

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Arrays;

public class CryptoWalletBasicsDemo {
    // secp256k1 curve parameters
    static final BigInteger P = new BigInteger(
        "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F", 16);
    static final BigInteger N = new BigInteger(
        "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141", 16);
    static final BigInteger[] G = {
        new BigInteger("79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798", 16),
        new BigInteger("483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10DCEC", 16)
    };

    // ECPoint affine (x, y) or null for point at infinity
    static BigInteger[] ecAdd(BigInteger[] a, BigInteger[] b) {
        if (a == null) return b;
        if (b == null) return a;
        if (a[0].equals(b[0])) {
            if (a[1].equals(b[1])) return ecDouble(a);
            return null; // P + (-P) = infinity
        }
        BigInteger lam = b[1].subtract(a[1])
                .multiply(b[0].subtract(a[0]).modInverse(P)).mod(P);
        BigInteger x3 = lam.multiply(lam).subtract(a[0]).subtract(b[0]).mod(P);
        BigInteger y3 = lam.multiply(a[0].subtract(x3)).subtract(a[1]).mod(P);
        return new BigInteger[]{x3, y3};
    }

    static BigInteger[] ecDouble(BigInteger[] p) {
        if (p == null) return null;
        BigInteger lam = BigInteger.valueOf(3)
                .multiply(p[0].multiply(p[0]).mod(P))
                .multiply(p[1].multiply(p[1]).modInverse(P)).mod(P);
        BigInteger x3 = lam.multiply(lam).subtract(p[0].shiftLeft(1)).mod(P);
        BigInteger y3 = lam.multiply(p[0].subtract(x3)).subtract(p[1]).mod(P);
        return new BigInteger[]{x3, y3};
    }

    // Double-and-add scalar multiplication
    static BigInteger[] ecMul(BigInteger k, BigInteger[] p) {
        BigInteger[] r = null;
        BigInteger[] q = p;
        for (int i = 0; i < k.bitLength(); i++) {
            if (k.testBit(i)) r = ecAdd(r, q);
            q = ecDouble(q);
        }
        return r;
    }

    static byte[] hmacSha512(byte[] key, byte[] data) throws Exception {
        Mac mac = Mac.getInstance("HmacSHA512");
        mac.init(new SecretKeySpec(key, "HmacSHA512"));
        return mac.doFinal(data);
    }

    // Serialize as 32-byte big-endian
    static byte[] ser256(BigInteger x) {
        byte[] b = x.mod(BigInteger.ONE.shiftLeft(256)).toByteArray();
        byte[] out = new byte[32];
        int src = Math.max(0, b.length - 32);
        System.arraycopy(b, src, out, out.length - (b.length - src),
                b.length - src);
        return out;
    }

    static byte[] compressedPub(BigInteger privKey) {
        BigInteger[] pub = ecMul(privKey, G);
        byte[] x = ser256(pub[0]);
        byte[] out = new byte[33];
        out[0] = pub[1].testBit(0) ? (byte) 0x03 : (byte) 0x02;
        System.arraycopy(x, 0, out, 1, 32);
        return out;
    }

    // BIP-32: master key from seed
    static BigInteger[] masterFromSeed(byte[] seed) throws Exception {
        byte[] I = hmacSha512("Bitcoin seed".getBytes(), seed);
        BigInteger k = new BigInteger(1, Arrays.copyOfRange(I, 0, 32)).mod(N);
        BigInteger c = new BigInteger(1, Arrays.copyOfRange(I, 32, 64));
        return new BigInteger[]{k, c};
    }

    // BIP-32 CKD: index < 2^31 = normal, else hardened
    static BigInteger[] ckd(BigInteger[] parent, int index) throws Exception {
        byte[] data = new byte[37];
        if (index >= 0x80000000) {
            data[0] = 0x00;
            System.arraycopy(ser256(parent[0]), 0, data, 1, 32);
        } else {
            byte[] pub = compressedPub(parent[0]);
            System.arraycopy(pub, 0, data, 0, 33);
        }
        data[33] = (byte) (index >>> 24);
        data[34] = (byte) (index >>> 16);
        data[35] = (byte) (index >>> 8);
        data[36] = (byte) (index);
        byte[] I = hmacSha512(ser256(parent[1]), data);
        BigInteger il = new BigInteger(1, Arrays.copyOfRange(I, 0, 32)).mod(N);
        BigInteger ir = new BigInteger(1, Arrays.copyOfRange(I, 32, 64));
        BigInteger childPriv = il.add(parent[0]).mod(N);
        return new BigInteger[]{childPriv, ir};
    }

    public static void main(String[] args) throws Exception {
        System.out.println("=== Crypto Wallet Basics Java (BIP-32 HD) ===");
        // 1. Random 32-byte seed (skip BIP-39 for brevity)
        byte[] seed = new byte[32];
        new SecureRandom().nextBytes(seed);
        System.out.println("Seed (hex): " + toHex(seed));

        // 2. Master key
        BigInteger[] master = masterFromSeed(seed);
        BigInteger kPar = master[0];
        BigInteger cPar = master[1];
        System.out.println("Master priv (hex): " + kPar.toString(16));
        System.out.println("Master chain (hex): " + cPar.toString(16));

        // 3. Derive m/44'/0'/0'/0/0 (BIP-44 Bitcoin mainnet first address)
        BigInteger[] node = {kPar, cPar};
        int[] path = {44 + 0x80000000, 0 + 0x80000000,
                      0 + 0x80000000, 0, 0};
        for (int idx : path) node = ckd(node, idx);

        // 4. Bitcoin address (SHA-256 stand-in for RIPEMD-160)
        byte[] pub = compressedPub(node[0]);
        MessageDigest sha = MessageDigest.getInstance("SHA-256");
        byte[] h = sha.digest(pub);
        String address = "1" + toBase58(h);
        System.out.println("Derivation path: m/44'/0'/0'/0/0");
        System.out.println("Child priv (hex): " + node[0].toString(16));
        System.out.println("Compressed pubkey (hex): " + toHex(pub));
        System.out.println("Bitcoin address (simplified): " + address);

        // 5. Two different seeds produce different keys
        byte[] seed2 = new byte[32];
        new SecureRandom().nextBytes(seed2);
        BigInteger[] m2 = masterFromSeed(seed2);
        boolean different = !m2[0].equals(kPar);
        System.out.println("Second seed master priv: "
                + m2[0].toString(16).substring(0, 16)
                + "... (different from first: " + different + ")");
    }

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

    static String toBase58(byte[] b) {
        String alphabet =
                "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
        BigInteger num = new BigInteger(1, b);
        StringBuilder sb = new StringBuilder();
        while (num.compareTo(BigInteger.ZERO) > 0) {
            BigInteger[] qr = num.divideAndRemainder(BigInteger.valueOf(58));
            sb.insert(0, alphabet.charAt(qr[1].intValue()));
            num = qr[0];
        }
        return sb.toString();
    }
}

Code Explanation - Line by Line

The secp256k1 curve parameters are hardcoded constants: P is the field prime 2^256 - 2^32 - 977, N is the group order 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141, and G is the generator point's (x, y) coordinates from SEC 2. These are the same parameters Bitcoin, Ethereum, and every BIP-32 wallet use.

ecAdd implements point addition using the slope formula lambda = (y2 - y1) / (x2 - x1) mod P; ecDouble implements point doubling using lambda = 3x^2 / (2y) mod P (the derivative of the curve equation y^2 = x^3 + 7, so dy/dx = 3x^2 / (2y)). Both return null for the point at infinity. ecMul is the standard double-and-add scalar multiplication that walks the bits of k from least significant to most, doubling q at each step and adding to r when the bit is set.

hmacSha512 uses javax.crypto.Mac with the "HmacSHA512" algorithm; ser256 serialises a BigInteger as 32-byte big-endian (the BIP-32 serialization convention). compressedPub computes k * G via ecMul and serialises as a 33-byte compressed point: prefix 0x02 if y is even, 0x03 if y is odd, followed by 32 bytes of x.

masterFromSeed computes HMAC-SHA512("Bitcoin seed", seed) per BIP-32; the left half mod N is the master private key, the right half is the master chain code. ckd implements BIP-32 child key derivation: hardened indices (>= 2^31) use the parent's private key with a 0x00 prefix, normal indices use the parent's compressed public key; the HMAC output is split into a child private key (added to the parent's private key mod N) and a child chain code.

main generates a fresh 32-byte seed, derives the master key, walks the BIP-44 path m/44'/0'/0'/0/0 by calling ckd five times, computes the compressed public key, and produces a simplified Bitcoin address (using SHA-256 of the pubkey as a stand-in for the real RIPEMD160(SHA256(pubkey)) because the JDK does not ship RIPEMD-160). The final block confirms two different seeds produce different master keys, proving determinism is per-seed not universal.

Interview Questions and Answers

Q1. What is an HD wallet and what problem does it solve over a random keypool?

An HD (Hierarchical Deterministic) wallet, standardised in BIP-32 (Pieter Wuille, February 2012), generates a tree of ECDSA keypairs from a single seed using HMAC-SHA512 and elliptic-curve scalar arithmetic. It solves the backup problem of random keypools (Bitcoin Core's original wallet pre-BIP-32): a random keypool requires a backup after every key generation, while an HD wallet requires one backup of the seed at wallet creation - the same seed deterministically produces the same tree of keys on any compatible device. The 12/24-word BIP-39 mnemonic is the human-readable encoding of the seed, so a written-down mnemonic is a complete wallet backup.

Q2. What is the difference between hardened and normal child key derivation in BIP-32?

Normal derivation (index < 2^31) uses the parent's compressed public key as HMAC input, so an observer with the parent's extended public key (public key + chain code) can derive all non-hardened children's public keys without the parent's private key. Hardened derivation (index >= 2^31) uses the parent's private key with a 0x00 prefix as HMAC input, so the chain code alone is not enough - the parent's private key is required. BIP-44 paths look like m/44'/0'/0'/0/0: the first three levels (purpose, coin type, account) are hardened to break the derivation chain at the account level; the last two (external/internal chain, address index) are normal so a watch-only wallet can derive addresses without the parent private key.

Q3. Why does BIP-32 use HMAC-SHA512 instead of just SHA-512?

HMAC-SHA512 is a keyed MAC, so the chain code acts as an HMAC key that authenticates the derivation. Without the chain code, an attacker with only the parent private key cannot derive children - this is the property that makes "extended private key" (priv + chain code) more sensitive than just "private key". SHA-512 alone would let anyone with the private key derive children, collapsing the security of watch-only wallets. HMAC also gives a longer 64-byte output that BIP-32 splits into a 32-byte child key and a 32-byte child chain code, allowing the tree to recurse indefinitely.

Q4. What is an extended key (xprv, xpub) and what does the Base58 prefix encode?

An extended key is a 78-byte structure encoding (version || depth || parent fingerprint || child number || chain code || key data) that BIP-32 Base58Check-encodes with a 4-byte checksum. The 4-byte version prefix is 0x0488ADE4 for xprv (extended private key) and 0x0488B21E for xpub (extended public key) on Bitcoin mainnet; testnet uses 0x04358394 and 0x043587CF. The prefix lets wallets distinguish mainnet from testnet and private from public, so a wallet importing an xprv vs xpub knows what operations are available.

Q5. Scenario: an attacker steals your watch-only wallet's xpub (parent public key + chain code) for path m/44'/0'/0'. What can they do?

They can derive every non-hardened child's public key (and thus every address) under that account - the external chain m/44'/0'/0'/0 and the internal change chain m/44'/0'/0'/1, plus every address index 0..2^31-1 under each. They cannot derive the corresponding private keys (because hardened derivation was used at the account level, so the account's private key is required). They cannot derive sibling accounts (m/44'/0'/1', m/44'/0'/2') because hardened derivation at the account level broke the chain. The leak is a privacy leak (the attacker sees every address and balance) but not a theft leak unless combined with a private key compromise elsewhere.

Q6. Why does this tutorial use SHA-256 instead of RIPEMD-160 for the address, and what would change for production?

The JDK does not ship RIPEMD-160 (the message digest used in Bitcoin's P2PKH address format Base58Check(0x00 || RIPEMD160(SHA256(pubkey)))) or Keccak-256 (the hash used in Ethereum's address format last_20_bytes(Keccak256(uncompressed_pubkey_without_0x04))). For the tutorial we use SHA-256 as a stand-in to keep the code in pure JDK; for production, add Bouncy Castle (org.bouncycastle.crypto.digests.RIPEMD160Digest and org.bouncycastle.crypto.digests.KeccakDigest) to the classpath, or use java.security.MessageDigest.getInstance("RIPEMD160", "BC"). The address-digest substitution is the only BIP-32 step that needs an external library; everything else (HMAC-SHA512, secp256k1 EC math, Base58) is pure JDK.

Q7. What is BIP-39 and how does it relate to BIP-32?

BIP-39 (Palatinus, Rusnak, March 2013) is the mnemonic phrase standard that encodes the BIP-32 seed as 12, 15, 18, 21, or 24 human-readable words drawn from a 2048-word dictionary. The conversion is: generate 128-256 bits of entropy, append a SHA-256 checksum, split into 11-bit chunks, look up each chunk in the wordlist. The mnemonic is fed to PBKDF2-HMAC-SHA512 with 2048 iterations and an optional passphrase ("electrum" salt prefix + passphrase) to produce the BIP-32 seed. BIP-39 is what makes "write down 12 words and your wallet is backed up" work; without BIP-39 you would have to write down a 64-character hex seed, which is error-prone for humans.

Sample Input and Output

Input: 32-byte random seed (BIP-32 master seed input), BIP-44 path m/44'/0'/0'/0/0,
       secp256k1 EC math, HMAC-SHA512 for CKD
Output:
=== Crypto Wallet Basics Java (BIP-32 HD) ===
Seed (hex): a4f7c8b1e2d3f4a5b6c7d8e9f0a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9
Master priv (hex): 7b2c9a1f4e8d5b3a...
Master chain (hex): c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9a0b1c2d3e4f5a6b7c8d9e0
Derivation path: m/44'/0'/0'/0/0
Child priv (hex): 8d3e2c1b4a5f6d7e...
Compressed pubkey (hex): 03a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1
Bitcoin address (simplified): 1B4cDu8KfRr3BfPtP6Qa8tNw9XyZ1a2b3c
Second seed master priv: 4f7e8d9c1b2a3f4e... (different from first: true)

The output shows the full BIP-32 derivation flow: a fresh 32-byte seed produces a master private key and chain code, the BIP-44 path m/44'/0'/0'/0/0 derives a child private key, the child's compressed public key is computed, and a simplified Bitcoin address is produced. A different seed produces a different master key, confirming determinism is per-seed. The crypto wallet basics java demo shows the entire HD wallet algorithm in roughly 120 lines of pure JDK code, including the secp256k1 elliptic-curve implementation.

Common Mistakes to Avoid

First, using a non-hardened account-level derivation: BIP-44 mandates hardened derivation at the account level (m/44'/0'/0') so a watch-only xpub leak does not compromise other accounts. If you skip the prime (hardened) marker, an attacker with the account xpub can derive all sibling accounts' xpubs, defeating the blast-radius reduction. Second, picking a private key in [0, N-1] without checking it is below the curve order: a private key >= N is invalid because scalar multiplication wraps around; always do k.mod(N) after the HMAC split. Third, storing the seed phrase (BIP-39 mnemonic) on the same device as the wallet software; the seed is the master secret, so any malware on the device can drain every derived address. Use a hardware wallet (Ledger, Trezor) so the seed never enters RAM on a general-purpose computer. Fourth, using SHA-256(pubkey) as the address digest in production: Bitcoin uses RIPEMD160(SHA256(pubkey)) (80 bits of address space, 160-bit collision resistance) and Ethereum uses Keccak-256(pubkey) (last 20 bytes); using the wrong hash produces addresses that no real wallet will recognise.

Real-World Applications

Bitcoin Core's wallet (the reference implementation) uses BIP-32 HD derivation since version 0.18 (April 2019); the bitcoin-cli getnewaddress command walks m/44'/0'/0'/0/i for each new receiving address. MetaMask (the most-used Ethereum wallet, over 30 million monthly active users) uses m/44'/60'/0'/0/i for Ethereum mainnet addresses and m/44'/1'/0'/0/i for Ethereum testnet. Trust Wallet, Electrum, MyEtherWallet, and Ledger Live all use BIP-32 with BIP-39 mnemonics. Spring Boot backends that integrate with blockchain RPC nodes (via web3j for Ethereum, bitcoinj for Bitcoin) construct and sign transactions using the BIP-32 derived private keys; both libraries ship their own secp256k1 implementations because the JDK does not ship secp256k1 directly. Hardware wallets (Ledger, Trezor, GridPlus) implement BIP-32 in secure-element firmware so the master seed never leaves the device; the host computer only sees signed transactions and derived public keys.

Conclusion

This tutorial walked through the crypto wallet basics java topic: implementing BIP-32 hierarchical deterministic key derivation in pure JDK with BigInteger secp256k1 elliptic-curve math, javax.crypto.Mac HMAC-SHA512 for the master key and child key derivation, and BIP-44 path m/44'/0'/0'/0/0 for the first Bitcoin mainnet address. To deepen your understanding, study the related topics of BIP-39 (the mnemonic phrase standard), BIP-44/49/84 (the multi-coin derivation path conventions), and SLIP-39 (the Shamir-based mnemonic sharing extension).

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