0Pricing
Swift Academy · Lesson

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"
]
_ = query

All lessons in this course

  1. Storing Secrets in the Keychain
  2. Keychain Access Control
  3. Biometric Authentication
  4. Data Protection and Encryption
← Back to Swift Academy