The user wants to know about handling secrets in client-side applications (mobile apps, desktop apps, single-page apps).
The request covers four specific areas:
- Envelope Encryption: What it is and how it applies here.
- Keychains/Storage: Where to store these secrets locally.
- Rotation: How to update keys/secrets.
- Compromise Playbook: What to do when things go wrong.
Target Audience/Context: This is a security-focused engineering question. The user likely understands basic cryptography but needs a practical architecture for client-side security. The crucial constraint here is "Client Apps." This is the hostile territory. You cannot trust the client.
Initial Brainstorming & Key Principles:
- The Golden Rule: You cannot hide secrets in a client app perfectly. If the app has the key, a determined attacker can get the key (reverse engineering, memory dumps, MITM).
- Goal: Raise the bar. Make it expensive enough to deter attackers, not impossible (because it's impossible).
- Architecture: Delegation is key. Use tokens (short-lived) instead of master keys.
- Envelope Encryption: This is usually for data at rest on the device. It involves a Data Key (DEK) and a Key Encryption Key (KEK). Where does the KEK come from? The OS (Keychain/Keystore) or a backend service.
Section 1: Envelope Encryption (The "How")
- Concept: Encrypt the data with a random key (DEK). Encrypt the DEK with a master key (KEK).
- Client Context:
- Scenario: Storing sensitive user data locally (e.g., health data, cached financial docs).
- DEK: Generated randomly per file/record.
- KEK: Stored in the secure enclave/Keychain (biometrics) OR derived from a user passphrase.
- Flow: App needs data -> Get KEK from Keychain -> Decrypt DEK -> Decrypt Data.
Section 2: Keychains & Storage (The "Where")
- iOS: Keychain Services (Secure Enclave).
- Android: Android Keystore (TEE/StrongBox).
- Web (SPA): This is the hardest.
localStorage is plain text. IndexedDB is plain text. No "Keychain."
- Web workaround: Use Service Workers + memory, or just rely on short-lived HttpOnly cookies. Don't store long-term secrets on web clients.
- Desktop: OS specific (Windows DPAPI, macOS Keychain).
- Avoid: Hardcoded strings, SharedPrefs, Plist files.
Section 3: Rotation (The "When")
- Why? Limit blast radius.
- Strategies:
- Passive: Wait for user to log in, issue new token.
- Active: Backend forces re-auth.
- Envelope specific: Re-encrypting the DEK. If the KEK changes (e.g., user changes password), you must unwrap the DEK with the old KEK and wrap it with the new KEK.
Section 4: Compromise Playbook (The "Oh No")
- Detection: How do you know? (Anomaly detection on backend, seeing API abuse).
- Immediate: Revoke the specific leaked keys (if it's an API key).
- Harder: If it's the code (hardcoded logic keys), you need an OTA update (Over The Air) or remote config change.
- Hardest: If the user's device is compromised.
- Post-Mortem: Rotate everything.
Structuring the Response:
I will structure this logically, addressing each of the four points requested.
- Introduction: Acknowledge the hostile environment.
- 1. Envelope Encryption (Local Data at Rest): Explain the mechanism (DEK/KEK) specifically for local storage.
- 2. Keychains & Secure Storage: Platform-specific implementation (iOS/Android/Web).
- 3. Key Rotation: Strategies for both server-side keys (API keys) and user-specific keys.
- 4. Compromise Playbook: A step-by-step incident response plan.
Refining Content:
- Self-Correction on Envelope Encryption: I need to make sure I distinguish between encrypting secrets (like API keys) vs encrypting user data. You usually shouldn't store API keys using envelope encryption on the client; you should use the OS Keychain directly. Envelope encryption is best for bulk user data. However, if the prompt implies "Secrets" as "Data the user wants kept secret," then envelope is correct. If it implies "Third Party API keys embedded in the app," that's a different problem (don't do it).
- Clarification: I will assume "Secrets" covers both embedded application secrets (API keys) and user data.
- Crucial distinction: Web vs Mobile. I must highlight that Web has no secure enclave.
Drafting the Content (Mental Draft):
- Envelope: Generate key. Encrypt data. Store key in Keychain.
- Keychain: Use the hardware security module (Secure Enclave). Don't roll your own crypto.
- Rotation: Use short-lived tokens (JWTs/OAuth) so rotation happens automatically on refresh. For app-level secrets, use Remote Config.
- Playbook: Kill the key, check logs, force update app.
Final Polish: Ensure the tone is authoritative and security-focused. Use clear headings and bullet points. Emphasize that "Security by Obscurity" is not a valid strategy, but "Defense in Depth" is.
Let's write it out.
- Topic: Envelope Encryption.
- DEK (Data Encryption Key): AES-256-GCM. Stored with the data (encrypted).
- KEK (Key Encryption Key): Stored in Keychain/Keystore.
- Benefit: You change the password (KEK) without re-encrypting gigabytes of data.
- Topic: Keychains.
- iOS: Keychain.
- Android: Keystore.
- Web: DANGER. Do not store secrets. Use HttpOnly Cookies.
- Topic: Rotation.
- Online vs Offline rotation.
- App Secret rotation requires a backend "handshake."
- Topic: Compromise.
- If a hardcoded API key is stolen: You are in trouble because you can't revoke it without breaking all old app versions. Mitigation: Proxy through your backend.
- If a user token is stolen: Revoke refresh token.
Self-Correction: The user asked for "Secrets in client apps." I need to be very clear: Do not embed high-value secrets (like an AWS Secret Key or Stripe Secret Key) in a client app. Instead, use a "Backend for Frontend" (BFF) proxy. I must state this immediately. Envelope encryption protects data, not embedded static keys (effectively).
Okay, plan is solid. I will execute.
Dealing with secrets in client-side applications (mobile, desktop, SPA) is fundamentally different from server-side security. The cardinal rule is: The client environment is untrusted. You cannot perfectly hide a secret on a device you do not control.
However, you can raise the bar significantly to deter attackers. Here is the architectural blueprint for managing client secrets using Envelope Encryption, Keychain storage, Key Rotation, and a Compromise Playbook.
1. Envelope Encryption (The Architecture)
Envelope encryption is the standard pattern for encrypting data locally without requiring the user to type a password every time. It separates the data from the key used to encrypt it.
The Analogy: You put a letter (Data) in a safe (Encryption), lock it with a physical key (DEK), and then put that physical key into a master safe (KEK) located elsewhere.
The Components:
- DEK (Data Encryption Key): A symmetric key (e.g., AES-256-GCM) generated randomly on the device. It is used to encrypt the actual user data (tokens, PII, local DB).
- KEK (Key Encryption Key): The "Master Key." This is not stored in the application code. It is derived from the device's hardware security or stored in the OS Keychain.
The Flow (Write):
- Generate: App creates a random DEK.
- Encrypt Data: App encrypts the sensitive payload with the DEK.
- Wrap: App asks the System Keychain/Secure Enclave to encrypt the DEK using the KEK.
- Store: The encrypted data and the wrapped (encrypted) DEK are stored together in standard storage (SharedPreferences, UserDefaults, LocalStorage).
The Flow (Read):
- Retrieve: App fetches the wrapped DEK.
- Unwrap: App asks the System Keychain to decrypt the DEK (requires FaceID/TouchID or Device Passcode).
- Decrypt: App uses the decrypted DEK to decrypt the data.
Why do this?
If an attacker dumps the memory or steals the database file, they have the encrypted data and the wrapped DEK. But without access to the Keychain/Secure Enclave, they cannot unwrap the DEK, rendering the data useless.
2. Keychains & Secure Storage (The "Vault")
Never store keys in localstorage, plaintext files, or shared_prefs. Use the hardware-backed storage provided by the OS.
| Platform | Technology | Security Level |
|---|
| iOS | Keychain Services | Highest. Uses Secure Enclave (CPU-bound). |
| Android | Android Keystore | High. Uses TEE (Trusted Execution Environment) or StrongBox. |
| Web (SPA) | None (Truly) | Low. localStorage is accessible to scripts and users. |
| Desktop | DPAPI (Windows) / Keychain (Mac) | Medium/High. Tied to OS user login. |
Implementation Strategy:
- Biometric Gating: Configure the Keychain access to require User Presence (FaceID/Biometrics) before releasing the KEK.
- Key Invalidation: On iOS/Android, you can configure keys to be invalidated if the device passcode is removed or if biometrics are changed. This prevents an attacker from forcing their way into a stolen phone by disabling the lock screen.
The "Web" Exception:
On the Web, you have no secure storage. Do not store long-lived secrets. Use Short-Lived Tokens (JWT) in memory and rely on HttpOnly cookies for refresh capabilities. Implementing "envelope encryption" on the web usually means encrypting data with a key stored in localStorage, which provides zero security against a malicious script injection (XSS).
3. Rotation (The Lifecycle)
Secrets accumulate "dust." The longer a key exists, the higher the probability it has been leaked. Rotation limits the blast radius.
Types of Rotation:
-
App-Level Secret Rotation (Hardcoded keys):
- Example: An API key embedded in the app code to talk to your backend.
- Strategy: Decouple. Use a "Key ID" alongside the Key.
- Play: Backend accepts Key ID
v1 and v2. You push an app update using v2. Once adoption is high, you delete v1 on the backend. Old app versions simply stop working (force update).
- Advanced: Use Firebase Remote Config or similar services to inject keys remotely without an app store update.
-
User-Data Key Rotation (DEKs):
- Trigger: User changes password, or app detects a "suspicious" login.
- Strategy:
- Decrypt data with old DEK.
- Generate new DEK.
- Re-encrypt data.
- Securely delete old DEK.
- Note: This is computationally expensive. Only rotate if necessary.
4. Compromise Playbook (Incident Response)
What happens when you realize a client secret (like an embedded Google Maps API key or a backend secret) has been scraped and is being abused?
Phase 1: Identification & Triage
- Verify: Check your backend logs or API provider dashboard. Do you see massive spikes in usage from random IPs?
- Scope: Is this a hardcoded key in the binary? Or a specific user's access token?
Phase 2: Containment (Immediate)
- The "Kill Switch": If you architected your app to check a "Remote Config" variable on startup, flip that switch to disable the compromised feature or force a "Maintenance Mode" while you fix it.
- Rate Limiting: Implement aggressive rate limiting on the backend for that specific key/service. Tie limits to User IDs, not just IP addresses (since attackers use botnets).
- Revoke (If temporary breakage is acceptable): Delete the compromised key from the provider console.
Phase 3: Remediation (The Fix)
- Hotfix / Forced Update:
- Generate a new secret (Key B).
- Update the backend to accept Key B.
- Release a new binary (App Store/Play Store) containing Key B.
- Crucial: Configure the backend to reject the old Key A immediately after the update goes live.
- Note: Users who do not update will lose functionality.
Phase 4: Post-Mortem
- Root Cause: Why was the secret there? Can you move the logic to the backend (BFF pattern) so the secret never touches the device?
- Restriction: If the secret must stay on the client (e.g., Firebase), restrict its usage on the provider side:
- Bundle ID/Package Name restriction: Only allow requests coming from
com.mycompany.myapp.
- App Attestation (iOS) / Play Integrity (Android): Implement these APIs on your backend. They cryptographically verify that the request is coming from a genuine, unmodified binary of your app.
Summary of Best Practices
- Don't store secrets on the client if you can avoid it. Proxy requests through your backend (Backend-For-Frontend).
- Use the OS Keychain for anything stored locally (Envelope Encryption).
- Rotate embedded secrets regularly via remote config.
- Use App Attestation to prevent modified clients from using your secrets.