If a web app encrypts every message inside your browser and never sends the decryption key to its server, can you automatically trust the session? Most tutorials on client-side encryption in JavaScript imply that the answer is yes. They walk you through generating a key, calling an encryption method, and shipping unreadable ciphertext across the wire, then stop right before the hardest security boundary in web engineering.
Server breaches happen often enough to make local encryption attractive. In 2024, 50% of UK businesses reported experiencing at least one cyber security breach or attack during the previous 12 months, according to the UK Government's Cyber Security Breaches Survey. Keeping plaintext off a remote database removes a huge target, because a compromised server can only leak scrambled bytes.
Even so, browser cryptography operates inside a strict boundary that developers and users rarely examine closely. Encryption running in your browser tab is only as trustworthy as the JavaScript the website delivers to that tab. Understanding how each layer works, from key derivation to authenticated encryption to code delivery, lets you judge what browser encryption protects and where its guarantees stop.
What Stays in the Browser and What the Server Sees
If a server only stores ciphertext, what exactly is being protected, and what still has to travel across the network for two people to talk? Picture sending a sealed physical letter through a postal relay. You write the note at your desk, slide it into a tamper-evident envelope, and lock it with a key that only you and the recipient hold. The courier sees the envelope, the address label, and the postmark, yet the courier can't open the seal or read a word inside.
A browser-encrypted chat works the same way. Say two people open a private channel to share sensitive notes without creating accounts. One person generates a channel link and a shared secret locally, then hands that secret to the other person over a separate medium like a phone call or an encrypted messenger. From that point on, the browser handles every piece of sensitive data before anything touches the network, while the relay handles only the outer envelope.
Where Each Item Lives in a Client-Side Encrypted Channel
| Item | Stays in browser | Sent to relay | Why it matters |
|---|---|---|---|
| Access key | Yes | No | Shared out of band; the server never needs it |
| Derived AES-256 key | Yes | No | Lives in browser memory only |
| Plaintext message or file | Yes | No | Encrypted before it touches the network |
| Ciphertext | Yes | Yes | Opaque output the relay stores |
| IV (initialization vector) | Yes | Yes | Not secret, but must be unique for every message |
| Authentication tag | Yes | Yes | Makes any tampering fail decryption |
| Salt | Yes | Yes | Per channel; needed to re-derive the same key |
| Expiry timestamp | Yes | Yes | Enforces the channel lifetime on the server |
Follow the data in the order your browser creates it. First, the access key is shared out of band, so the server never receives it. Next, your browser turns that access key into a derived AES-256 key that stays in browser memory and is never sent to the server. Every plaintext message or file is encrypted locally before leaving your device.
What crosses the wire are the public envelope fields. The relay sees only opaque ciphertext, an initialization vector (IV), an authentication tag, a per-channel salt, and an expiry timestamp, and it never sees passwords, derived keys, messages, or files. Developers often worry when they see IVs and salts sitting in plaintext beside ciphertext in a database, so it helps to remember their jobs. An IV ensures that encrypting the same message twice produces completely different ciphertext, while a salt ensures that two channels using similar secrets still derive different keys. Neither value lets an observer reverse the encryption without the secret key.
That separation is the foundation of a zero-knowledge encrypted chat server architecture. It's also the same architectural boundary security reviewers look for when they compare encrypted email services and evaluate whether a provider holds any decryption material on its infrastructure.
Practical audit test: List every single field a web app's server stores for a session, then ask whether an engineer with full database access could recover plaintext from that list alone. If the answer is yes, you don't have true client-side encryption.
How Web Crypto Gives JavaScript Real Cryptography
For years, building client-side encryption in JavaScript meant choosing between two bad options. Developers either forced users to install browser plug-ins or pulled in pure JavaScript cipher libraries written by hand. Hand-written JavaScript cryptography was slow, hard to audit, and notoriously prone to side-channel leaks, where tiny timing differences during math operations could betray bits of a secret key.
Things changed on January 26, 2017, when the World Wide Web Consortium published the W3C Web Cryptography API Recommendation. Moving encryption, decryption, hashing, digital signatures, signature verification, and key management into a standardized browser interface gave web applications access to native, compiled cryptographic primitives. Instead of running custom math loops in interpreted JavaScript, a web app hands its bytes to the browser's underlying crypto engine.

Inside SubtleCrypto and Browser Randomness
Every modern browser exposes these primitives through the window.crypto.subtle object, known as SubtleCrypto. Two operations carry most of the weight in browser-based encrypted chat:
- PBKDF2 for key derivation: Transforms a human-readable channel secret into structured cryptographic key material inside the browser.
- AES-GCM for authenticated encryption: Scrambles messages and files while generating an integrity tag in one pass. The underlying cipher belongs to the Advanced Encryption Standard, published by the National Institute of Standards and Technology as FIPS 197 on November 26, 2001. AES processes data in 128-bit blocks using keys of 128, 192, or 256 bits, with AES-256 running 14 encryption rounds.
- Native cryptographic randomness: Generates salts, IVs, and access secrets using
crypto.getRandomValues, pulling entropy directly from the operating system's secure random generator.
Never substitute Math.random() for cryptographic values. Math.random() uses a predictable pseudorandom algorithm designed for animations and UI math, not security; an attacker who observes a handful of outputs can often predict future values. All randomness in our browser channels comes straight from the browser's native crypto random source instead.
Relying on native SubtleCrypto implementations also spares developers from writing custom block-cipher code in JavaScript, where memory management and constant-time execution are nearly impossible to guarantee. Still, the W3C specification is explicit about its boundaries. Having standardized primitives doesn't automatically yield a secure product. Key lifecycle management, participant authentication, metadata hygiene, and the integrity of the JavaScript delivered to the browser all remain the application's job.
Turning a Shared Access Key into an AES Key
Humans are terrible at typing 256 random bits from memory, yet AES-256 needs an exact 256-bit binary key. A browser app bridges that gap by taking a readable shared secret and stretching it through a key derivation function. When a channel is created in Ciphar, the browser generates the channel name, which is the URL, and a random access key, which works as the password, locally on the device. The access key then feeds into PBKDF2-HMAC-SHA-256 with a per-channel salt.
That derivation step is like turning a spoken passphrase into a shaped key that fits a lock. The passphrase is easier for people to carry, while the derived key has the exact form the cipher expects. Ciphar derives the encryption key from the access key and a per-channel salt using PBKDF2 with 100,000 SHA-256 iterations, producing a 256-bit AES key. The MDN Web Docs guide for SubtleCrypto.deriveKey documents browser-side derivation with PBKDF2-HMAC-SHA-256 and 100,000 iterations to output a 256-bit AES-GCM key, matching that construction. The derived encryption key stays in browser memory and is never sent to the server.
Choosing an iteration count is a trade-off between join latency and offline guessing resistance. More rounds make each legitimate derivation slower, and they also make each password guess more expensive if an attacker obtains ciphertext, salt, and verification material. The useful comparison is therefore between parameters and the secret itself, not between a browser setting and a universal number.
Key Derivation Settings Compared
| Parameter | Ciphar as documented | Practical role |
|---|---|---|
| Hash function | HMAC-SHA-256 within PBKDF2 | Mixes the access key and salt repeatedly |
| Iterations | 100,000 | Adds work to each derivation and each guess |
| Salt | Random, unique per channel | Prevents one precomputed table from covering many channels |
| Derived key | 256-bit AES-GCM key | Fits the symmetric cipher used for channel content |
| Entropy source | Browser secure random generator | Keeps generated access keys and salts unpredictable |
Each row controls a specific defensive property. HMAC-SHA-256 is the pseudorandom function inside PBKDF2, folding the access key and salt through every round. The per-channel random salt means an attacker cannot reuse one lookup table across multiple channels. Each stolen channel payload requires its own cracking work. The 256-bit output gives SubtleCrypto a full-strength symmetric key for AES-GCM.
Access keys are built from words in a fixed dictionary, so they are easy to read aloud or paste into another encrypted medium. That readability has a boundary. For a deeper look at how browser-native key derivation compares with memory-hard alternatives, see our breakdown of PBKDF2 vs. Argon2. You can also watch this quick walkthrough on how password-based key derivation works under the hood before tuning your own parameters.
Why Iterations Are Not a Substitute for Entropy
Raising the iteration count increases the CPU work required for every legitimate participant joining a channel. It also multiplies the cost for an attacker trying to guess passwords offline if ciphertext, salt, and verification blobs are ever taken from a relay.
PBKDF2 does not create entropy out of thin air. Stretching a short, predictable secret many times still leaves a weak secret.
If a human chooses a short, predictable phrase as a channel password, an attacker with offline ciphertext can test common words without facing live rate limits. Failed-access rate limiting and encrypted verification blobs slow online guessing against a live relay, yet they offer no protection once ciphertext leaves the server. That is why the secret itself should be generated with the browser's cryptographically secure random generator, with PBKDF2 used as a derivation and stretching step.
Before changing a work factor in production, benchmark real devices instead of guessing from a fast developer laptop. Measure median and worst-case derivation latency, memory pressure, and battery impact across Chrome, Safari, and Firefox on representative low-end mobile phones. Once a parameter set balances security margin against mobile responsiveness, publish the exact parameters and a clear migration policy so users can audit the trade-off themselves. The same discipline applies to application integrity: a strong derivation routine only helps when the JavaScript delivered to the browser is the code users intended to run.
Encrypting Each Message with AES-256-GCM
Once the browser holds a derived 256-bit key, it needs a cipher mode that delivers both secrecy and tamper detection in a single operation. Older modes like AES-CBC only hide message contents; without a separate Message Authentication Code, an attacker could flip bits in transit. AES-256-GCM (Galois/Counter Mode) solves both problems at once by producing ciphertext alongside an authentication tag, as specified in NIST Special Publication 800-38D.

Step-by-Step Message Encryption Flow
- Generate a fresh, unpredictable 96-bit IV for every message. Call
crypto.getRandomValues(new Uint8Array(12))right before encrypting each message or file, because NIST identifies reusing an IV with the same GCM key as a critical failure that can destroy both confidentiality and authenticity. A common mistake is using an incrementing counter stored only in memory; if a user opens a second tab or reloads the page, the counter resets and collides with earlier messages. - Bind protocol metadata as additional authenticated data (AAD). Encode the channel identifier, message type, sequence number, and expiry context into a single byte array and pass it as
additionalData. Leaving metadata outside AAD lets a compromised relay copy valid ciphertext from one channel into another, or alter a message's classification without triggering a decryption error. - Encrypt the payload inside the browser with a non-extractable key. Pass the plaintext bytes, IV, and AAD to
crypto.subtle.encryptusing your derivedCryptoKey. Always createaesKeywithextractableset tofalsewhenever the application doesn't need to export raw key bytes, which reduces the chance of accidental key leakage through logging or buggy serialization code. - Collect the ciphertext and authentication tag. Web Crypto appends the authentication tag directly to the end of the returned buffer, and your app stores the 96-bit IV right beside it. Keep the authentication tag at its full strength; NIST has proposed removing support for GCM tags shorter than 96 bits because shorter tags weaken forgery resistance.
- Transmit only the opaque bundle to the relay. Send the ciphertext, IV, tag, and authenticated metadata over the network while keeping the plaintext and key strictly local. Because the server holds only ciphertext and doesn't have the key, it can't read messages or hand cleartext to a court, an attacker, or an employee.
- Verify and decrypt on the receiving client. The recipient's browser passes the exact same IV, AAD, ciphertext, and derived key into
crypto.subtle.decrypt. On our platform, a new participant is admitted to a channel only if their browser derives the same key and successfully decrypts the channel's test blob; otherwise they never enter the channel.
How SubtleCrypto Calls Look in Practice
In application code, steps one through six boil down to four asynchronous operations in your browser script:
const iv = crypto.getRandomValues(new Uint8Array(12));const aad = new TextEncoder().encode(channelId + '|' + type + '|' + seq + '|' + expiry);const ct = await crypto.subtle.encrypt({ name: 'AES-GCM', iv, additionalData: aad }, aesKey, plaintextBytes);const pt = await crypto.subtle.decrypt({ name: 'AES-GCM', iv, additionalData: aad }, aesKey, ct);
Pay close attention to what happens when decryption fails. If a single bit of the ciphertext, the authentication tag, or any field inside aad was altered in transit, crypto.subtle.decrypt doesn't return garbled characters. It throws a rejected promise (OperationError). Your user interface must catch that rejection and display an explicit verification failure state instead of rendering partial or unverified output. For a closer technical look at GCM internals and tag verification, read our guide to AES-GCM encryption.
Key Loss, Refreshes and Expiry in Practice
Developers building client-side encryption in JavaScript often obsess over millisecond encryption speeds. In day-to-day use, speed is almost never the bottleneck. The central usability trade-off is key loss.
When a derived key lives strictly in browser memory, closing a tab wipes it immediately. Even when web apps persist CryptoKey objects in IndexedDB, Open Security Architecture Pattern SP-039 warns that losing the browser profile or clearing site data permanently eliminates access to encrypted content, and describes secure key recovery that preserves a zero-knowledge model as an unresolved research problem.
What Happens to the Key and the Channel After Common Events
| Event | Effect on the key | Can the channel be recovered? |
|---|---|---|
| Page refresh in the same browser | In-memory key is lost | Yes, by rejoining with the link and access key while the channel is live |
| Private browsing window closed | Memory and session storage discarded | Yes, by rejoining, if the channel is still live |
| Clearing site data | Any stored key removed | No; support cannot restore it |
| Switching to another device | Key not copied | Only by entering the access key again on the new device |
| Channel reaches 60 minutes | Ciphertext deleted server-side | No |
| BURN CHANNEL pressed | Immediate wipe on the server | No |
Deliberate Ephemerality Versus Accidental Data Loss
Teams used to cloud accounts often expect a "Forgot Password" link to bail them out. With no accounts and no server-side key backup, support can't restore lost plaintext. In response to lawful process, the operator can provide only encrypted blobs that expire on a one-hour clock, since it holds no plaintext, keys, or message history. That refusal to offer recovery is a privacy feature, yet it changes how users must treat browser tabs.
It helps to draw a sharp line between accidental loss and deliberate expiry:
- Recoverable slips: Refreshing a page, closing a private window, or moving from a laptop to a phone wipes local memory, not the active relay channel. As long as the channel is still live, paste the channel link and access key again to re-derive the AES key and resume.
- Irreversible expiry: Each channel expires 60 minutes after it is created, and then the channel and all its ciphertext are deleted server-side. Pressing BURN CHANNEL triggers an immediate wipe on the server. Neither action can be undone, and no later export is possible.
If you're working inside a long-lived enterprise environment where key rotation, escrow, and multi-device persistence are mandatory, browser-only memory keys aren't the right fit. Exploring how PushOps simplifies encryption security offers a useful look at structured key lifecycle management for persistent teams. For ephemeral browser sessions, treat the 60-minute lifetime as fixed, copy any notes or files you need locally before the clock runs out, and never rely on your browser to remember a session key for you.
Browser Limits and a Pre-Trust Checklist
Now ask the question most browser cryptography articles skip: what happens if the website serves altered JavaScript after you've already decided to trust it?
Every time you open a web app, your browser downloads fresh executable code from the server. Even when the derived key stays in browser memory and never leaves your device, client-side encryption in JavaScript cannot protect your plaintext or your key from malicious code running inside the same origin. As the OWASP Web Frontend Security Cheat Sheet explains, browser cryptography offers no shield against hostile scripts executing inside the application, and even a non-extractable CryptoKey won't stop an injected script from calling decrypt on your messages and exfiltrating the plaintext.
Application-integrity boundary: Zero-knowledge server storage protects ciphertext at rest if a database is breached or subpoenaed, but it cannot by itself guarantee that a future browser session receives unaltered encryption code.
That distinction matters for journalists protecting sources, lawyers handling privileged discussions, and healthcare teams coordinating sensitive patient cases. If someone assumes "the key never leaves the browser" means the session is automatically tamper-proof, they miss the delivery path entirely. Our design goal at Ciphar, a zero-knowledge encrypted chat app that runs entirely in the browser, is that if our database is leaked, stolen, subpoenaed, or exfiltrated by a state actor, the attacker still has nothing useful. Securing the delivery path requires a second layer of frontend defenses, each with clear limits.

Code-Delivery Mitigations and Their Honest Limits
- Strict Content Security Policy (CSP): Restricts which domains can load scripts and where the page can send network requests. Limit: A compromised server operator who controls the HTTP headers can relax the CSP on the next page load.
- No unsafe inline scripts and no
eval: Eliminates common cross-site scripting (XSS) sinks that attackers use to inject rogue code into a live session. Limit: Prevents third-party injection bugs, not malicious changes merged into the primary script bundle. - Pinned dependencies: Locks every third-party library to an exact, verified version instead of pulling floating updates. Limit: Stops upstream supply-chain drift, but requires disciplined auditing whenever dependencies are updated.
- Subresource Integrity (SRI): Forces the browser to verify a cryptographic hash of externally hosted script files before running them. Limit: Protects external CDN assets against tampering, yet doesn't protect the root HTML document that declares the hashes.
- Reproducible builds: Allows independent reviewers to compile public source code and confirm it produces byte-for-byte identical JavaScript to what the server ships. Limit: Only catches server-side tampering if someone checks the live bundle against the build output.
- Independent security review and public release notes: External audits uncover protocol flaws early, and transparent changelogs flag every modification to encryption files. Limit: An audit verifies a snapshot in time, not an unreviewed deployment pushed two weeks later.
Security across the full stack also extends past the browser tab to the endpoints and hardware people use every day, especially in clinical and regulated environments where teams evaluate data protection for connected devices alongside web application controls.
A Five-Minute Pre-Trust Checklist
Before trusting any browser-based encrypted tool with sensitive material, run through these six checks in your browser's developer tools and public documentation:
- Verify HTTPS and the certificate: Confirm the page loads strictly over HTTPS with a valid TLS certificate and no mixed-content warnings.
- Inspect the CSP header: Open the Network tab, click the main document request, and confirm a strict Content Security Policy is present with no
unsafe-inlineorunsafe-evaldirectives. - Check code transparency: Confirm the encryption code is open for public audit or backed by a published independent security review.
- Verify the cipher and metadata binding: Confirm the application uses AES-256-GCM with a fresh random IV per message and binds protocol metadata as AAD.
- Review published derivation settings: Check that PBKDF2 parameters are documented openly and weighed against current guidance, such as 100,000 iterations as documented for browser responsiveness compared against roughly 600,000 iterations in current OWASP guidance.
- Separate the key exchange: Confirm you're sharing the access key over a separate trusted channel, never inside the same unencrypted email or ticket that carries the session link.
Once you've checked those six points, run a dry test with a low-stakes message before sharing anything confidential. Watch how key entry, decryption, the 60-minute expiry clock, and the burn control behave in practice so there are no surprises when privacy really counts.
If you want to inspect and test browser-native AES-256-GCM encryption without installing software or creating an account, you can spin up a temporary one-hour channel in seconds on Ciphar. Every message, file, and voice frame is encrypted locally in your browser with keys that never touch our relay, and you can burn the channel at any moment or let it self-destruct automatically at 60 minutes. Try a quick test session with a colleague to see how zero-knowledge client-side encryption behaves end to end.



