-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKeychainStorage.swift
More file actions
81 lines (65 loc) · 2.05 KB
/
Copy pathKeychainStorage.swift
File metadata and controls
81 lines (65 loc) · 2.05 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
import Foundation
// A type that just manages talking to system keychain and nothing else
struct KeychainStorage {
let identifier: String
init(identifier: String) { self.identifier = identifier}
private func makeParameters(for key: String?) -> [CFString: Any] {
var query: [CFString: Any] = [
kSecAttrGeneric: Data(self.identifier.utf8),
kSecClass: kSecClassGenericPassword,
]
if let key {
query[kSecAttrService] = key
}
return query
}
func data(for key: String) throws -> Data? {
var params = makeParameters(for: key)
params[kSecMatchLimit] = kSecMatchLimitOne
params[kSecReturnData] = kCFBooleanTrue
var result: CFTypeRef?
let status = SecItemCopyMatching(
params as CFDictionary,
&result)
if status == errSecItemNotFound {
return nil
}
guard status == errSecSuccess else {
throw KeychainError(status)
}
return result as? Data
}
func set(data: Data, for key: String) throws {
var params = makeParameters(for: key)
// Attempt to update the entry
var status = SecItemUpdate(
params as CFDictionary,
[kSecValueData: data] as CFDictionary)
// If it doesn't exist, try adding it
if status == errSecItemNotFound {
params[kSecAttrAccessible] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
params[kSecValueData] = data
status = SecItemAdd(params as CFDictionary, nil)
}
guard status == errSecSuccess else {
throw KeychainError(status)
}
}
func removeData(for key: String) throws {
let params = makeParameters(for: key)
let status = SecItemDelete(params as CFDictionary)
guard status == errSecSuccess || status == errSecItemNotFound else {
throw KeychainError(status)
}
}
func reset() throws {
var query = makeParameters(for: nil)
#if os(macOS)
query[kSecMatchLimit] = kSecMatchLimitAll
#endif
let status = SecItemDelete(query as CFDictionary)
guard status == errSecSuccess || status == errSecItemNotFound else {
throw KeychainError(status)
}
}
}