Client-Side Encryption Architecture in React: Web Crypto API, AES-GCM, and Zero-Knowledge State
Modern web applications frequently handle highly sensitive user data: personal health records, financial ledgers, private journals, credentials, and end-to-end encrypted chat logs. Traditional security models rely on Transport Layer Security (HTTPS) to encrypt data in transit and database encryption to protect data at rest. However, in these models, the backend server retains full access to plaintext user data. A compromised backend database, rogue cloud infrastructure, or subpoena can expose the user's most confidential information.
To achieve zero-knowledge privacy, modern architectures execute encryption and decryption directly on the client. The application server only ever stores and synchronizes encrypted opaque blobs (ciphertext). The cryptographic keys are derived locally from user master secrets and never leave the browser.
Historically, implementing cryptography in JavaScript required third-party libraries (such as CryptoJS) that executed slow math in unoptimized JS, were vulnerable to timing side-channel attacks, and exposed raw key bytes in memory.
The standardized Web Crypto API and its SubtleCrypto interface provide hardware-accelerated, timing-attack-resistant cryptographic primitives built directly into modern browser engines.
In this deep dive, we architect a production-grade, zero-knowledge client-side encryption system in React: deriving authenticated keys via PBKDF2, encrypting state with AES-GCM, managing non-extractable CryptoKey references with React Context, and preventing sensitive memory leakage.
The Zero-Knowledge Cryptographic Lifecycle
In an authenticated symmetric encryption architecture:
- Key Derivation (PBKDF2): A user's password or passphrase is transformed into a high-entropy symmetric key using SubtleCrypto.deriveKey() paired with a unique cryptographically random salt and high iteration count (e.g., 600,000 rounds of SHA-256).
- Authenticated Encryption (AES-GCM): Application state is serialized into bytes and encrypted using SubtleCrypto.encrypt() with AES-GCM (Galois/Counter Mode). AES-GCM provides both confidentiality and built-in ciphertext integrity authentication.
- Initialization Vector (IV): A fresh 96-bit (12-byte) random IV is generated for every single encryption operation. Reusing an IV with the same AES-GCM key catastrophically compromises the cipher.
- Ciphertext Envelope: The salt, IV, and ciphertext are packaged together into a portable payload for backend persistence.
+-----------------------------------------------------------------------------------+
| Client Browser (React Context) |
| |
| [User Passphrase] + [Random Salt (16B)] |
| | |
| v |
| [PBKDF2 Derivation (600,000 iterations)] =====> [Non-Extractable CryptoKey] |
| | |
| [Plaintext React State / JSON] | |
| | | |
| v v |
| [TextEncoder] + [Random IV (12B)] ==================> [AES-GCM 256-bit Encrypt] |
| | |
| v |
| [Ciphertext + Auth Tag] |
| | |
| v |
| [Packaged Payload: Salt + IV + Data] |
+--------------------------------------------------------------|--------------------+
v (HTTPS Sync)
+--------------------+
| Untrusted Backend |
| (Zero-Knowledge) |
+--------------------+
Core Cryptographic Primitives: crypto.ts
Let's build a modular cryptographic service using modern TypeScript and standard typed arrays:
// utils/crypto.ts
export interface EncryptedPayload {
cipherText: string; // Base64
iv: string; // Base64
salt: string; // Base64
}
// Helper: Convert ArrayBuffer to Base64
export function bufferToBase64(buffer: ArrayBuffer): string {
const bytes = new Uint8Array(buffer);
let binary = '';
for (let i = 0; i < bytes.byteLength; i++) {
binary += String.fromCharCode(bytes[i]);
}
return window.btoa(binary);
}
// Helper: Convert Base64 to Uint8Array
export function base64ToBuffer(base64: string): Uint8Array {
const binary = window.atob(base64);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) {
bytes[i] = binary.charCodeAt(i);
}
return bytes;
}
/**
* Derives an AES-GCM 256-bit CryptoKey from a password and salt using PBKDF2.
* The key is configured as `extractable: false` so it cannot be read back by scripts.
*/
export async function deriveKeyFromPassword(
password: string,
salt: Uint8Array
): Promise<CryptoKey> {
const encoder = new TextEncoder();
const passwordKey = await window.crypto.subtle.importKey(
'raw',
encoder.encode(password),
{ name: 'PBKDF2' },
false,
['deriveKey']
);
return window.crypto.subtle.deriveKey(
{
name: 'PBKDF2',
salt: salt,
iterations: 600000, // Recommended standard for SHA-256
hash: 'SHA-256',
},
passwordKey,
{ name: 'AES-GCM', length: 256 },
false, // Non-extractable: raw key bytes cannot be stolen via devtools/scripts
['encrypt', 'decrypt']
);
}
/**
* Encrypts arbitrary serializable data using AES-GCM.
*/
export async function encryptData(
key: CryptoKey,
salt: Uint8Array,
plainData: unknown
): Promise<EncryptedPayload> {
const encoder = new TextEncoder();
const jsonString = JSON.stringify(plainData);
const encodedPlaintext = encoder.encode(jsonString);
// Generate a fresh 12-byte (96-bit) IV for this specific message
const iv = window.crypto.getRandomValues(new Uint8Array(12));
const cipherBuffer = await window.crypto.subtle.encrypt(
{
name: 'AES-GCM',
iv: iv,
},
key,
encodedPlaintext
);
return {
cipherText: bufferToBase64(cipherBuffer),
iv: bufferToBase64(iv),
salt: bufferToBase64(salt),
};
}
/**
* Decrypts an EncryptedPayload back into its typed JavaScript structure.
*/
export async function decryptData<T>(
key: CryptoKey,
payload: EncryptedPayload
): Promise<T> {
const decoder = new TextDecoder();
const ivBuffer = base64ToBuffer(payload.iv);
const cipherBuffer = base64ToBuffer(payload.cipherText);
const decryptedBuffer = await window.crypto.subtle.decrypt(
{
name: 'AES-GCM',
iv: ivBuffer,
},
key,
cipherBuffer
);
const jsonString = decoder.decode(decryptedBuffer);
return JSON.parse(jsonString) as T;
}
Managing Cryptographic Sessions: The VaultContext
A common hazard in React applications is storing raw encryption passwords in component state or localStorage. If an attacker exploits an XSS vulnerability or an untrusted NPM dependency, any credentials stored in localStorage or plain global state can be extracted.
By leveraging non-extractable CryptoKey objects, the raw cryptographic bytes reside inside the browser's protected internal C++ engine memory. JavaScript can use the key to encrypt and decrypt, but calling crypto.subtle.exportKey() throws an error.
Here is a VaultContext that manages the user's active session:
// context/VaultContext.tsx
import React, { createContext, useContext, useState, useCallback, useRef } from 'react';
import {
deriveKeyFromPassword,
encryptData,
decryptData,
EncryptedPayload,
} from '../utils/crypto';
interface VaultContextValue {
isUnlocked: boolean;
unlockVault: (passphrase: string, storedSalt?: string) => Promise<string>;
lockVault: () => void;
encrypt: (data: unknown) => Promise<EncryptedPayload>;
decrypt: <T>(payload: EncryptedPayload) => Promise<T>;
}
const VaultContext = createContext<VaultContextValue | null>(null);
export function VaultProvider({ children }: { children: React.ReactNode }) {
const [isUnlocked, setIsUnlocked] = useState<boolean>(false);
const activeKeyRef = useRef<CryptoKey | null>(null);
const activeSaltRef = useRef<Uint8Array | null>(null);
const lockVault = useCallback(() => {
activeKeyRef.current = null;
activeSaltRef.current = null;
setIsUnlocked(false);
}, []);
const unlockVault = useCallback(async (passphrase: string, storedSalt?: string) => {
let salt: Uint8Array;
if (storedSalt) {
const binary = window.atob(storedSalt);
salt = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) {
salt[i] = binary.charCodeAt(i);
}
} else {
salt = window.crypto.getRandomValues(new Uint8Array(16));
}
const key = await deriveKeyFromPassword(passphrase, salt);
activeKeyRef.current = key;
activeSaltRef.current = salt;
setIsUnlocked(true);
// Return the base64 salt so the app can persist it alongside the ciphertext
return window.btoa(String.fromCharCode(...salt));
}, []);
const encrypt = useCallback(async (data: unknown) => {
if (!activeKeyRef.current || !activeSaltRef.current) {
throw new Error('Vault is locked. Cannot encrypt data.');
}
return encryptData(activeKeyRef.current, activeSaltRef.current, data);
}, []);
const decrypt = useCallback(async <T,>(payload: EncryptedPayload): Promise<T> => {
if (!activeKeyRef.current) {
throw new Error('Vault is locked. Cannot decrypt data.');
}
return decryptData<T>(activeKeyRef.current, payload);
}, []);
return (
<VaultContext.Provider
value={{ isUnlocked, unlockVault, lockVault, encrypt, decrypt }}
>
{children}
</VaultContext.Provider>
);
}
export function useVault(): VaultContextValue {
const context = useContext(VaultContext);
if (!context) {
throw new Error('useVault must be used within a VaultProvider');
}
return context;
}
Production Secure Journal Component
Now, let's assemble a complete, production-ready private notes interface. Users enter private notes that are immediately encrypted into ciphertext before being stored or synced:
// components/SecureJournal.tsx
import React, { useState } from 'react';
import { useVault } from '../context/VaultContext';
import { EncryptedPayload } from '../utils/crypto';
interface JournalEntry {
id: string;
timestamp: number;
title: string;
body: string;
}
export function SecureJournal() {
const { isUnlocked, unlockVault, lockVault, encrypt, decrypt } = useVault();
const [passphrase, setPassphrase] = useState('');
const [isDeriving, setIsDeriving] = useState(false);
const [entries, setEntries] = useState<JournalEntry[]>([]);
const [encryptedStorage, setEncryptedStorage] = useState<EncryptedPayload[]>([]);
const [title, setTitle] = useState('');
const [body, setBody] = useState('');
// Unlock Vault and derive key
const handleUnlock = async (e: React.FormEvent) => {
e.preventDefault();
if (!passphrase) return;
try {
setIsDeriving(true);
await unlockVault(passphrase);
setPassphrase('');
} catch (err) {
console.error('Failed to unlock vault:', err);
} finally {
setIsDeriving(false);
}
};
// Create an entry and encrypt it immediately
const handleSaveEntry = async (e: React.FormEvent) => {
e.preventDefault();
if (!title || !body) return;
const newEntry: JournalEntry = {
id: crypto.randomUUID(),
timestamp: Date.now(),
title,
body,
};
try {
// 1. Encrypt with AES-GCM
const encryptedBlob = await encrypt(newEntry);
// 2. Persist only ciphertext
setEncryptedStorage((prev) => [...prev, encryptedBlob]);
// 3. Keep decrypted view in local session state
setEntries((prev) => [newEntry, ...prev]);
setTitle('');
setBody('');
} catch (err) {
console.error('Encryption failed:', err);
}
};
if (!isUnlocked) {
return (
<div className="max-w-md mx-auto p-6 bg-slate-900 border border-slate-800 rounded-2xl shadow-xl">
<h2 className="text-xl font-bold text-white mb-2">Unlock Secure Vault</h2>
<p className="text-xs text-slate-400 mb-6">
Your master passphrase derives an AES-GCM 256-bit key locally using PBKDF2 (600,000 rounds). The server never receives your password.
</p>
<form onSubmit={handleUnlock} className="space-y-4">
<input
type="password"
placeholder="Enter master passphrase"
value={passphrase}
onChange={(e) => setPassphrase(e.target.value)}
className="w-full px-4 py-2 bg-slate-950 border border-slate-700 rounded-lg text-white text-sm focus:outline-none focus:ring-2 focus:ring-sky-500"
/>
<button
type="submit"
disabled={isDeriving}
className="w-full py-2 px-4 bg-sky-500 hover:bg-sky-600 disabled:bg-slate-700 text-white font-semibold rounded-lg text-sm transition"
>
{isDeriving ? 'Deriving Cryptographic Key...' : 'Unlock Vault'}
</button>
</form>
</div>
);
}
return (
<div className="max-w-3xl mx-auto p-6 bg-slate-900 border border-slate-800 rounded-2xl shadow-xl space-y-6">
<div className="flex items-center justify-between pb-4 border-b border-slate-800">
<div>
<h2 className="text-xl font-bold text-white">Private Encrypted Journal</h2>
<span className="text-xs text-emerald-400 font-mono flex items-center gap-1 mt-1">
<span className="w-2 h-2 rounded-full bg-emerald-500 animate-pulse" />
Zero-Knowledge Session Active
</span>
</div>
<button
onClick={lockVault}
className="px-3 py-1.5 text-xs font-semibold bg-rose-600 hover:bg-rose-700 text-white rounded-lg transition"
>
Lock Vault
</button>
</div>
<form onSubmit={handleSaveEntry} className="space-y-3">
<input
type="text"
placeholder="Entry title"
value={title}
onChange={(e) => setTitle(e.target.value)}
className="w-full px-4 py-2 bg-slate-950 border border-slate-700 rounded-lg text-white text-sm focus:ring-2 focus:ring-sky-500 focus:outline-none"
/>
<textarea
placeholder="Write confidential note..."
rows={3}
value={body}
onChange={(e) => setBody(e.target.value)}
className="w-full px-4 py-2 bg-slate-950 border border-slate-700 rounded-lg text-white text-sm focus:ring-2 focus:ring-sky-500 focus:outline-none"
/>
<button
type="submit"
className="px-4 py-2 bg-sky-500 hover:bg-sky-600 text-white text-xs font-semibold rounded-lg transition"
>
Encrypt & Save Note
</button>
</form>
<div className="space-y-4">
<h3 className="text-sm font-semibold text-slate-300">Decrypted Session Entries</h3>
{entries.length === 0 ? (
<p className="text-xs text-slate-500">No notes written in this session yet.</p>
) : (
entries.map((entry) => (
<div
key={entry.id}
className="p-4 rounded-xl bg-slate-950 border border-slate-800 space-y-1"
>
<div className="flex justify-between items-center">
<h4 className="font-semibold text-sm text-sky-400">{entry.title}</h4>
<span className="text-[10px] text-slate-500">
{new Date(entry.timestamp).toLocaleTimeString()}
</span>
</div>
<p className="text-xs text-slate-300">{entry.body}</p>
</div>
))
)}
</div>
{/* Audit View: Demonstrates what an attacker/backend actually sees */}
<div className="p-4 bg-black/60 rounded-xl border border-slate-800 space-y-2">
<h4 className="text-xs font-mono text-slate-400">
Backend Storage Inspector (Ciphertext Blobs)
</h4>
<div className="max-h-28 overflow-y-auto font-mono text-[11px] text-slate-500 space-y-1">
{encryptedStorage.map((blob, idx) => (
<div key={idx} className="truncate">
[{idx + 1}] IV: {blob.iv.slice(0, 8)}... | Cipher: {blob.cipherText.slice(0, 32)}...
</div>
))}
</div>
</div>
</div>
);
}
Architectural Comparison & Security Trade-Offs
| Security Layer | Standard TLS / HTTPS | Server-Side Encryption (KMS) | Client-Side Web Crypto (Zero-Knowledge) |
|---|---|---|---|
| Data in Transit | Encrypted | Encrypted | Double Encrypted |
| Server Inspection | Full Plaintext Access | Full Plaintext Access | ❌ Zero Plaintext Access |
| Database Breach Impact | Plaintext Leaked | Plaintext Leaked if KMS keys compromised | Ciphertext is uncrackable |
| Searchability | Full text SQL/Elasticsearch | Full text indexed | ❌ Blind Indexing or Client Search only |
| Password Recovery | Trivial (Email reset) | Trivial (Email reset) | ❌ Impossible without Recovery Key |
Key Production Best Practices
- Enforce Non-Extractability: Always instantiate keys with
extractable: false. This ensures malicious browser extensions or compromised vendor scripts cannot invokecrypto.subtle.exportKey('raw', key). - Never Reuse IVs: In AES-GCM, encrypting two different plaintexts with the exact same key and IV allows an attacker to compute the XOR of the plaintexts and forge authentication tags. Always generate a fresh 12-byte IV using
crypto.getRandomValues(new Uint8Array(12)). - Account for Search Trade-offs: Because the backend only holds opaque ciphertext, traditional server-side search (
LIKE %query%) is impossible. Solutions include client-side indexing (such as MiniSearch running in an IndexedDB cache) or homomorphic blind indexing hashes. - Implement Key Rotation: If a user updates their master passphrase, decrypt all active records in memory using the old key and re-encrypt them under the newly derived key with fresh IVs.
Conclusion
Client-side encryption turns the conventional security paradigm on its head. By shifting cryptographic trust boundaries into the browser using the Web Crypto API and AES-GCM, React developers can build zero-knowledge applications where even a catastrophic database compromise leaves user confidentiality completely intact.