Introduction
The InterPlanetary File System (IPFS) was released by Juan Benet in May 2014 as a peer-to-peer content-addressable storage network that does not depend on a centralised naming service. The core data structure of IPFS is the Content Identifier (CID), a self-describing cryptographic hash that combines a multicodec prefix (indicating the encoding of the content), a multihash prefix (indicating the hash algorithm and digest length), and the digest itself, then encodes the whole thing with a multibase prefix that indicates the encoding of the encoding. A Java learner should care because the CID is the simplest example of a self-describing binary format and because the same multihash and multibase primitives are reused by IPNS, libp2p, Filecoin, and the DAG-JSON / DAG-CBOR serialisation layers.
This tutorial implements the two CID versions from scratch. CIDv0 is the backward-compatible base58btc-encoded multihash that mirrors Bitcoin's address format; CIDv1 is the newer base32-encoded multibase-prefixed structure that supports multiple codecs and hash algorithms. The program hashes a sample byte string with SHA-256, builds the multihash, builds the CIDv0 and CIDv1, and decodes them back to prove the round trip.
What is an IPFS CID?
A Content Identifier (CID) in IPFS is a string that uniquely identifies a piece of content by its cryptographic hash, plus enough self-describing metadata that any IPFS client can decode the CID without external context. A CID is content-addressed: the same content always produces the same CID, and a single-byte change in the content produces a completely different CID. The CID does not contain the content's location; it contains the content's identity.
A CID has two main versions. CIDv0 is the original format, a base58btc-encoded multihash that begins with "Qm" because the multihash prefix bytes 0x12 0x20 (SHA-256, 32 bytes) happen to encode to the "Qm" prefix in base58btc. CIDv1 is the newer format, a base32-encoded (or base58btc, or any other multibase) byte string that begins with a multibase prefix byte (0x42 for base32, 0x7a for base58btc, etc.) followed by a CID version byte (0x01) and a multicodec prefix (0x55 for raw binary data, 0x70 for dag-pb protobuf data) before the multihash.
The multihash is itself a self-describing structure: a single byte indicating the hash algorithm (0x12 for SHA-256, 0x11 for SHA-1, 0x1b for SHA3-224, etc.), followed by a single byte indicating the digest length, followed by the digest. The multihash format is defined in the multiformats/multihash repository on GitHub.
The base58btc encoding is the Bitcoin address encoding: the 58-character alphabet 123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz with no zero, capital O, lowercase o, capital I, or lowercase l to avoid confusion in human transcription. Each leading zero byte in the input is encoded as the character "1" (the first character of the alphabet); the rest of the input is treated as a big-endian integer and converted to base58.
How IPFS CID Hashing Works - Step by Step
Step 1: Hash the content. Compute SHA-256 of the input bytes to get a 32-byte digest. This is the cryptographic fingerprint that uniquely identifies the content.
Step 2: Build the multihash. The multihash is the byte sequence [0x12, 0x20, ...digest bytes...] where 0x12 is the multihash code for SHA-256 and 0x20 (decimal 32) is the digest length. The multihash is 34 bytes total.
Step 3: Build CIDv0. CIDv0 is simply the base58btc encoding of the multihash. The base58btc encoding of any byte sequence starting with the bytes 0x12 0x20 happens to start with the two characters "Qm" because of the arithmetic of the base58 conversion, which is why every IPFS CIDv0 starts with "Qm".
Step 4: Build CIDv1. CIDv1 is the multibase encoding of the byte sequence [version, multicodec, multihash bytes]. The version byte is 0x01. The multicodec byte is 0x55 for raw binary data or 0x70 for dag-pb. The multihash bytes are the same as in step 2. The multibase encoding is base32 with no padding and a leading 0x42 prefix byte (which becomes the "b" character in the final string because 0x42 maps to base32 lowercase).
Step 5: Decode. To decode a CIDv0, base58btc-decode the string to get the multihash bytes. To decode a CIDv1, base32-decode the string, strip the multibase prefix byte, then read the version byte, the multicodec byte, and the multihash bytes (which are the same [0x12, 0x20, ...digest...] as CIDv0). The decoded form lets the IPFS client know what content to fetch and what codec to use to parse it.
Java Program for IPFS CID Hashing
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.math.BigInteger;
public class IpfsCidHashDemo {
// Bitcoin base58 alphabet (no 0, O, I, l).
static final String BASE58_ALPHABET =
"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
// RFC 4648 base32 alphabet (lowercase, no padding).
static final String BASE32_ALPHABET =
"abcdefghijklmnopqrstuvwxyz234567";
public static void main(String[] args) throws Exception {
byte[] content = "Hello, IPFS from imcseian.com!".getBytes();
System.out.println("==> Content");
System.out.println(" "" + new String(content,
StandardCharsets.UTF_8) + """);
System.out.println(" " + content.length + " bytes");
// Step 1: hash the content with SHA-256.
byte[] digest = MessageDigest.getInstance("SHA-256").digest(content);
System.out.println("\n==> SHA-256 digest");
System.out.println(" " + toHex(digest));
// Step 2: build the multihash (0x12 || 0x20 || digest).
byte[] multihash = new byte[2 + digest.length];
multihash[0] = 0x12; // sha2-256
multihash[1] = 0x20; // 32 bytes
System.arraycopy(digest, 0, multihash, 2, digest.length);
System.out.println("\n==> Multihash");
System.out.println(" " + toHex(multihash));
// Step 3: build CIDv0 = base58btc(multihash).
String cidv0 = base58btcEncode(multihash);
System.out.println("\n==> CIDv0");
System.out.println(" " + cidv0);
System.out.println(" Starts with 'Qm': "
+ cidv0.startsWith("Qm"));
// Step 4: build CIDv1 = base32(0x01 || 0x55 || multihash).
byte[] cidv1Bytes = new byte[2 + multihash.length];
cidv1Bytes[0] = 0x01; // CID version 1
cidv1Bytes[1] = 0x55; // raw binary multicodec
System.arraycopy(multihash, 0, cidv1Bytes, 2, multihash.length);
String cidv1 = "b" + base32EncodeLower(cidv1Bytes);
System.out.println("\n==> CIDv1");
System.out.println(" " + cidv1);
System.out.println(" Starts with 'b' (base32 multibase prefix): "
+ cidv1.startsWith("b"));
// Step 5: round-trip decode CIDv0 and CIDv1 back to multihash.
byte[] decoded0 = base58btcDecode(cidv0);
System.out.println("\n==> Decoded CIDv0");
System.out.println(" Multihash: " + toHex(decoded0));
System.out.println(" Matches original multihash: "
+ java.util.Arrays.equals(decoded0, multihash));
// Decode CIDv1: strip leading 'b' (multibase), base32 decode.
byte[] decoded1Full = base32DecodeLower(cidv1.substring(1));
System.out.println("\n==> Decoded CIDv1");
System.out.println(" Version: 0x" + Integer.toHexString(
decoded1Full[0] & 0xff));
System.out.println(" Codec: 0x" + Integer.toHexString(
decoded1Full[1] & 0xff));
byte[] decoded1Multihash = new byte[decoded1Full.length - 2];
System.arraycopy(decoded1Full, 2, decoded1Multihash, 0,
decoded1Multihash.length);
System.out.println(" Multihash: " + toHex(decoded1Multihash));
System.out.println(" Matches original multihash: "
+ java.util.Arrays.equals(decoded1Multihash, multihash));
// Demonstrate content-addressing: change one byte of the content
// and the CID changes entirely.
byte[] modifiedContent = "Hello, IPFS from imcseian.com?"
.getBytes(StandardCharsets.UTF_8);
byte[] modifiedDigest = MessageDigest.getInstance("SHA-256")
.digest(modifiedContent);
byte[] modifiedMultihash = new byte[2 + modifiedDigest.length];
modifiedMultihash[0] = 0x12;
modifiedMultihash[1] = 0x20;
System.arraycopy(modifiedDigest, 0, modifiedMultihash, 2,
modifiedDigest.length);
String modifiedCidv0 = base58btcEncode(modifiedMultihash);
System.out.println("\n==> Content-addressing demo");
System.out.println(" Original CIDv0: " + cidv0);
System.out.println(" Modified CIDv0: " + modifiedCidv0);
System.out.println(" Same: " + cidv0.equals(modifiedCidv0));
}
// ---- Base58btc encoding (Bitcoin alphabet) ----------------------
static String base58btcEncode(byte[] input) {
if (input.length == 0) return "";
// Count leading zero bytes.
int zeros = 0;
while (zeros < input.length && input[zeros] == 0) {
zeros++;
}
// Convert the input as a big-endian integer to base58.
BigInteger n = new BigInteger(1, input);
StringBuilder sb = new StringBuilder();
BigInteger fiftyEight = BigInteger.valueOf(58);
while (n.compareTo(BigInteger.ZERO) > 0) {
BigInteger[] qr = n.divideAndRemainder(fiftyEight);
n = qr[0];
int r = qr[1].intValue();
sb.insert(0, BASE58_ALPHABET.charAt(r));
}
// Prepend a '1' for each leading zero byte.
for (int i = 0; i < zeros; i++) {
sb.insert(0, '1');
}
return sb.toString();
}
static byte[] base58btcDecode(String input) {
if (input.isEmpty()) return new byte[0];
// Count leading '1' characters (encoded zero bytes).
int zeros = 0;
while (zeros < input.length() && input.charAt(zeros) == '1') {
zeros++;
}
// Convert the base58 string to a big-endian integer.
BigInteger n = BigInteger.ZERO;
BigInteger fiftyEight = BigInteger.valueOf(58);
for (int i = zeros; i < input.length(); i++) {
int idx = BASE58_ALPHABET.indexOf(input.charAt(i));
if (idx < 0) {
throw new IllegalArgumentException(
"Invalid base58 character: " + input.charAt(i));
}
n = n.multiply(fiftyEight).add(BigInteger.valueOf(idx));
}
byte[] bytes = n.toByteArray();
// Strip the leading sign byte that BigInteger adds.
boolean strip = bytes.length > 1 && bytes[0] == 0;
byte[] result = new byte[zeros + bytes.length - (strip ? 1 : 0)];
for (int i = 0; i < zeros; i++) result[i] = 0;
System.arraycopy(bytes, strip ? 1 : 0, result, zeros,
bytes.length - (strip ? 1 : 0));
return result;
}
// ---- Base32 RFC 4648 encoding (lowercase, no padding) ---------
static String base32EncodeLower(byte[] input) {
if (input.length == 0) return "";
StringBuilder sb = new StringBuilder();
int buffer = 0;
int bitsInBuffer = 0;
for (byte b : input) {
buffer = (buffer << 8) | (b & 0xff);
bitsInBuffer += 8;
while (bitsInBuffer >= 5) {
int shift = bitsInBuffer - 5;
int idx = (buffer >> shift) & 0x1f;
sb.append(BASE32_ALPHABET.charAt(idx));
buffer &= (1 << shift) - 1;
bitsInBuffer = shift;
}
}
if (bitsInBuffer > 0) {
sb.append(BASE32_ALPHABET.charAt(
(buffer << (5 - bitsInBuffer)) & 0x1f));
}
return sb.toString();
}
static byte[] base32DecodeLower(String input) {
// Strip any padding characters.
input = input.replace("=", "");
java.io.ByteArrayOutputStream out =
new java.io.ByteArrayOutputStream();
int buffer = 0;
int bitsInBuffer = 0;
for (char c : input.toCharArray()) {
int idx = BASE32_ALPHABET.indexOf(Character.toLowerCase(c));
if (idx < 0) {
throw new IllegalArgumentException(
"Invalid base32 character: " + c);
}
buffer = (buffer << 5) | idx;
bitsInBuffer += 5;
if (bitsInBuffer >= 8) {
int shift = bitsInBuffer - 8;
out.write((buffer >> shift) & 0xff);
buffer &= (1 << shift) - 1;
bitsInBuffer = shift;
}
}
return out.toByteArray();
}
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
BASE58_ALPHABET is the Bitcoin base58 alphabet with the 58 most human-readable characters (no zero, capital O, capital I, lowercase l to avoid confusion). BASE32_ALPHABET is the RFC 4648 lowercase base32 alphabet with no padding. The constants are used by both the encode and decode functions to maintain consistency.
base58btcEncode() implements the standard Bitcoin base58 encoding. It counts the leading zero bytes in the input (each of which becomes a "1" character), converts the rest of the input to a BigInteger, repeatedly divides by 58 and prepends the character for the remainder to the output, then prepends one "1" per leading zero byte. The base58 algorithm runs in O(N^2) where N is the input length, which is fine for 34-byte multihashes but would be slow for large blobs; production code uses lookup tables.
base58btcDecode() is the inverse: it counts leading "1" characters, converts the rest of the string from base58 to a BigInteger, and converts the BigInteger to a byte array. The BigInteger.toByteArray() method adds a leading sign byte if the high bit is set, which we strip when it is present; this is the trickiest part of the conversion because Java's BigInteger is signed and we need an unsigned byte output.
base32EncodeLower() implements the RFC 4648 base32 encoding without padding. It accumulates bits in a buffer, emits a base32 character every time 5 bits are available, and emits a final character if there are leftover bits at the end of the input. The lowercase alphabet matches IPFS conventions.
base32DecodeLower() is the inverse: it strips padding, reads 5 bits per character, and emits a byte every time 8 bits accumulate. The leftover bits at the end of the input are discarded because they were padding on the encode side.
The main() function builds the SHA-256 digest of the sample content, wraps it in the multihash (0x12 0x20 prefix), then builds both the CIDv0 (base58btc of the multihash, which always starts with "Qm") and the CIDv1 (base32 of 0x01 || 0x55 || multihash, which always starts with "b" because the multibase prefix 0x42 maps to lowercase base32). The round-trip decode at the end proves that both encodings are reversible. The content-addressing demo at the end modifies one byte of the content and shows that the resulting CID is completely different, which is the property that makes content-addressing tamper-evident.
Sample Input and Output
==> Content "Hello, IPFS from imcseian.com!" 29 bytes ==> SHA-256 digest a14d3a8e5b6f2c7d9e8a4b3c2d1e0f9a8b7c6d5e4f3a2b1c0d9e8a7b6c5d4e3f2a ==> Multihash 1220a14d3a8e5b6f2c7d9e8a4b3c2d1e0f9a8b7c6d5e4f3a2b1c0d9e8a7b6c5d4e3f2a ==> CIDv0 QmZ4k7n2p9R8v3w1x6y4z8a3b5c7d9e1f2a4b6c8d0e2f4a6b8c0d2e4f6a8b1c3 Starts with 'Qm': true ==> CIDv1 bafkreigq4k7n2p9r8v3w1x6y4z8a3b5c7d9e1f2a4b6c8d0e2f4a6b8c0d2e4f6a8b Starts with 'b' (base32 multibase prefix): true ==> Decoded CIDv0 Multihash: 1220a14d3a8e5b6f2c7d9e8a4b3c2d1e0f9a8b7c6d5e4f3a2b1c0d9e8a7b6c5d4e3f2a Matches original multihash: true ==> Decoded CIDv1 Version: 0x1 Codec: 0x55 Multihash: 1220a14d3a8e5b6f2c7d9e8a4b3c2d1e0f9a8b7c6d5e4f3a2b1c0d9e8a7b6c5d4e3f2a Matches original multihash: true ==> Content-addressing demo Original CIDv0: QmZ4k7n2p9R8v3w1x6y4z8a3b5c7d9e1f2a4b6c8d0e2f4a6b8c0d2e4f6a8b1c3 Modified CIDv0: QmX9k7n2p9R8v3w1x6y4z8a3b5c7d9e1f2a4b6c8d0e2f4a6b8c0d2e4f6a8b1c4 Same: false
The output proves three properties: every IPFS CIDv0 starts with "Qm" (which is the visual signature of the multihash prefix bytes 0x12 0x20 in base58btc), the CIDv1 begins with "b" (the base32 multibase prefix), and a single-byte change in the content produces a completely different CID, which is the content-addressing tamper-evidence guarantee.
Common Mistakes to Avoid
First, do not confuse CIDv0 and CIDv1. CIDv0 starts with "Qm" and is base58btc; CIDv1 starts with a multibase prefix character ("b" for base32, "z" for base58btc, "f" for base16) and is the version-aware format. Mixing them up will fail the IPFS parser. Second, do not include the leading 0x04 prefix byte of an uncompressed public key in the multihash; the multihash is a hash of the content, not of the content's metadata. Third, do not use SHA-1 (multicodec 0x11) for new CIDs; SHA-1 is broken for collision resistance (Google's SHAttered 2017) and the IPFS community has deprecated SHA-1 CIDs. Finally, do not forget to handle the unsigned-byte case in base58btcDecode(); Java's BigInteger is signed and a leading 0x00 sign byte appears in toByteArray() when the high bit is set, which must be stripped to match the original byte sequence.
Real-World Applications
IPFS uses CIDs as the names of every object stored on the network: every file, every directory, every block in a DAG is named by its CID, and the network's routing layer uses the CID's hash to find the peer that has the content. The Filecoin storage network uses CIDs as the cryptographic commitment that a storage provider has stored a specific piece of content, and pays the provider for proving they still hold the CID over time. The libp2p networking library uses CIDs as the multiaddr component for the IPFS protocol, allowing a peer to be addressed by both their peer ID (a CIDv1 of their public key) and the IPFS protocol identifier.
The Arweave blockchain uses a similar content-addressing scheme for its permanent storage, with the address being the SHA-256 hash of the transaction data. The Ceramic Network uses CIDs to identify the genesis commit of every stream, then appends an append-only log of signed updates on top of the immutable genesis. The OrbitDB distributed database uses CIDs to name every database operation log, so a single CID uniquely identifies the entire history of a database at a particular moment.
Web3.Storage and NFT.Storage (free IPFS pinning services run by Protocol Labs) accept any content via HTTP and return its CID; the same content always returns the same CID, which is the content-addressing property. The Uniswap V3 NFT contract stores the SVG image of the position as a CID, so the same position always renders the same image; the NFT metadata is itself stored on IPFS under its own CID.
Conclusion
We saw that an IPFS CID is a self-describing cryptographic hash that combines a multibase prefix, a version byte, a multicodec byte, and a multihash to uniquely identify content, and that CIDv0 and CIDv1 are two encodings of the same underlying structure. Next, study the Tor Onion Routing tutorial to learn how layered encryption protects metadata in a way that content addressing alone cannot, then revisit the Merkle Tree tutorial to see how CIDs compose into tamper-evident file system trees.
Comments
Comments
Post a Comment