Course contentsShow
← Security
Lesson 1078 of 3,05222. Web Security - Client-Side and SPA SecurityFree lesson

Client-Side Encryption for Storage

Implementing encryption before storing sensitive data, key management challenges, and WebCrypto API usage patterns.

Client-Side Encryption for Storage

What you'll learn: How to encrypt sensitive data in the browser before storing it, protecting users even if storage is compromised.

Why Encrypt Client-Side Storage?

Even with localStorage, sessionStorage, and IndexedDB scoped by origin, an XSS attack can still read everything. Client-side encryption adds a crucial defense layer: even if an attacker extracts your stored data, they get encrypted gibberish without the key.

Think of it like storing valuables in a safe deposit box (browser storage) versus storing them in that same box but inside a locked safe (encryption). If someone breaks into the box, they still can't access your valuables.

Core Implementation Pattern

Encryption before storage:

  1. User provides or derives a key (password-based, session-specific, or from server)
  2. Use WebCrypto API to encrypt sensitive data
  3. Store only the encrypted ciphertext
  4. Decrypt on retrieval using the same key

Example flow (conceptual):

plaintext → WebCrypto.encrypt(key) → ciphertext → localStorage
localStorage → ciphertext → WebCrypto.decrypt(key) → plaintext

Key Management Challenges

This is the hard part. Where do you keep the encryption key?

  • Store the key in memory only: Secure but lost on page refresh
  • Derive from user password: Requires user to re-enter password
  • Request from server per session: Adds network dependency
  • Never store encryption keys alongside encrypted data: Defeats the purpose entirely

WebCrypto API Usage

The browser's crypto.subtle API provides cryptographically secure encryption primitives. You'll use methods like generateKey(), encrypt(), and decrypt() with algorithms such as AES-GCM. This avoids the security pitfalls of implementing your own crypto.

Key Takeaway: Client-side encryption protects stored data from XSS and storage compromise, but key management is the critical security challenge—the encryption is only as strong as how you handle the keys.