forked from intitni/CopilotForXcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKeychain.swift
More file actions
89 lines (75 loc) · 2.61 KB
/
Keychain.swift
File metadata and controls
89 lines (75 loc) · 2.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import Configs
import Foundation
import Security
public struct Keychain {
let service = keychainService
let accessGroup = keychainAccessGroup
public enum Error: Swift.Error {
case failedToDeleteFromKeyChain
case failedToUpdateOrSetItem
}
public init() {}
func query(_ key: String) -> [String: Any] {
[
kSecClass as String: kSecClassGenericPassword as String,
kSecAttrService as String: service,
kSecAttrAccessGroup as String: accessGroup,
kSecAttrAccount as String: key,
kSecUseDataProtectionKeychain as String: true,
]
}
func set(_ value: String, key: String) throws {
let query = query(key).merging([
kSecValueData as String: value.data(using: .utf8) ?? Data(),
], uniquingKeysWith: { _, b in b })
let result = SecItemAdd(query as CFDictionary, nil)
switch result {
case noErr:
return
default:
throw Error.failedToUpdateOrSetItem
}
}
public func update(_ value: String, key: String) throws {
let query = query(key).merging([
kSecMatchLimit as String: kSecMatchLimitOne,
kSecReturnData as String: true,
], uniquingKeysWith: { _, b in b })
let attributes: [String: Any] =
[kSecValueData as String: value.data(using: .utf8) ?? Data()]
let result = SecItemUpdate(query as CFDictionary, attributes as CFDictionary)
switch result {
case noErr:
return
case errSecItemNotFound:
try set(value, key: key)
default:
throw Error.failedToUpdateOrSetItem
}
}
public func get(_ key: String) throws -> String? {
let query = query(key).merging([
kSecMatchLimit as String: kSecMatchLimitOne,
kSecReturnData as String: true,
kSecReturnAttributes as String: true,
], uniquingKeysWith: { _, b in b })
var item: CFTypeRef?
if SecItemCopyMatching(query as CFDictionary, &item) == noErr {
if let existingItem = item as? [String: Any],
let passwordData = existingItem[kSecValueData as String] as? Data,
let password = String(data: passwordData, encoding: .utf8)
{
return password
}
return nil
} else {
return nil
}
}
public func remove(_ key: String) throws {
if SecItemDelete(query(key) as CFDictionary) == noErr {
return
}
throw Error.failedToDeleteFromKeyChain
}
}