Sobes.tech
Junior — Middle

What is the advantage of using Key Chain for secure password storage?

sobes.tech AI

Answer from AI

Keychain is a secure storage in iOS designed for storing confidential data such as passwords, tokens, and certificates. Its advantage is that it provides data encryption at the system level and protects data using hardware components (Secure Enclave), significantly enhancing security compared to storing passwords in regular files or UserDefaults.

Additionally, Keychain automatically manages access to data, allowing restrictions to be set so that only certain apps or groups of apps can access it, reducing the risk of leaks. Data in the Keychain is also preserved across device reboots and even when the app is deleted (if configured accordingly).

Example of using Keychain to save a password:

import Security

func savePassword(_ password: String, for account: String) {
    let data = password.data(using: .utf8)!
    let query: [String: Any] = [
        kSecClass as String: kSecClassGenericPassword,
        kSecAttrAccount as String: account,
        kSecValueData as String: data
    ]
    SecItemAdd(query as CFDictionary, nil)
}