tezvyn:

Keychain Services: A Secure Vault for Small Secrets

AI-drafted, machine-checkedSource: developer.apple.comintermediate
Keychain Services: A Secure Vault for Small Secrets

Think of Keychain as a system-managed safe deposit box for small secrets like passwords or tokens. It's the go-to for storing API keys or user credentials securely. The main footgun is its clunky C-style API, leading most developers to use a wrapper.

WHY IT EXISTS: Apps often handle sensitive user data like passwords and authentication tokens. Storing this information in plaintext, such as in UserDefaults or a simple file, is a major security vulnerability. Keychain Services provides a standardized, OS-level solution for securely storing these small secrets.

THE MENTAL MODEL: Keychain Services is an encrypted database managed by the operating system, not your app directly. Think of it as a digital safe deposit box. You give the OS a secret to store, and the OS locks it away. To get it back, you must have the right permissions. Your app never deals with the raw encryption keys or the file on disk.

HOW IT WORKS: You interact with the Keychain via a low-level, C-style API (e.g., SecItemAdd, SecItemCopyMatching). You construct a query dictionary specifying the item's attributes, such as its class (generic password, internet password), service, account, and the secret data itself. The OS then encrypts the item and stores it. You can also define accessibility policies, like requiring the device to be unlocked or even biometric authentication (Face ID/Touch ID) to retrieve an item.

WHEN TO USE IT: Use it for small, sensitive pieces of data that need to be stored securely and persistently. This includes things like user credentials, API authentication tokens (like OAuth or JWTs), and cryptographic keys. Because keychain data can persist after an app is deleted, it's also useful for sharing credentials between your own apps or maintaining a login across reinstalls.

WHEN NOT TO USE IT: Do not use the Keychain for storing large amounts of data, like images, documents, or large JSON blobs. It is not a general-purpose database and performance will be poor. For non-sensitive user settings or configuration, UserDefaults or property lists are more appropriate.

ONE CANONICAL EXAMPLE: A user logs into your app, and you receive an OAuth 2.0 access token. To avoid asking for a password on every launch, you store this token in the Keychain. You'd create a query to add a generic password item, setting the 'service' to your app's bundle ID, the 'account' to the user's ID, and the 'value' to the token string. On the next launch, you query for that service and account to retrieve the token and make authenticated API calls.

Read the original → developer.apple.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.