End-to-end encryption in my chat app: static ECDH, and where it breaks
How ChatApp encrypts every message in the browser with the Web Crypto API, the reload bug that kept destroying keys, and why one shared key isn't enough.
ChatApp started as a way to understand how messaging apps like WhatsApp work behind the scenes: real-time delivery, voice and video calls, offline support, and end-to-end encryption (E2EE). The encryption part taught me the most, partly because of a bug that kept silently destroying everyone's keys.
The goal of E2EE is simple to say: the server should only ever store scrambled text. MongoDB and my Node.js backend should never see what you actually wrote.
The idea: two keys, one shared secret
Every user gets an ECDH key pair on the P-256 curve. The private key never leaves the device. The public key goes to the server so contacts can download it. ECDH has one useful property: if Alice combines her private key with Bob's public key, she gets exactly the same secret Bob gets by combining his private key with her public key.
SharedAESKey1 = Bob's Public Key + Alice's Private Key
SharedAESKey2 = Alice's Public Key + Bob's Private Key
SharedAESKey1 === SharedAESKey2Both devices end up with the same 256-bit AES key without it ever being sent anywhere. The Web Crypto API does this in one call:
export async function deriveSharedAESKey(myPrivateKey, peerPublicKey) {
return await window.crypto.subtle.deriveKey(
{ name: 'ECDH', public: peerPublicKey },
myPrivateKey,
{ name: 'AES-GCM', length: 256 },
false, // Non-extractable shared secret
['encrypt', 'decrypt']
)
}Encrypting a message
Messages are encrypted with AES-GCM, using a fresh random 12-byte IV for every message. Reusing an IV with the same key is one of the classic ways to break AES-GCM, so this matters.
export async function encryptMessageText(text, aesKey) {
const data = new TextEncoder().encode(text)
const iv = window.crypto.getRandomValues(new Uint8Array(12))
const ciphertextBuffer = await window.crypto.subtle.encrypt({ name: 'AES-GCM', iv }, aesKey, data)
return {
ciphertext: btoa(String.fromCharCode(...new Uint8Array(ciphertextBuffer))),
iv: btoa(String.fromCharCode(...iv)),
}
}On the backend, the Message schema just gained two fields: isEncrypted and iv. The text field now holds ciphertext. When Alice sends "Hello Bob", the server stores something like "x89Fk2mP..." and never sees the original.
The bug: keys that died on reload
The first version worked perfectly until I refreshed the page. Then every old message showed "[Encrypted Message - Decryption Failed]".
I was saving the raw CryptoKey objects straight into IndexedDB. A CryptoKey isn't plain data. It's a handle to key material held inside the browser's crypto engine, and on several browsers and mobile webviews it didn't come back after a reload. IndexedDB returned null, the app assumed this was a new device, generated a brand-new key pair, and the new key couldn't decrypt anything sent with the old one.
The fix, the same day, was to export the keys to JWK (JSON Web Key) before storing them. A JWK is just a JSON object with the key's numbers in it, which every browser can save reliably. On the next load, importKey rebuilds the exact same key.
async function saveKeyPairToIndexedDB(userId, keyPair) {
const privateJwk = await window.crypto.subtle.exportKey('jwk', keyPair.privateKey)
const publicJwk = await window.crypto.subtle.exportKey('jwk', keyPair.publicKey)
const db = await openCryptoDB()
// ...store.put({ privateJwk, publicJwk }, userId)
// Also cache in localStorage as secondary fallback across page reloads & mobile webviews
localStorage.setItem(`chatapp_ecdh_key_${userId}`, JSON.stringify({ privateJwk, publicJwk }))
}A key pair is only generated once per device now. Every later visit loads the same keys, and old messages stay readable.
Where static ECDH breaks
This setup protects messages from the server and the database, which was the goal. But it has two real weaknesses, and they both come from the same fact: the shared key never changes.
- No forward secrecy: if someone steals your private key and has recorded old encrypted traffic, they can derive the shared key and decrypt every past message.
- No post-compromise security: once a key leaks, every future message in that chat is readable too, until the user clears storage and generates new keys.
“One key protecting a conversation forever is one key too few.”
What the Double Ratchet changes
This is why Signal and WhatsApp use the Double Ratchet protocol. It uses the same ECDH formula, but the keys inside it keep changing. It combines two ratchets:
- A KDF hash chain: every message gets its own key, derived from the previous one, and old keys are deleted right after use. That gives forward secrecy.
- A Diffie-Hellman ratchet: every time someone replies, they generate a new temporary key pair, so both sides derive a completely new shared secret and throw away the old one. That gives post-compromise security.
Secure messaging turns out to be less about encrypting text and more about designing a key lifecycle that keeps evolving.
What I'd tighten next
Looking back at this code, there are three things I would fix before calling this production-grade, separate from the Double Ratchet:
- The localStorage fallback. I added it so keys survive on mobile webviews, but it means the private key also sits in localStorage as plain JSON. Any script that runs on the page through an XSS bug could read it in one line. Keeping keys only in IndexedDB, ideally as non-extractable keys where the browser supports it, shrinks that risk a lot.
- One public key per user. Each device generates its own key pair and uploads its public key with
PUT /public-key, which overwrites the previous one. Log in on a second device and your first device can no longer decrypt new messages. Real apps keep one key per device and encrypt each message for every device the person owns. - Trusting the server with public keys. Contacts download your public key from my server. A malicious or compromised server could hand out its own key instead and read everything in the middle. That's why Signal and WhatsApp show safety numbers or a QR code you can compare in person.
The group chat problem, and what I found
Here is what bothered me when I posted about this: picture a group of 1,000 people. With pairwise encryption, one message has to be encrypted 1,000 separate times, once per member. That drains battery and bandwidth fast, and it grows linearly with the group.
Digging into it, there are two answers in production today:
- Sender Keys (what WhatsApp does for groups): your device creates one sender key, ratchets it with a KDF, and sends it to each member once. After that, every group message is encrypted only once with that key.
- MLS (Messaging Layer Security, IETF RFC 9420, finalized in 2023): members are arranged in a binary tree (TreeKEM), so adding, removing or updating keys costs O(log N) instead of O(N). It is built for groups with thousands of members, and Wire and Webex use it.
And the frontier after that is post-quantum E2EE, which adds a lattice-based layer (Kyber / ML-KEM) on top of ECDH to defend against "harvest now, decrypt later" attacks. Signal (PQXDH) and iMessage (PQ3) already ship it.
The rest of ChatApp
Encryption was the deepest part, but ChatApp pushed me into a lot of other areas:
- WebRTC peer-to-peer voice and video calls, plus screen sharing: signaling, ICE candidate exchange, media controls.
- Real-time messaging with Socket.IO: typing indicators, reactions, replies, pinned messages, unread counters and reconnection.
- Offline-first messaging with Service Workers, IndexedDB and background sync.
- Auth with Better Auth: 30-day sessions plus Google and GitHub OAuth.
- A backend with rate limiting, Helmet, CORS, input sanitization and proxy-aware IP handling, all running in Docker.
Stack: React 18 (Vite), Tailwind CSS, Node.js, Express, MongoDB, Socket.IO, Better Auth, WebRTC, the Web Crypto API, IndexedDB, Service Workers, Cloudinary and Docker.