Securing Secrets in Client Apps: A Sherlock Investigation
Client-side applications (mobile, web, desktop) are inherently untrusted environments. Users control the runtime, and attackers can reverse-engineer, debug, or hook into your app. Storing "secrets" (API keys, tokens, signing keys) here is risky, but sometimes unavoidable (e.g., offline-first apps, P2P features). The golden rule: Minimize, isolate, and rotate. Never hardcode or store long-lived master secrets.
I'll break this down by your query topics: envelope encryption, keychains, rotation, and compromise playbook. This is a practical blueprint, with code snippets in Swift (iOS), Kotlin (Android), and JS (web/React Native).
1. Envelope Encryption: Layered Protection for Data at Rest
Directly encrypting with a master key exposes it on compromise. Envelope encryption uses:
Data Encryption Key (DEK): Symmetric key (e.g., AES-256-GCM) for the actual secret/data. Generated per-item or per-session.
Key Encryption Key (KEK): Stronger, managed key (from keychain) that encrypts the DEK.
Why in clients? DEKs are short-lived/ephemeral; KEKs stay in secure hardware.
Implementation Example
iOS (Swift + CryptoKit)
swift
import CryptoKit
import Security // For Keychain
func encryptSecret(plaintext: String, kek: SymmetricKey) -> (ciphertext: Data, encryptedDEK: Data)? {
let dek = SymmetricKey(size: .bits256)
let sealedData = try? AES.GCM.seal(plaintext.data(using: .utf8)!, using: dek)
let encryptedDEK = try? AES.GCM.seal(dek.withUnsafeBytes { Data($0) }, using: kek)
return (sealedData?.combined ?? Data(), encryptedDEK?.combined ?? Data())
}
func decryptSecret(ciphertext: Data, encryptedDEK: Data, kek: SymmetricKey) -> String? {
// Extract nonce, tag, ciphertext from combined
guard let dekData = AES.GCM.open(encryptedDEK, using: kek) else { return nil }
let dek = SymmetricKey(data: dekData)
// Similar extraction for sealedData...
return String(data: plaintextData, encoding: .utf8)
}
// Store KEK in Keychain (see below)
Android (Kotlin + Jetpack Security)
Use EncryptedSharedPreferences or Jetpack Security libs—they handle envelope under the hood.
Web/JS (Web Crypto API)
javascript
async function envelopeEncrypt(plaintext, kek) {
const dek = await crypto.subtle.generateKey({ name: 'AES-GCM', length: 256 }, true, ['encrypt']);
const iv = crypto.getRandomValues(new Uint8Array(12));
const encryptedData = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, dek, new TextEncoder().encode(plaintext));
const encryptedDek = await crypto.subtle.encrypt({ name: 'RSA-OAEP' }, kek, await crypto.subtle.exportKey('raw', dek)); // KEK as RSA
return { ciphertext: new Uint8Array(encryptedData), encryptedDek: new Uint8Array(encryptedDek), iv };
}
Pro Tip: Derive KEKs from device-bound factors (e.g., Secure Enclave on iOS, TEE on Android).
2. Keychains: Hardware-Backed Secure Storage
Don't use localStorage, SharedPreferences, or files—use platform keychains for root-of-trust.
Platform
API
Features
iOS
SecKeychain / Security framework
Secure Enclave, biometric gating, app-scoped.
Android
KeyStore / Jetpack Security
StrongBox (TEE), MasterKey for auto-rotation.
Web
Web Crypto API + IndexedDB (with caveats)
Ephemeral; persist encrypted blobs.
Desktop
keytar (Node), Windows Credential Manager, macOS Keychain
Cross-app isolation.
React Native/Flutter
react-native-keychain, flutter_secure_storage
Abstracts platforms.
iOS Keychain Example
swift
// Store KEK
let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrAccount as String: "myAppKEK",
kSecValueData as String: kek.withUnsafeBytes { Data($0) },
kSecAttrAccessible as String: kSecAttrAccessibleWhenUnlockedThisDeviceOnly
]
SecItemDelete(query as CFDictionary) // Idempotent
SecItemAdd(query as CFDictionary, nil)
// Retrieve
var result: AnyObject?
SecItemCopyMatching(query as CFDictionary, &result)
let retrievedKEK = SymmetricKey(data: result as! Data)
Security Notes:
iOS: Use whenUnlockedThisDeviceOnly + biometric auth.
Android: setUserAuthenticationRequired(true) for biometrics.
Limitation: Keychains survive app uninstalls (iOS) or can be extracted with root/jailbreak.
3. Rotation: Limit Blast Radius
Rotate secrets proactively (e.g., 90-day TTL) and reactively (post-compromise).
Strategies
Short-lived DEKs: Generate per-session, derive from KEK + nonce.
Automated Rotation:
App fetches rotation signal from server (e.g., via signed manifest).
Generate new DEK/KEK pair.
Re-encrypt all data with new DEK.
Update server mappings (e.g., upload new pubkey for hybrid crypto).
Versioned Envelopes: Store (version, encryptedDEK, ciphertext). On decrypt, fallback to older KEKs.
Rotation Flow (Pseudo)
code
1. Check server for rotation epoch > local_epoch
2. Fetch new_KEK_wrapped_in_old_KEK
3. Unwrap → new_KEK
4. Re-encrypt all local secrets
5. Update keychain, bump local_epoch
Tools: Firebase Remote Config for signals, or self-hosted /v1/rotate endpoint with JWT auth.