iOS Keychain & Data Protection
Mobile Cryptographic Implementation · Mobile Application Security track
9 min read
In this module
The Problem: Protecting Secrets on a Mobile Device
A phone holds some of the most sensitive data a person owns: passwords, auth tokens, cryptographic keys, certificates, financial credentials. Unlike a rack-mounted server in a data centre, a phone gets stolen, seized, dropped on a train. The OS has to protect this stuff from malicious apps on the device and from someone holding the hardware in their hand.
iOS handles it with two interlocking systems: Keychain Services for individual secrets, and Data Protection for filesystem-level file encryption. Both lean on a hardware-rooted key hierarchy that bottoms out in the Secure Enclave.
Keychain Services API
The iOS Keychain is an encrypted database tended by the securityd daemon. Apps talk to it through the Keychain Services API, which boils down to four functions:
- SecItemAdd - store a new item (password, key, certificate, or identity).
- SecItemCopyMatching - retrieve items matching a query.
- SecItemUpdate - modify an existing item's attributes or value.
- SecItemDelete - remove an item from the Keychain.
Each Keychain item is a dictionary of attributes plus a secret value. The attributes — account name, service identifier, access group — are searchable. The secret payload — password, key material, certificate bytes — is encrypted.
// Storing a password in the Keychainlet query: [String: Any] = [ kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: "com.example.myapp", kSecAttrAccount as String: "user@example.com", kSecValueData as String: "s3cretP@ss".data(using: .utf8)!, kSecAttrAccessible as String: kSecAttrAccessibleWhenUnlocked]let status = SecItemAdd(query as CFDictionary, nil)The Keychain supports several item classes: kSecClassGenericPassword for arbitrary secrets, kSecClassInternetPassword for URL-associated credentials, kSecClassCertificate for X.509 certificates, kSecClassKey for cryptographic keys, and kSecClassIdentity for a certificate paired with its private key.
Keychain Access Groups and App Isolation
Every Keychain item lives inside an access group. By default, an app can only see items in its own access group, derived from its bundle identifier and code-signing entitlements.
Apps from the same developer can share items by declaring a shared access group in their entitlements. The keychain-access-groups entitlement controls this, and it has to be signed off by Apple's provisioning system. An app can't claim an access group belonging to someone else's developer account.
securityd enforces this isolation with code-signing checks behind it. Even a fully compromised app can't reach into another app's Keychain items unless they were already in a shared access group.
Keychain Protection Classes
Every item carries a protection class that decides when it can be read. The class governs how the item's encryption key is managed against the device's lock state:
kSecAttrAccessibleWhenUnlocked (behaves like file Class A)
Readable only while the device is unlocked. Shortly after it locks, the class key is wiped from memory. It's also what you get if you don't set kSecAttrAccessible at all. This is the strongest setting for sensitive credentials — a locked, seized device gives an attacker nothing usable without the passcode.
kSecAttrAccessibleAfterFirstUnlock (behaves like file Class C)
Becomes readable after the first unlock since boot. The class key stays in memory until the next reboot. Apple uses it for a lot of system items, and it's the right pick for background work that has to keep going while the device is locked — push tokens, background fetch credentials, that kind of thing.
kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly
Readable only while the device is unlocked and a passcode is in place. Remove the passcode and the items get deleted. This class is for things that should never exist on a passcode-less device — auth keys for high-security apps, for example.
kSecAttrAccessibleAlways (Deprecated)
Readable any time, lock state irrelevant. The weakest setting; deprecated since iOS 12. Items in this class are encrypted only with the hardware UID key — no passcode involvement at all.
Every protection class has a ThisDeviceOnly variant (e.g. kSecAttrAccessibleWhenUnlockedThisDeviceOnly). The encryption key for these items folds in the device's unique hardware UID, so they can't be restored to a different device from a backup. Reach for ThisDeviceOnly for anything that should never leave the physical device — private keys, authentication tokens, the obvious targets.
Data Protection: File-Level Encryption
Beyond the Keychain, iOS offers Data Protection to encrypt whole files at the filesystem layer. Every file gets its own per-file key, which is itself wrapped by a class key from one of four protection classes.
The four file Data Protection classes mirror the Keychain protection classes:
- NSFileProtectionComplete (Class A): file accessible only when unlocked.
- NSFileProtectionCompleteUnlessOpen (Class B): file accessible while open, even if device locks.
- NSFileProtectionCompleteUntilFirstUserAuthentication (Class C): accessible after first unlock.
- NSFileProtectionNone (Class D): no passcode-based protection. Files are still encrypted, but the class key is protected only by the hardware UID, so they're readable whenever the device is on.
The Keychain borrows the file classes' behaviour but not their names: there's no Keychain equivalent of Class B, and "Class A" strictly means the file class. If an app doesn't pick a file class, new files get NSFileProtectionCompleteUntilFirstUserAuthentication.
The Key Hierarchy
iOS Data Protection stacks several layers of keys so that compromising any single one doesn't unlock the whole device:
- Hardware UID key: a 256-bit AES key fused into the Secure Enclave at manufacture. It never leaves the chip and no software can read it — kernel included.
- Class keys: random keys stored in the system keybag, wrapped with a key that the Secure Enclave derives by tangling the user's passcode with the hardware UID key. Some classes mix in the UID alone; Class B uses an asymmetric scheme so files can be written while the device is locked. The derivation's iteration count is calibrated per device so that each attempt takes about 80 ms, which throttles brute force.
- Per-file keys: a random 256-bit AES key minted per file. Each per-file key is wrapped with the appropriate class key and stashed in the file's metadata.
Reading a file means unwrapping its per-file key with the class key, and the class key is only available once the Secure Enclave has used the passcode and UID key to unlock the keybag.
The diagram below adds the pieces the chart leaves out: Class D, and the file system key that encrypts every file's metadata. Flip between the three device states and watch which class keys survive, then click Class B to see how a locked phone can still write a mail attachment it can't read back.
Data Protection key hierarchy
Device state
The user unlocked it at least once since boot, then locked it. Class A's key and Class B's private key are discarded; Class C's key stays in memory.
tangled together inside the Secure Enclave
unwraps class keys A, B and C; D is wrapped by the UID key alone
each class key wraps the per-file keys of its files
The wrapped per-file key lives in the file's metadata, and the file system key encrypts all metadata.
the per-file key encrypts
UID key
A 256-bit AES key fused into the Secure Enclave at manufacture, unique to this device. No software or firmware can read it, the kernel included; the Enclave's AES engine only uses it. Every key below is tied to it, which is why pulling the flash chip gets an attacker nowhere.
Which files can be read now (example files are illustrative)
| Class | Example file | Read existing | Write new |
|---|---|---|---|
| A Complete ProtectionNSFileProtectionComplete | A banking app's cached statements | No | No |
| B Protected Unless OpenNSFileProtectionCompleteUnlessOpen | A mail attachment downloading in the background | Only if already open | Yes |
| C Protected Until First User AuthenticationNSFileProtectionCompleteUntilFirstUserAuthentication | An app's files with no class set (the default) | Yes | Yes |
| D No ProtectionNSFileProtectionNone | A file explicitly marked NSFileProtectionNone | Yes | Yes |
Source: Apple Platform Security, “Data Protection” and “Data Protection classes”.
The Secure Enclave's Role
The Secure Enclave is a dedicated hardware security subsystem: its own processor running an L4-based microkernel, its own encrypted memory, and a hardware RNG. It's physically isolated from the application processor.
Inside the Data Protection scheme, the Secure Enclave handles:
- Holding the hardware UID key that anchors the whole hierarchy. The Enclave is the only thing on the chip that knows it.
- Deriving the passcode key from the UID key and passcode, and unwrapping the class keys with it.
- Rate-limiting passcode attempts in hardware, with escalating delays between failures. The application processor cannot bypass this.
- Guarding biometric templates for Face ID and Touch ID. Matching happens entirely inside the Enclave.
Pull the flash chip off an iOS device and read it raw, and every file is still encrypted with a per-file key, wrapped by a class key, wrapped by the hardware UID key locked inside the Secure Enclave. Without the Enclave — which lives on the SoC, not the storage chip — there's no way to unwrap the class keys. The Enclave's roughly 80 ms key-derivation cost drags brute-forcing a 6-digit numeric passcode out to roughly 22 hours, and a strong alphanumeric passcode lands firmly in the "computationally infeasible" column.
Guess before you reveal: how long does a 4-digit code survive at 80 ms a try? Then a 6-digit one, then a custom 8-character alphanumeric passcode. Turn on the lock-screen delays to see why nobody brute-forces through the UI.
Passcode keyspace calculator
Apple calibrates the passcode key derivation so each attempt takes about 80 ms. It runs inside the Secure Enclave, tangled with the device's UID key, so every guess has to happen on that phone.
Predict first: how long to try every 6-digit passcode at 80 ms each?
Backup Implications
How safe your Keychain and Data Protection items actually stay depends a lot on backup handling:
iCloud Backups
iCloud backups carry most Keychain items, except anything marked ThisDeviceOnly. The backed-up items are re-encrypted using Apple-managed keys. So Apple — and anyone who can compromise the user's Apple account — can potentially read non-ThisDeviceOnly Keychain items out of an iCloud backup.
Encrypted Local Backups (Finder/iTunes)
Local backups encrypted with a user-chosen password sweep up Keychain items from every protection class — the backup password is what protects them inside the archive. Unencrypted local backups still carry the non-ThisDeviceOnly Keychain items, but wrapped with a key derived from the device's UID, so they can only be restored to the same device.
Advanced Data Protection
Advanced Data Protection (iOS 16.2+) end-to-end encrypts iCloud backups with keys held only on the user's devices. Apple itself cannot read the data. The trade-off: Apple also can't help with account recovery if the user loses all their devices and recovery contacts.
What Developers Must Consider
If you store sensitive credentials, default to the ThisDeviceOnly suffix. Auth tokens, private keys, and session credentials should never come back on a different device from a backup. Items that genuinely need to sync — saved passwords in a password manager, say — belong in iCloud Keychain, which has its own end-to-end encryption independent of iCloud Backup.