iOS best practices - storage sensitive data
Local data storage#
When building iOS applications, developers always deal with sensitive data (e.g., passwords, secret keys, personally identifiable information (PII)). Thus, you need to ensure that sensitive data is only stored with appropriate protection. For instance:
- Authentication tokens (access token, refresh token) or credentials should not be saved in UserDefaults without any encryption.
- Avoid storing API Keys, Encryption Keys in
.plistfiles, hardcoded asStringin code.
Instead, you must store sensitive data by using Keychain, which stores data inside the Secure Enclave. Or in advance, you can use the envelop encryption approach and store the "root key" in Keychain.
When working with Keychain, you should use
kSecAttrAccessibleWhenPasscodeSetThisDeviceOnlywithSecAccessControlCreateWithFlagsso that the data in the Keychain can only be accessed when the device is unlocked
Logging#
Developers always use logs to debug or track the data flows. Consequently, sensitive data could be shown in the log files. You should check predefined and built-in log functions (e.g., NSLog, assert, print) or custom functions (e.g., Logging, Logger, Logfile) and remove it from the codebase.
If you still want to use log, consider allowing it for DEBUG or development modes only.
#if DEBUG NSLog(...)#endifThird-party services#
Recently, I integrates Firebase, Braze, and Appsflyer into mobile applications. These tools provide tracking services to monitor users’ behaviors, showing banner advertisements, etc. You should determine whether sensitive data is shared with third parties or not. So I recommend:
- Do check or review their code, requested permissions, and known vulnerabilities.
- Data that is sent to third-party services should be anonymized to prevent exposure of PII.
- Encrypt data (e.g., email) before sending it to third-party services if it’s required.
- Do check all API requests to external services for sensitive information (e.g., using Proxyman to intercept traffic between the client and service, then sniff the traffic).