Hmm, the user is asking about a comprehensive security strategy for handling secrets in client applications, specifically covering envelope encryption, keychains, key rotation, and compromise playbooks. This is a technical but practical security question, likely from a developer or security engineer designing a system.
I should structure this as a clear, actionable guide rather than just theory. The user probably wants implementation details and best practices. I'll break it down into the four requested areas, but also emphasize how they interconnect—like how envelope encryption ties into key rotation and keychains.
The response should balance depth with readability, avoiding fluff. Since this is security-critical, I'll include concrete examples (e.g., AWS KMS vs. Tink) and warnings about common pitfalls. The compromise playbook is especially important—it's often overlooked in design phases but critical during incidents.
I should also hint at trade-offs: e.g., key rotation vs. offline usability, or hardware-backed keychains vs. cost. The user might not have considered these tensions. Finally, I'll summarize with a layered approach diagram to tie it all together visually.
Excellent topic. Here is a comprehensive guide to managing secrets in client applications, structured around your four pillars: Envelope Encryption, Keychains, Rotation, and the Compromise Playbook.
This is a defense-in-depth strategy. No single technique is sufficient; they work together.
1. Envelope Encryption (The Core Data Protection Model)
Goal: Protect data at rest (in local storage, databases, caches) even if the device is compromised.
How it works:
- Data Encryption Key (DEK): A unique, strong symmetric key (e.g., AES-256-GCM) generated per user or per data item. This key encrypts the actual sensitive data.
- Key Encryption Key (KEK): A master key that encrypts/decrypts the DEK. The KEK is never stored alongside the encrypted data.
- Process:
- Encrypt:
EncryptedData = AES(DEK, Plaintext)
- Envelope:
EncryptedDEK = RSA_OAEP(KEK, DEK) or Wrap(KEK, DEK) (using a Key Management Service).
- Store: Persist
{ EncryptedDEK, EncryptedData, IV/Nonce, AuthTag }.
- Decrypt: Retrieve envelope → unwrap DEK using KEK → decrypt data.
Why this is superior to simple symmetric encryption:
- KEK Separation: The KEK can be stored in a hardware-backed, access-controlled location (see Keychains below). An attacker who exfiltrates the app's local database gets only
EncryptedDEK and EncryptedData—useless without the KEK.
- Easy DEK Rotation: To rotate a DEK, generate a new DEK, re-encrypt the data, and store the new
EncryptedDEK. You don't need to re-encrypt all historical data with a new KEK.
- Granular Access: Different DEKs for different data types (e.g., payment info vs. health records).
Implementation Choices for KEK:
- Mobile/Desktop: Use the OS Keychain/Keystore (iOS Keychain, Android Keystore, Windows DPAPI, macOS Keychain/Linux libsecret). The KEK is generated and never leaves the secure enclave/TEE if possible.
- Web/SPA: Impossible to do perfectly. Best options:
- Hardware-backed (WebAuthn/Passkeys): Derive a key from a user's authenticator (security key, TPM). Most robust but requires user interaction.
- Browser Crypto API (SubtleCrypto): Generate a key tied to the browser's origin. Vulnerable to XSS and session theft.
- Never store secrets long-term in a pure web client. Use short-lived sessions with server-side storage.
2. Keychains & Secure Storage (The KEK Vault)
Goal: Securely store and use the KEK (and other keys/secrets) leveraging hardware-backed security where available.
Platform-Specific Vaults:
| Platform | Facility | Key Properties |
|---|
| iOS/macOS | Keychain Services | Items can be bound to device lock (kSecAttrAccessibleWhenUnlocked). Uses Secure Enclave for key ops when possible. |
| Android | Keystore System | Keys can be hardware-backed (TEE/StrongBox). Set setUserAuthenticationRequired(true) for biometric/pin gating. |
| Windows | Windows Hello / DPAPI | Keys tied to user credentials or TPM. |
| Linux | libsecret / GPG Agent | Less standardized; often relies on user login password. |
Critical Configuration:
- Access Control: Require user authentication (biometric or passcode) for key use, not just app launch. Prevents malware from using the key when the user is away.
- Invalidation on Logout: On explicit user logout, delete the KEK from the keychain. This renders all locally stored
EncryptedDEK blobs permanently inaccessible.
- Biometric as Auth, Not Key: Never store the biometric template. Use biometric auth to unlock the KEK stored in the keychain.
3. Key Rotation (Proactive Compromise Mitigation)
Goal: Limit the "blast radius" of a key compromise by regularly replacing keys.
What to Rotate & When:
- Data Encryption Keys (DEKs):
- Frequency: Can be high (per-session, per-item). Low cost due to envelope encryption.
- Trigger: New data creation. Re-encrypt data with a new DEK and store the new
EncryptedDEK.
- Benefit: Limits exposure if a single DEK is leaked.
- Key Encryption Keys (KEKs):
- Frequency: Much lower (e.g., annually, on app major update, on user re-auth).
- Process: The Rotation Playbook (see below). Requires:
- Old KEK (
KEK_old) still present in keychain.
- For each stored
{ EncryptedDEK_old, EncryptedData }:
DEK = Decrypt(KEK_old, EncryptedDEK_old)
EncryptedDEK_new = Encrypt(KEK_new, DEK)
- Update storage with
EncryptedDEK_new.
- After all data is re-wrapped, delete
KEK_old.
- Challenge: Requires access to all data and both keys. Must be done while user is active and online if relying on a server-backed KMS.
Rotation Triggers (Beyond Schedule):
- User Re-Authentication: Rotate KEK on strong re-auth (password change, new device registration).
- Platform Rotation: If underlying hardware/OS key is deprecated (e.g., Android Keymaster Hub upgrade).
4. Compromise Playbook (Incident Response)
Goal: Have a clear, tested, automated (where possible) response plan for key compromise scenarios.
Scenario 1: Client Device Compromise (Malware/Theft)
- Detection: Unusual API calls, location anomalies, user report.
- Actions:
- Server-Side: Invalidate all user sessions and refresh tokens. Force re-authentication with strong credential.
- Client-Side: On next app launch, delete all locally stored secrets (KEK from keychain, encrypted blobs). This is the nuclear option but necessary.
- Recovery: User must re-sync data from server (which is encrypted with server-side keys, not the compromised KEK). Requires server to have original, authoritative copy of data.
Scenario 2: DEK Compromise (Exfiltration of Encrypted Blob)
- Risk: Low if KEK is secure. The blob is useless.
- Action: Rotate the DEK (re-wrap it with the same KEK). This is a routine operation.
Scenario 3: KEK Compromise (The Worst Case)
- How? Physical device access + keychain extraction exploit, compromised root cert, or a bug in the keystore implementation.
- Detection: Extremely difficult. Often discovered via external disclosure or forensic analysis.
- Actions:
- Immediate: Global key rotation. Generate a new
KEK_new. Re-wrap every DEK for every user on the server (if you have access) or force every client to perform rotation on next sync.
- Invalidate: Invalidate all active sessions and local keychains. Treat as Scenario 1.
- Forensics: Analyze how the KEK was extracted to patch the vulnerability (e.g., specific OS version, jailbreak/root).
- Communicate: If user data could have been decrypted, you may have a breach notification obligation.
Scenario 4: Server-Side Key Management Service (KMS) Compromise
- Action: If using a cloud KMS (AWS KMS, GCP KMS, Azure Key Vault), rely on the provider's isolation and audit logs. You can rotate the customer-managed key (CMK) in the KMS. The process of re-wrapping all DEKs may be automated server-side.
Architecture Summary & Best Practices
graph TD
A[User Data Plaintext] --> B[Encrypt with DEK_A];
B --> C[EncryptedDEK_A = Wrap(KEK, DEK_A)];
C --> D[Store {EncryptedDEK_A, Ciphertext}];
D --> E{Decrypt Request};
E --> F[Get KEK from Secure Hardware Keychain <br/> (Biometric/Pin Gated)];
F --> G[Unwrap DEK_A];
G --> H[Decrypt Ciphertext with DEK_A];
I[Compromise Response] --> J[Invalidate KEK <br/> Delete from Keychain];
J --> K[Force Full Re-sync <br/> from Server];
K --> L[Server Re-wraps DEKs <br/> with new KEK];
M[Routine Rotation] --> N[Generate New DEK per item <br/> Re-wrapping trivial];
N --> O[Periodic KEK Rotation <br/> Re-wrap all stored DEKs];
Golden Rules:
- Assume the device is hostile. Design so that local data theft is non-trivial.
- Never roll your own crypto. Use platform keystores and vetted libraries (Tink, libsodium).
- Server is the source of truth. The client is a cache that must be able to be wiped and rebuilt from the server, which stores data encrypted with its own robust keys.
- Test your playbook. Simulate a "lost device" scenario. Can you remotely logout all sessions? Does the app correctly wipe local state?
- Audit and Monitor: Log key usage and authentication events (respecting privacy). Anomalies in key access patterns are a key compromise signal.
- Threat Model: Define yours. Is your threat a casual thief, a state actor with a zero-day, or a malicious insider? Your controls, especially rotation frequency and hardware reliance, should match.
By implementing these four pillars as an interconnected system, you move from simple "obfuscation" to a cryptographically sound, incident-resilient secrets management strategy for your client applications.