DomainDig/GenericPasswordKeychain.swift

v5.5.6
domain-dig/DomainDig/GenericPasswordKeychain.swift history · blame · raw

41 lines · 1540 bytes

 1import Foundation
 2import Security
 3
 4/// Secrets kept as generic-password keychain items, keyed by account and
 5/// readable after first unlock.
 6enum GenericPasswordKeychain {
 7    /// Replaces any item under `reference`. False when the keychain refuses.
 8    static func save(_ secret: String, reference: String) -> Bool {
 9        delete(reference: reference)
10        let query: [String: Any] = [
11            kSecClass as String: kSecClassGenericPassword,
12            kSecAttrAccount as String: reference,
13            kSecValueData as String: Data(secret.utf8),
14            kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlock
15        ]
16        return SecItemAdd(query as CFDictionary, nil) == errSecSuccess
17    }
18
19    static func secret(reference: String) -> String? {
20        let query: [String: Any] = [
21            kSecClass as String: kSecClassGenericPassword,
22            kSecAttrAccount as String: reference,
23            kSecReturnData as String: true,
24            kSecMatchLimit as String: kSecMatchLimitOne
25        ]
26        var result: CFTypeRef?
27        guard SecItemCopyMatching(query as CFDictionary, &result) == errSecSuccess,
28              let data = result as? Data else {
29            return nil
30        }
31        return String(data: data, encoding: .utf8)
32    }
33
34    static func delete(reference: String) {
35        let query: [String: Any] = [
36            kSecClass as String: kSecClassGenericPassword,
37            kSecAttrAccount as String: reference
38        ]
39        SecItemDelete(query as CFDictionary)
40    }
41}