Data Protection API and Keychain
What you'll learn: How iOS encrypts data at rest using protection classes and securely stores credentials in the Keychain.
Understanding iOS Data Protection
iOS provides Data Protection API to encrypt files automatically using hardware-backed keys. When you save data, you assign it a protection class that determines when the data becomes accessible:
- Complete Protection (
NSFileProtectionComplete): Data accessible only when device is unlocked. Strongest protection. - Protected Unless Open (
NSFileProtectionCompleteUnlessOpen): Files can stay open even after lock, but new files require unlock. - Protected Until First User Authentication (
NSFileProtectionCompleteUntilFirstUserAuthentication): Default for most apps. Data accessible after first unlock since boot. - No Protection (
NSFileProtectionNone): Always accessible. Use sparingly.
Analogy: Think of protection classes like safe deposit boxes with different key requirements—some need your presence, others just need the bank to be open.
The iOS Keychain
The Keychain is iOS's encrypted vault for sensitive credentials (passwords, tokens, certificates, cryptographic keys). Unlike regular files, Keychain items:
- Are encrypted with device-specific hardware keys
- Persist across app updates and reinstalls
- Can be configured with accessibility levels similar to Data Protection classes
- Support biometric authentication requirements
- Can be synced via iCloud Keychain (if enabled)
Common accessibility levels:
kSecAttrAccessibleWhenUnlocked: Similar to Complete ProtectionkSecAttrAccessibleAfterFirstUnlock: Similar to default Data ProtectionkSecAttrAccessibleWhenPasscodeSetThisDeviceOnly: Requires device passcode, never syncs
You would store API tokens, encryption keys, and user credentials here—never in UserDefaults or plain files.
Key Takeaway: iOS Data Protection API automatically encrypts files using hardware-backed protection classes that tie decryption to device lock state, while the Keychain provides a dedicated, hardware-secured vault specifically for credentials and cryptographic material.