Apply Secure Mobile Storage
Store sensitive mobile app data using platform-provided secure enclaves (iOS Keychain, Android Keystore) and encrypted databases — never in plaintext files, SharedPreferences, or UserDefaults.
Why This Is Best Practice
Adopted by: OWASP Mobile Top 10 2024 M9 (Insecure Data Storage) is a top mobile vulnerability. OWASP MASVS (Mobile Application Security Verification Standard) MSTG-STORAGE-1 through MSTG-STORAGE-14 specify secure storage requirements. Apple's iOS Security Guide mandates Keychain for sensitive data. Google's Android Security Best Practices require Keystore for cryptographic keys. PCI DSS v4.0 Requirement 3 and HIPAA both mandate encryption for stored sensitive data on mobile.
Impact: The OWASP Mobile Top 10 consistently ranks insecure data storage as a critical finding across mobile app security assessments. Common findings: app tokens stored in plaintext SQLite databases (accessible after physical device access or backup extraction), encryption keys stored in UserDefaults/SharedPreferences (readable without root on unencrypted devices), and PII cached in unencrypted temporary files. Physical device access, iCloud/adb backup extraction, and root/jailbreak all enable reading non-secure storage.
Why best: Encrypting files with a key stored in the same location as the encrypted data is the common alternative — it's equivalent to locking a safe and taping the combination to the door. Platform-provided secure hardware enclaves (Secure Enclave on iOS, TEE/StrongBox on Android) store keys in hardware that cannot be extracted even with root access.
Sources: OWASP Mobile Top 10 2024 M9; OWASP MASVS MSTG-STORAGE; Apple iOS Security Guide; Android Security Best Practices; CWE-312
Steps
iOS — use Keychain for all secrets and tokens:
import Security
func saveToKeychain(key: String, data: Data) -> Bool {
let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrAccount as String: key,
kSecValueData as String: data,
kSecAttrAccessible as String: kSecAttrAccessibleWhenUnlockedThisDeviceOnly
// Never use kSecAttrAccessibleAlways — accessible even when locked
]
SecItemDelete(query as CFDictionary) // remove existing
return SecItemAdd(query as CFDictionary, nil) == errSecSuccess
}
func loadFromKeychain(key: String) -> Data? {
let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrAccount as String: key,
kSecReturnData as String: true
]
var result: AnyObject?
SecItemCopyMatching(query as CFDictionary, &result)
return result as? Data
}
Use kSecAttrAccessibleWhenUnlockedThisDeviceOnly for most secrets — requires device unlock, non-exportable.
Android — use EncryptedSharedPreferences and Android Keystore:
import androidx.security.crypto.EncryptedSharedPreferences
import androidx.security.crypto.MasterKey
// Create master key backed by Android Keystore
val masterKey = MasterKey.Builder(context)
.setKeyScheme(MasterKey.KeyScheme.AES256_GCM)
.build()
// EncryptedSharedPreferences — transparently encrypted
val securePrefs = EncryptedSharedPreferences.create(
context,
"secure_prefs",
masterKey,
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
)
// Use like normal SharedPreferences
securePrefs.edit().putString("auth_token", token).apply()
val token = securePrefs.getString("auth_token", null)
Never use these for sensitive data:
| Storage mechanism |
Why it's insecure |
UserDefaults (iOS) |
Plaintext plist, readable from backup |
SharedPreferences without encryption |
Plaintext XML, readable with root |
| SQLite without encryption |
Readable from backup or filesystem |
| Files in Documents/ (iOS) |
Included in iCloud backup by default |
| External storage (Android) |
World-readable before Android 10 |
| Log output |
Readable from ADB on debug builds |
Use SQLCipher for encrypted databases:
// Android — SQLCipher
import net.sqlcipher.database.SQLiteDatabase
SQLiteDatabase.loadLibs(context)
val db = SQLiteDatabase.openOrCreateDatabase(dbPath, getDatabaseKey(), null)
// getDatabaseKey() should return key from Android Keystore
// iOS — SQLCipher (via Swift Package Manager)
let db = try Connection(dbPath)
try db.key(getKeyFromKeychain())
Exclude sensitive files from backups:
// iOS — mark file as excluded from iCloud backup
var url = URL(fileURLWithPath: sensitiveFilePath)
var values = URLResourceValues()
values.isExcludedFromBackup = true
try url.setResourceValues(values)
<!-- Android — exclude files from Auto Backup (AndroidManifest.xml) -->
<application
android:allowBackup="true"
android:fullBackupContent="@xml/backup_rules">
<!-- res/xml/backup_rules.xml -->
<full-backup-content>
<exclude domain="database" path="sensitive.db"/>
<exclude domain="sharedpref" path="secure_prefs.xml"/>
</full-backup-content>
Clear sensitive data from memory when no longer needed:
// Overwrite sensitive strings in memory
var password = getPassword()
defer {
password = String(repeating: "\0", count: password.count)
}
authenticate(with: password)
Rules
- Keys that decrypt sensitive data must live in the Keychain/Keystore — never in the database or alongside the data.
- Use
kSecAttrAccessibleWhenUnlockedThisDeviceOnly / setUserAuthenticationRequired(true) for the highest-value secrets.
- On Android,
StrongBox-backed keys are stored in dedicated hardware security module — use for the most sensitive keys on supported devices.
- Debug builds often log sensitive data — use
#if DEBUG / BuildConfig.DEBUG guards to prevent logging tokens in release builds.
Common Mistakes
- Storing JWT access tokens in UserDefaults/SharedPreferences — the most common finding in mobile security assessments.
- Encrypting a database with a key derived only from the app's bundle ID — predictable key defeats encryption.
- Using the same Keychain item across all apps with the same bundle prefix — set explicit
kSecAttrAccessGroup to restrict access.
- Logging sensitive data to NSLog/Log.d without stripping in release — crashes and analytics platforms may capture logs.
1---2name: apply-secure-mobile-storage3description: Use when storing sensitive data on a mobile device — credentials, tokens, PII, health data, financial data, or any data that should not be accessible to other apps or readable from device backups.4source: 'OWASP Mobile Top 10 2024 M9 (owasp.org/www-project-mobile-top-10/); OWASP Mobile Application Security Verification Standard (MASVS); CWE-312; Apple Keychain documentation; Android Keystore documentation'5tags: [security, owasp, mobile, secure-storage, keychain, keystore, ios, android]6metadata:7 source: https://skillmd.com/skills/jeffreytse/apply-secure-mobile-storage8---910# Apply Secure Mobile Storage1112Store sensitive mobile app data using platform-provided secure enclaves (iOS Keychain, Android Keystore) and encrypted databases — never in plaintext files, SharedPreferences, or UserDefaults.1314## Why This Is Best Practice1516**Adopted by:** OWASP Mobile Top 10 2024 M9 (Insecure Data Storage) is a top mobile vulnerability. OWASP MASVS (Mobile Application Security Verification Standard) MSTG-STORAGE-1 through MSTG-STORAGE-14 specify secure storage requirements. Apple's iOS Security Guide mandates Keychain for sensitive data. Google's Android Security Best Practices require Keystore for cryptographic keys. PCI DSS v4.0 Requirement 3 and HIPAA both mandate encryption for stored sensitive data on mobile.17**Impact:** The OWASP Mobile Top 10 consistently ranks insecure data storage as a critical finding across mobile app security assessments. Common findings: app tokens stored in plaintext SQLite databases (accessible after physical device access or backup extraction), encryption keys stored in UserDefaults/SharedPreferences (readable without root on unencrypted devices), and PII cached in unencrypted temporary files. Physical device access, iCloud/adb backup extraction, and root/jailbreak all enable reading non-secure storage.18**Why best:** Encrypting files with a key stored in the same location as the encrypted data is the common alternative — it's equivalent to locking a safe and taping the combination to the door. Platform-provided secure hardware enclaves (Secure Enclave on iOS, TEE/StrongBox on Android) store keys in hardware that cannot be extracted even with root access.1920Sources: OWASP Mobile Top 10 2024 M9; OWASP MASVS MSTG-STORAGE; Apple iOS Security Guide; Android Security Best Practices; CWE-3122122## Steps23241. **iOS — use Keychain for all secrets and tokens**:2526 ```swift27 import Security2829 func saveToKeychain(key: String, data: Data) -> Bool {30 let query: [String: Any] = [31 kSecClass as String: kSecClassGenericPassword,32 kSecAttrAccount as String: key,33 kSecValueData as String: data,34 kSecAttrAccessible as String: kSecAttrAccessibleWhenUnlockedThisDeviceOnly35 // Never use kSecAttrAccessibleAlways — accessible even when locked36 ]37 SecItemDelete(query as CFDictionary) // remove existing38 return SecItemAdd(query as CFDictionary, nil) == errSecSuccess39 }4041 func loadFromKeychain(key: String) -> Data? {42 let query: [String: Any] = [43 kSecClass as String: kSecClassGenericPassword,44 kSecAttrAccount as String: key,45 kSecReturnData as String: true46 ]47 var result: AnyObject?48 SecItemCopyMatching(query as CFDictionary, &result)49 return result as? Data50 }51 ```5253 Use `kSecAttrAccessibleWhenUnlockedThisDeviceOnly` for most secrets — requires device unlock, non-exportable.54552. **Android — use EncryptedSharedPreferences and Android Keystore**:5657 ```kotlin58 import androidx.security.crypto.EncryptedSharedPreferences59 import androidx.security.crypto.MasterKey6061 // Create master key backed by Android Keystore62 val masterKey = MasterKey.Builder(context)63 .setKeyScheme(MasterKey.KeyScheme.AES256_GCM)64 .build()6566 // EncryptedSharedPreferences — transparently encrypted67 val securePrefs = EncryptedSharedPreferences.create(68 context,69 "secure_prefs",70 masterKey,71 EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,72 EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM73 )7475 // Use like normal SharedPreferences76 securePrefs.edit().putString("auth_token", token).apply()77 val token = securePrefs.getString("auth_token", null)78 ```79803. **Never use these for sensitive data**:8182 | Storage mechanism | Why it's insecure |83 |---|---|84 | `UserDefaults` (iOS) | Plaintext plist, readable from backup |85 | `SharedPreferences` without encryption | Plaintext XML, readable with root |86 | SQLite without encryption | Readable from backup or filesystem |87 | Files in Documents/ (iOS) | Included in iCloud backup by default |88 | External storage (Android) | World-readable before Android 10 |89 | Log output | Readable from ADB on debug builds |90914. **Use SQLCipher for encrypted databases**:9293 ```kotlin94 // Android — SQLCipher95 import net.sqlcipher.database.SQLiteDatabase9697 SQLiteDatabase.loadLibs(context)98 val db = SQLiteDatabase.openOrCreateDatabase(dbPath, getDatabaseKey(), null)99 // getDatabaseKey() should return key from Android Keystore100101 // iOS — SQLCipher (via Swift Package Manager)102 let db = try Connection(dbPath)103 try db.key(getKeyFromKeychain())104 ```1051065. **Exclude sensitive files from backups**:107108 ```swift109 // iOS — mark file as excluded from iCloud backup110 var url = URL(fileURLWithPath: sensitiveFilePath)111 var values = URLResourceValues()112 values.isExcludedFromBackup = true113 try url.setResourceValues(values)114 ```115116 ```xml117 <!-- Android — exclude files from Auto Backup (AndroidManifest.xml) -->118 <application119 android:allowBackup="true"120 android:fullBackupContent="@xml/backup_rules">121122 <!-- res/xml/backup_rules.xml -->123 <full-backup-content>124 <exclude domain="database" path="sensitive.db"/>125 <exclude domain="sharedpref" path="secure_prefs.xml"/>126 </full-backup-content>127 ```1281296. **Clear sensitive data from memory when no longer needed**:130131 ```swift132 // Overwrite sensitive strings in memory133 var password = getPassword()134 defer {135 password = String(repeating: "\0", count: password.count)136 }137 authenticate(with: password)138 ```139140## Rules141142- Keys that decrypt sensitive data must live in the Keychain/Keystore — never in the database or alongside the data.143- Use `kSecAttrAccessibleWhenUnlockedThisDeviceOnly` / `setUserAuthenticationRequired(true)` for the highest-value secrets.144- On Android, `StrongBox`-backed keys are stored in dedicated hardware security module — use for the most sensitive keys on supported devices.145- Debug builds often log sensitive data — use `#if DEBUG` / `BuildConfig.DEBUG` guards to prevent logging tokens in release builds.146147## Common Mistakes148149- **Storing JWT access tokens in UserDefaults/SharedPreferences** — the most common finding in mobile security assessments.150- **Encrypting a database with a key derived only from the app's bundle ID** — predictable key defeats encryption.151- **Using the same Keychain item across all apps with the same bundle prefix** — set explicit `kSecAttrAccessGroup` to restrict access.152- **Logging sensitive data to NSLog/Log.d without stripping in release** — crashes and analytics platforms may capture logs.