Software development · Security · Tutorial

End-to-end encryption in the browser with the Web Crypto API

A practical tutorial on encrypting messages in the browser with ECDH key agreement, HKDF and AES-256-GCM using the built-in Web Crypto API, plus the mistakes to avoid.

To encrypt end to end in the browser, give each device an ECDH key pair from the Web Crypto API, share only the public keys, derive a shared secret, turn it into an AES-256-GCM key with HKDF, and encrypt every message with a fresh random 12-byte IV. The server only ever stores ciphertext and public keys.

Shroud, the encrypted messenger we built at LOLCorp, is built on a simple promise: what you say to people you trust stays between you. In the browser, the foundation for that is already built in. The Web Crypto API gives you audited, fast, native cryptography without shipping a JavaScript crypto library. This tutorial walks through the core building blocks. It is a starting point for understanding, not a complete secure messaging protocol.

1. Generate a key pair on the device

const keyPair = await crypto.subtle.generateKey(
  { name: 'ECDH', namedCurve: 'P-256' },
  false,                       // the private key can never be exported
  ['deriveBits']
);

// The public key is always exportable, so it can be shared.
const publicJwk = await crypto.subtle.exportKey('jwk', keyPair.publicKey);

Marking the key as non-extractable means even your own JavaScript can't read the private key bytes. You can still store the CryptoKey object in IndexedDB so it survives a page reload, and it never leaves the device.

2. Derive a shared key

When Alice has Bob's public key and Bob has Alice's, each side can compute the same shared secret without it ever crossing the network. Run it through HKDF to get a proper encryption key:

async function deriveMessageKey(myPrivateKey, theirPublicJwk, salt) {
  const theirPublicKey = await crypto.subtle.importKey(
    'jwk', theirPublicJwk, { name: 'ECDH', namedCurve: 'P-256' }, false, []
  );
  const shared = await crypto.subtle.deriveBits(
    { name: 'ECDH', public: theirPublicKey }, myPrivateKey, 256
  );
  const hkdfKey = await crypto.subtle.importKey('raw', shared, 'HKDF', false, ['deriveKey']);
  return crypto.subtle.deriveKey(
    { name: 'HKDF', hash: 'SHA-256', salt, info: new TextEncoder().encode('chat-message-key-v1') },
    hkdfKey,
    { name: 'AES-GCM', length: 256 },
    false,
    ['encrypt', 'decrypt']
  );
}

The info label ties the key to one purpose. If you later derive keys for files or calls, use a different label for each so one key is never reused for two jobs.

3. Encrypt and decrypt messages

async function encrypt(key, text) {
  const iv = crypto.getRandomValues(new Uint8Array(12));   // new for EVERY message
  const ciphertext = await crypto.subtle.encrypt(
    { name: 'AES-GCM', iv }, key, new TextEncoder().encode(text)
  );
  return { iv, ciphertext };        // both are sent; the IV is not secret
}

async function decrypt(key, { iv, ciphertext }) {
  const plain = await crypto.subtle.decrypt({ name: 'AES-GCM', iv }, key, ciphertext);
  return new TextDecoder().decode(plain);
}

AES-GCM is authenticated: if anyone changes a single bit of the ciphertext, decrypt throws instead of returning tampered text. Treat that error as a security event, not a glitch.

The mistakes that break encryption

  • Reusing an IV with the same key. With AES-GCM this can leak plaintext and let attackers forge messages. Always generate a new random 12-byte IV.
  • Trusting the server to hand out the right public keys. A malicious or compromised server could swap in its own key. Let users compare a safety number or QR code derived from both public keys, and warn them when a contact's key changes.
  • One static key forever. If a long-lived key leaks, every past message can be read. Real messengers use a ratchet, such as the Signal protocol's Double Ratchet, to rotate keys per message and provide forward secrecy.
  • Leaking through the edges. Push notification previews, analytics events, error reports and search indexes can all contain plaintext. Audit every place message content flows.
  • Serving the app code insecurely. In the browser, the code doing the encryption comes from your server. Use HTTPS everywhere, a strict Content Security Policy and Subresource Integrity on any third-party scripts.

What the server still sees

End-to-end encryption hides message content, not everything. The server still knows who talks to whom, when and how much. If metadata matters for your users, minimise what you log, delete it quickly and say plainly what you can and cannot see.

FAQ

Is the Web Crypto API secure enough for end-to-end encryption?

Yes. It exposes the browser's native, well-tested implementations of standard algorithms such as ECDH, HKDF and AES-GCM. The risks are in how you use it: key exchange, IV handling and key verification.

Should I use AES-GCM or AES-CBC?

AES-GCM. It provides both confidentiality and integrity, so tampered messages are rejected. AES-CBC needs a separate MAC to be safe and is easy to get wrong.

Can I build my own encrypted messaging protocol?

For learning, yes. For production, build on a reviewed protocol such as Signal's, and get the design reviewed by someone who does cryptography professionally.

Keep reading