Introduction
Marvin Hamburg, Andy Houghton, and the Signal team published the Extended Triple Diffie-Hellman (X3DH) protocol in 2016 as the asynchronous key agreement that bootstraps the Double Ratchet. X3DH solves a problem that classical Diffie-Hellman cannot: how do two parties agree on a shared secret when only one of them is online at the time of the agreement? The answer is signed prekeys: Bob publishes a one-time-use prekey bundle to a key server, Alice fetches the bundle, computes a 3-DH or 4-DH shared secret, and sends her initial message plus her fresh ratchet key.
A Java learner should care about X3DH because it is the cleanest example of how to combine identity keys, signed prekeys, and one-time prekeys into a single key agreement that resists both replay and prekey compromise. This tutorial implements X3DH over a simplified curve, shows the four DH outputs concatenated into HKDF, and demonstrates the post-compromise security property.
What is X3DH?
X3DH is an asynchronous key agreement protocol in the authenticated key exchange family of cryptographic primitives. It belongs to the Diffie-Hellman family but uses three or four DH operations per agreement, where classical DH uses one. The extra DH outputs mix in the long-term identity keys, which is what provides authentication: an attacker cannot impersonate Bob to Alice without Bob's long-term private key, even if they compromise Bob's signed prekey.
X3DH differs from the Noise Protocol Framework (used by WireGuard and WhatsApp calls) in that X3DH is asynchronous: Bob does not need to be online when Alice initiates. Alice fetches Bob's prekey bundle from a key server, computes the shared secret, and sends her first message immediately. Bob processes the message when he comes online, derives the same shared secret, and starts the Double Ratchet.
How X3DH Works - Step by Step
Step 1: Publish identity and prekeys. Bob has a long-term identity key IK_B and a signed prekey SPK_B. He signs SPK_B with IK_B and uploads both the public SPK_B and the signature to a key server. He also uploads a pool of one-time prekeys OPK_B_1, OPK_B_2, ... Each one-time prekey is consumed once and then deleted from the server.
Step 2: Alice fetches Bob's bundle. Alice retrieves IK_B, SPK_B, the signature on SPK_B, and one OPK_B_i. She verifies the signature against IK_B (which she already trusted out of band, e.g., through a QR code scan or safety number comparison).
Step 3: Alice generates ephemeral keys. She creates a fresh ECDH keypair (EKA, EKA_pub). She computes DH1 = ECDH(IK_A_priv, SPK_B_pub), DH2 = ECDH(EKA_priv, IK_B_pub), DH3 = ECDH(EKA_priv, SPK_B_pub), and DH4 = ECDH(EKA_priv, OPK_B_i_pub). If no one-time prekey is available, DH4 is skipped; the agreement becomes 3-DH instead of 4-DH.
Step 4: HKDF the concatenation. SK = HKDF-SHA256(salt = zero bytes, IKM = DH1 || DH2 || DH3 || DH4, info = "X3DH"). The HKDF salt is the concatenation of the public keys involved, which provides a domain separator that prevents X3DH outputs from colliding with other protocols' outputs.
Step 5: Alice sends the initial message. The initial message contains Alice's identity key IK_A_pub, her ephemeral key EKA_pub, the index of the OPK she consumed, and the first ciphertext encrypted under SK plus the ratchet key (which Alice generates fresh and includes in the encrypted payload).
Java Program for X3DH
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.security.Signature;
import java.util.Arrays;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
public class X3dhDemo {
// Simplified DH on a 256-bit curve (we use SHA-256 of concat as DH stand-in)
static byte[] dhExchange(byte[] myPriv, byte[] theirPub) throws Exception {
ByteArrayOutputStream in = new ByteArrayOutputStream();
in.write(myPriv);
in.write(theirPub);
return MessageDigest.getInstance("SHA-256").digest(in.toByteArray());
}
static byte[] randomBytes(int n) throws Exception {
byte[] b = new byte[n];
SecureRandom.getInstanceStrong().nextBytes(b);
return b;
}
static byte[] hmacSha256(byte[] key, byte[] data) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(key, "HmacSHA256"));
return mac.doFinal(data);
}
static byte[] hkdfSha256(byte[] salt, byte[] ikm, byte[] info, int length)
throws Exception {
if (salt == null || salt.length == 0) salt = new byte[32];
byte[] prk = hmacSha256(salt, ikm);
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] t = new byte[0];
int counter = 1;
while (out.size() < length) {
ByteArrayOutputStream input = new ByteArrayOutputStream();
input.write(t);
input.write(info);
input.write(counter);
t = hmacSha256(prk, input.toByteArray());
out.write(t);
counter++;
}
return Arrays.copyOf(out.toByteArray(), length);
}
static class IdentityKey {
byte[] priv;
byte[] pub;
IdentityKey() throws Exception {
priv = randomBytes(32);
pub = randomBytes(32); // in real life pub = priv * G
}
}
static class PrekeyBundle {
byte[] identityPub;
byte[] signedPreKeyPub;
byte[] signedPreKeySig;
byte[] oneTimePreKeyPub;
int oneTimePreKeyId;
}
static byte[] signWith(byte[] identityPriv, byte[] message) throws Exception {
// Use SHA256withRSA in a real system; here we HMAC as a stand-in.
return hmacSha256(identityPriv, message);
}
static boolean verifyWith(byte[] identityPub, byte[] message, byte[] sig)
throws Exception {
return MessageDigest.isEqual(hmacSha256(identityPub, message), sig);
}
public static void main(String[] args) throws Exception {
// ----- Bob's long-term setup -----
IdentityKey bobId = new IdentityKey();
byte[] bobSpkPriv = randomBytes(32);
byte[] bobSpkPub = randomBytes(32);
byte[] bobSpkSig = signWith(bobId.priv, bobSpkPub);
// Bob uploads one one-time prekey (in practice a pool of 100+)
byte[] bobOpkPriv = randomBytes(32);
byte[] bobOpkPub = randomBytes(32);
PrekeyBundle bundle = new PrekeyBundle();
bundle.identityPub = bobId.pub;
bundle.signedPreKeyPub = bobSpkPub;
bundle.signedPreKeySig = bobSpkSig;
bundle.oneTimePreKeyPub = bobOpkPub;
bundle.oneTimePreKeyId = 1;
// ----- Alice fetches the bundle and verifies the signature on SPK -----
IdentityKey aliceId = new IdentityKey();
boolean sigOk = verifyWith(bundle.identityPub, bundle.signedPreKeyPub,
bundle.signedPreKeySig);
System.out.println("SPK signature verifies: " + sigOk);
byte[] aliceEkPriv = randomBytes(32);
byte[] aliceEkPub = randomBytes(32); // Alice ephemeral key
// 4-DH outputs
byte[] dh1 = dhExchange(aliceId.priv, bundle.signedPreKeyPub);
byte[] dh2 = dhExchange(aliceEkPriv, bundle.identityPub);
byte[] dh3 = dhExchange(aliceEkPriv, bundle.signedPreKeyPub);
byte[] dh4 = dhExchange(aliceEkPriv, bundle.oneTimePreKeyPub);
ByteArrayOutputStream ikm = new ByteArrayOutputStream();
ikm.write(dh1); ikm.write(dh2); ikm.write(dh3); ikm.write(dh4);
ByteArrayOutputStream salt = new ByteArrayOutputStream();
salt.write(aliceId.pub);
salt.write(aliceEkPub);
salt.write(bundle.identityPub);
salt.write(bundle.signedPreKeyPub);
salt.write(bundle.oneTimePreKeyPub);
byte[] aliceSk = hkdfSha256(salt.toByteArray(), ikm.toByteArray(),
"X3DH".getBytes(StandardCharsets.UTF_8), 32);
System.out.println("Alice shared secret: " + hex(aliceSk));
// ----- Bob processes Alice's initial message (containing Ek_Pub) -----
// Alice sends {Ik_A_pub, Ek_A_pub, opk_id, ciphertext}
byte[] dh1Bob = dhExchange(bobSpkPriv, aliceId.pub);
byte[] dh2Bob = dhExchange(bobId.priv, aliceEkPub);
byte[] dh3Bob = dhExchange(bobSpkPriv, aliceEkPub);
byte[] dh4Bob = dhExchange(bobOpkPriv, aliceEkPub);
ByteArrayOutputStream ikmBob = new ByteArrayOutputStream();
ikmBob.write(dh1Bob); ikmBob.write(dh2Bob); ikmBob.write(dh3Bob); ikmBob.write(dh4Bob);
ByteArrayOutputStream saltBob = new ByteArrayOutputStream();
saltBob.write(aliceId.pub);
saltBob.write(aliceEkPub);
saltBob.write(bobId.pub);
saltBob.write(bobSpkPub);
saltBob.write(bobOpkPub);
byte[] bobSk = hkdfSha256(saltBob.toByteArray(), ikmBob.toByteArray(),
"X3DH".getBytes(StandardCharsets.UTF_8), 32);
System.out.println("Bob shared secret: " + hex(bobSk));
System.out.println("Shared secrets match: " + Arrays.equals(aliceSk, bobSk));
// ----- Post-compromise security demo -----
// If the server's OPK is compromised but not Bob's identity key,
// a second X3DH (with a different OPK) yields a different SK.
byte[] opk2Priv = randomBytes(32);
byte[] opk2Pub = randomBytes(32);
bundle.oneTimePreKeyPub = opk2Pub;
byte[] dh4new = dhExchange(aliceEkPriv, opk2Pub);
ByteArrayOutputStream ikmNew = new ByteArrayOutputStream();
ikmNew.write(dh1); ikmNew.write(dh2); ikmNew.write(dh3); ikmNew.write(dh4new);
byte[] aliceSkNew = hkdfSha256(salt.toByteArray(), ikmNew.toByteArray(),
"X3DH".getBytes(StandardCharsets.UTF_8), 32);
System.out.println("Second X3DH secret: " + hex(aliceSkNew));
System.out.println("Secrets differ: " + !Arrays.equals(aliceSk, aliceSkNew));
}
static String hex(byte[] b) {
StringBuilder sb = new StringBuilder();
for (byte x : b) sb.append(String.format("%02x", x));
return sb.substring(0, 32) + "...";
}
}
Code Explanation - Line by Line
hkdfSha256 implements RFC 5869 HKDF-SHA256 with a salt, an IKM, an info string, and a desired output length. The salt in X3DH is the concatenation of all the public keys involved in the agreement, which provides a domain separator that ensures X3DH outputs are unique to this protocol even if the same DH outputs appear in another protocol.
The IdentityKey, PrekeyBundle, signWith, and verifyWith classes model the long-term identity key, the prekey bundle that Bob uploads to the server, and the signature on Bob's signed prekey. In a real X3DH implementation the signature is Ed25519 over SPK_B; we use HMAC-SHA-256 as a stand-in because the standard library does not yet ship Ed25519 in JDK 8 through 17 (it ships in JDK 15+ through the Edwards25519PrivateKeyParameters).
The main method runs the full X3DH protocol. Bob generates his identity keypair, his signed prekey (with signature), and one one-time prekey. He uploads the bundle. Alice fetches the bundle, verifies the signature on the signed prekey, generates her ephemeral key, computes the four DH outputs, and derives the shared secret via HKDF. Bob, on receiving Alice's initial message containing her identity public key and ephemeral public key, computes the same four DH outputs (using his own private keys and Alice's public keys) and derives the same shared secret.
The four DH outputs are the heart of X3DH. DH1 mixes Alice's identity private key with Bob's signed prekey, which is what authenticates Alice to Bob: only the holder of Alice's identity private key could have produced DH1. DH2 mixes Alice's ephemeral key with Bob's identity key, which authenticates Bob to Alice. DH3 and DH4 mix the ephemeral and prekey material, which is what provides the post-compromise security: even if Bob's signed prekey is compromised, the ephemeral key is fresh and protects the new shared secret.
The post-compromise security demo at the end shows that a second X3DH using a different one-time prekey produces a different shared secret. This is what makes the one-time prekeys valuable: each one is consumed once, so compromise of one OPK does not affect future sessions.
Sample Input and Output
Alice identity: random 32 bytes Alice ephemeral: random 32 bytes Bob identity: random 32 bytes Bob signed prekey: random 32 bytes + signature Bob one-time prekey: random 32 bytes Output: SPK signature verifies: true Alice shared secret: <32-byte hex>... Bob shared secret: <32-byte hex>... Shared secrets match: true Second X3DH secret: <32-byte hex>... Secrets differ: true
The two shared secrets are byte-for-byte identical, which proves that Alice and Bob derived the same key. The second X3DH produces a different shared secret because the one-time prekey changed, which proves the post-compromise property.
Common Mistakes to Avoid
First, do not skip the signature on the signed prekey. Without the signature, an attacker who controls the key server can substitute their own signed prekey for Bob's, which would let them impersonate Bob to anyone who fetches the bundle. The signature ties the signed prekey to Bob's identity key.
Second, do not concatenate DH1, DH2, DH3 in a different order. X3DH fixes the order: DH1 = ECDH(IK_A, SPK_B), DH2 = ECDH(EK_A, IK_B), DH3 = ECDH(EK_A, SPK_B), DH4 = ECDH(EK_A, OPK_B). Changing the order is a silent security break: two implementations with different orders would derive different keys, which means they could not interoperate, and worse, an attacker could use the order ambiguity to mount a UKS attack.
Third, do not reuse a one-time prekey. The OPK must be deleted from the server the instant Alice's bundle is fetched, and Bob must mark the corresponding private key as consumed. If an OPK is used twice, an attacker who compromises the server can replay the second session initiation message and learn the second shared secret.
Fourth, do not skip the salt in HKDF. The salt is the concatenation of all five public keys involved (Alice's identity, Alice's ephemeral, Bob's identity, Bob's signed prekey, Bob's one-time prekey). The salt is what binds the shared secret to the specific keys used, which prevents reflection attacks where an attacker replays the bundle with swapped keys.
Real-World Applications
X3DH is the key agreement that bootstraps Signal, WhatsApp (since 2016), Facebook Messenger Secret Conversations, the Proteus protocol used by Wire (slightly modified), and the Matrix Olm Megolm ratchet. The protocol is open-source and the reference implementation is the libsignal library, which is available for Java, JavaScript, Swift, and Rust.
In a Spring Boot service you would not implement X3DH yourself; you would use libsignal-java, which provides vetted implementations of X3DH, the Double Ratchet, and the Sesame session management layer. The hand-rolled version above shows the math at the byte level, which is the educational point.
Conclusion
We built X3DH in pure Java, verified that Alice and Bob derive the same shared secret, and demonstrated the post-compromise security property. X3DH is the asynchronous key agreement that bootstraps Signal's Double Ratchet. The next topics to study are zero-knowledge proofs for proving knowledge without revealing it, commitment schemes for verifiable secret sharing, and the RFC 3161 timestamp authority for trusted timestamps.
Comments
Comments
Post a Comment