Storing Secrets in the Keychain
Save and retrieve credentials securely.
Why the Keychain
Passwords, tokens, and keys must never sit in UserDefaults or plain files — those are easy to read. The Keychain is an encrypted, OS-managed database for small secrets, protected by hardware and the user's passcode. It is the only correct place for credentials.
import Security
// Keychain stores secrets encrypted at rest,
// survives app updates, and gates access by policy.Items Are Dictionaries
The Keychain Services API is C-based: you describe an item with a [String: Any] query dictionary using kSec... constant keys. The same dictionary shape is reused for add, search, update, and delete.
import Security
let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrAccount as String: "user@example.com",
kSecAttrService as String: "com.example.app"
]
_ = queryAll lessons in this course
- Storing Secrets in the Keychain
- Keychain Access Control
- Biometric Authentication
- Data Protection and Encryption