Sobes.tech
Junior — Middle

What approach would you use for securely storing passwords in the KeyChain system?

sobes.tech AI

Answer from AI

To securely store passwords in iOS Keychain, you should:

  • Use the Keychain Services API, which provides encryption and secure data storage.
  • Save passwords as protected objects with attributes that restrict access (e.g., kSecAttrAccessibleWhenUnlocked).
  • Never store passwords in plain text outside the Keychain.

Example of saving a password in the Keychain using Swift:

let password = "user_password".data(using: .utf8)!
let query: [String: Any] = [
    kSecClass as String: kSecClassGenericPassword,
    kSecAttrAccount as String: "user@example.com",
    kSecValueData as String: password,
    kSecAttrAccessible as String: kSecAttrAccessibleWhenUnlocked
]
SecItemAdd(query as CFDictionary, nil)

This approach ensures that passwords are stored encrypted and are accessible only when the device is unlocked.