Design an E2EE Messenger (Signal / WhatsApp)
Combine X3DH pre-key bundles, Double Ratchet forward secrecy, encrypted media envelopes, and sealed sender over an untrusted relay.
In this lesson (4 bite-sized sections)
Untrusted relay and asynchronous X3DH setup
In an end-to-end encrypted messenger (Signal, WhatsApp), the messaging server is treated as an untrusted relay: it routes packets and stores offline queues (WhatsApp ran a customized binary XMPP transport, while modern relays use WebSockets or persistent TLS sockets), yet even a root compromise of the server must reveal zero plaintext.
The hard systems twist is asynchronous key agreement: Alice wants to send Bob a secret message while Bob's phone is powered off. X3DH (Extended Triple Diffie-Hellman) solves this with a pre-key bundle server. Whenever Bob registers or comes online, his phone publishes three public keys: a long-term Identity Key (IK_B), a periodically rotated Signed Pre-Key (SPK_B), and a batch of single-use One-Time Pre-Keys (OPK_B). To start a chat, Alice fetches Bob's bundle, runs four local Diffie-Hellman exchanges combining her identity and ephemeral keys with Bob's keys, derives the initial root key, and sends her encrypted first message right away. The server pops and deletes that OPK_B atomically so no second conversation reuses it.
Double Ratchet: forward secrecy and self-healing
Encrypting every message under one static shared key means a single stolen phone exposes years of history and every future chat. The Double Ratchet protocol chains two ratchets together so keys constantly evolve and old keys are erased immediately after use:

- Symmetric KDF ratchet (forward secrecy): each outgoing message hashes the current chain key through an HKDF step to produce a fresh one-time Message Key (
MK) and the next chain key, then deletes the old chain key. Even if an attacker steals device memory tomorrow, past messages remain undecryptable. - Diffie-Hellman ratchet (post-compromise security): every time the conversation changes turns, the sender attaches a fresh ephemeral DH public key in the header. Mixing the new DH shared secret into the root key heals the session after one unobserved round-trip, locking out an attacker who captured an earlier state snapshot.
To survive out-of-order mobile delivery, message headers carry a counter N so the receiver can derive and briefly cache skipped message keys (bounded by a strict max-skip cap to prevent CPU/memory DoS).
Encrypted media blobs and metadata protection
Sending 50 MB videos through the chat queue saturates relay memory. Media instead uses envelope encryption: the sender generates a random 256-bit key, encrypts the file locally with AEAD (or AES-CBC + HMAC), uploads the opaque ciphertext blob to S3/CDN, and sends {blob_url, media_key, ciphertext_sha256} inside the Double Ratchet text message.
Even when content is hidden, metadata (who messaged whom and when) leaks the social graph. Sealed Sender places a server-signed sender certificate inside the encrypted envelope and presents a short-lived delivery token for Bob's mailbox, so the relay checks delivery permission and routes the ciphertext without knowing Alice sent it.
| Server Visibility | TLS-Only Chat | E2EE (X3DH + Ratchet) | E2EE + Sealed Sender |
|---|---|---|---|
| Message text | Readable by server | Opaque ciphertext | Opaque ciphertext |
| Media attachments | Readable by server | Opaque encrypted blob | Opaque encrypted blob |
| Sender identity | Visible on every send | Visible in routing header | Encrypted inside envelope |
| Recipient + timing | Visible | Visible | Visible (needed for delivery) |
Multi-device fan-out and key verification
Linked desktops and tablets hold their own identity key pairs. Under client-side fan-out (Signal's Sesame), Alice maintains an independent Double Ratchet session with each of Bob's devices and her own linked devices, encrypting one small envelope per device. For large groups, pairwise fan-out becomes expensive, so messengers use Sender Keys (encrypt once under a sender's symmetric group chain key, distribute that key pairwise, and rotate whenever a member leaves) or MLS (TreeKEM) for O(log N) group key updates.
Finally, because an untrusted key server could try substituting Bob's identity key to mount a man-in-the-middle attack, clients let users verify Safety Numbers (a fingerprint of both identity keys scanned via QR code out-of-band) and back key directories with auditable Key Transparency logs.
Sources: Signal X3DH specification · Signal Double Ratchet specification · Signal Sealed Sender blog · WhatsApp Security Whitepaper
import hashlib
import hmac
def step_chain(chain_key: bytes) -> tuple[bytes, bytes]:
message_key = hmac.new(chain_key, b"msg", hashlib.sha256).digest()
next_chain_key = hmac.new(chain_key, b"chain", hashlib.sha256).digest()
return next_chain_key, message_key
chain_key = hashlib.sha256(b"initial-x3dh-session-secret").digest()
message_keys: list[bytes] = []
for msg_num in range(1, 4):
chain_key, msg_key = step_chain(chain_key)
message_keys.append(msg_key)
print(f"Msg {msg_num}: MK={msg_key.hex()[:16]}... | next CK={chain_key.hex()[:16]}...")
assert len(set(message_keys)) == 3, "every message must get a unique key"
chain_key_3 = chain_key
_, mk4 = step_chain(chain_key_3)
print(f"Compromised chain_key_3: {chain_key_3.hex()[:16]}...")
print(f"Attacker can step forward to MK_4 ({mk4.hex()[:16]}...) until a DH ratchet heals.")
print(f"Forward secrecy: SHA-256 is one-way, so chain_key_3 cannot invert back to message_key_1 ({message_keys[0].hex()[:16]}...).")Apply
Your turn
The task this lesson builds to.
Architect a Signal-style end-to-end encrypted messenger supporting offline session start, forward secrecy, encrypted media attachments, and linked desktop devices.
Think about
- How does an X3DH pre-key bundle server enable encrypted first messages when the recipient is offline?
- How do the symmetric KDF ratchet and DH ratchet provide forward secrecy and post-compromise security?
- How do envelope-encrypted media blobs, Sealed Sender, and Safety Numbers close storage, metadata, and MITM gaps?
Draft your design answer here Save your draft, compare against the model answer, and track progress.
Practice
Make it stick
A second problem on the same idea, so it survives past today.
Outline the group-messaging encryption protocol and membership-change workflow for a 500-member E2EE chat where removed members must immediately lose access to future messages.
Think about
- Why does pairwise Sesame fan-out (500 encryptions per message) degrade battery and bandwidth in large groups?
- How do Signal Sender Keys differ from MLS (TreeKEM) when a member is removed?
- How do you defend against a malicious server that withholds a remove-member event from senders?
Draft your design answer here Save your draft, compare against the model answer, and track progress.