-
Notifications
You must be signed in to change notification settings - Fork 0
/
GoNativeKeychain.swift
215 lines (186 loc) · 7.67 KB
/
GoNativeKeychain.swift
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
//
// GoNativeKeychain.swift
// Copyright © 2021-2022 WindCloud Australia. All rights reserved.
//
// Created by Weiyin He on 7/1/16.
// Copyright © 2016 GoNative.io LLC. All rights reserved.
//
import UIKit
import LocalAuthentication
let kGoNativeKeychainService:String = "GoNative Keychain Service"
enum KeychainOperationResult: String {
case Success = "success"
case DuplicateItem = "duplicateItem"
case ItemNotFound = "itemNotFound"
case AuthenticationFailed = "authenticationFailed"
case GenericError = "genericError"
case UserCanceled = "userCanceled"
case Unimplemented = "unimplemented"
}
open class GoNativeKeychain: NSObject {
var authContext = LAContext()
func getStatusAsync(_ callback: @escaping ([String:AnyObject]) -> (Void)) -> Void {
getSecretExistsAsync { (exists) -> (Void) in
let result: [String: AnyObject] = [
"hasTouchId": self.hasTouchIdD() as AnyObject,
"biometryType": self.getBiometryType() as AnyObject,
"hasSecret": exists as AnyObject
]
callback(result)
}
}
fileprivate func hasTouchIdD() -> Bool {
if #available(iOS 9.0, *) {
return authContext.canEvaluatePolicy(LAPolicy.deviceOwnerAuthenticationWithBiometrics, error: nil)
} else {
return false
}
}
fileprivate func getBiometryType() -> String {
if #available(iOS 11.0, *) {
if !hasTouchIdD() {
return "none";
}
let type = authContext.biometryType;
if type.rawValue == 1 {
return "touchId";
} else if type.rawValue == 2 {
return "faceId";
} else {
return "none";
}
} else {
return "none";
}
}
func getSecretAsync(_ prompt: String?, callback: @escaping (_ result: KeychainOperationResult, _ secret: String?)->(Void)) -> Void {
if #available(iOS 9.0, *) {
let operationPrompt = prompt == nil ? "Authenticate to retrieve saved credentials" : prompt
let query: NSDictionary = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: kGoNativeKeychainService,
kSecReturnData as String: true,
kSecUseOperationPrompt as String: operationPrompt!
]
var dataTypeRef: AnyObject?
DispatchQueue.global(qos: DispatchQoS.QoSClass.default).async {
let status: OSStatus = withUnsafeMutablePointer(to: &dataTypeRef) {
SecItemCopyMatching(query as CFDictionary, UnsafeMutablePointer($0))
}
if status == errSecSuccess {
let data = dataTypeRef as! Data
let secret = String(data: data, encoding: String.Encoding.utf8)
DispatchQueue.main.async(execute: {
callback(.Success, secret)
})
} else {
DispatchQueue.main.async(execute: {
callback(self.statusToEnum(status), nil)
})
}
}
} else {
DispatchQueue.main.async(execute: {
callback(.Unimplemented, nil)
})
}
}
func getSecretExistsAsync(_ callback: @escaping (_ exists: Bool)->(Void)) -> Void {
if #available(iOS 9.0, *) {
let query: NSDictionary = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: kGoNativeKeychainService,
kSecUseAuthenticationUI as String: kSecUseAuthenticationUIFail
]
var dataTypeRef: AnyObject?
DispatchQueue.global(qos: DispatchQoS.QoSClass.default).async {
let status: OSStatus = withUnsafeMutablePointer(to: &dataTypeRef) {
SecItemCopyMatching(query as CFDictionary, UnsafeMutablePointer($0))
}
if status == errSecInteractionNotAllowed || status == errSecSuccess {
callback(true)
} else {
callback(false)
}
}
} else {
DispatchQueue.main.async(execute: {
callback(false)
})
}
}
func saveSecretAsync(_ secret: String, callback:@escaping (_ result: KeychainOperationResult)->(Void)) -> Void {
deleteSecretAsync { (deleteResult) -> (Void) in
// ignore delete result
self._saveSecretAsync(secret, callback: callback)
}
}
fileprivate func _saveSecretAsync(_ secret: String, callback:@escaping (_ result:KeychainOperationResult)->(Void)) -> Void {
if #available(iOS 9.0, *) {
let secretData = secret.data(using: String.Encoding.utf8)
let accessControlError:UnsafeMutablePointer<Unmanaged<CFError>?>? = nil
let accessControlRef = SecAccessControlCreateWithFlags(kCFAllocatorDefault, kSecAttrAccessibleWhenUnlockedThisDeviceOnly, SecAccessControlCreateFlags.biometryAny, accessControlError)
if accessControlRef == nil || accessControlError != nil {
DispatchQueue.main.async(execute: {
callback(.GenericError)
})
return
}
let query: NSDictionary = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: kGoNativeKeychainService,
kSecValueData as String: secretData!,
kSecUseAuthenticationUI as String: kSecUseAuthenticationUIFail,
kSecAttrAccessControl as String: accessControlRef!
]
DispatchQueue.global(qos: DispatchQoS.QoSClass.default).async {
let status = SecItemAdd(query, nil)
DispatchQueue.main.async(execute: {
callback(self.statusToEnum(status))
})
}
} else {
DispatchQueue.main.async(execute: {
callback(.Unimplemented)
})
}
}
func deleteSecretAsync(_ callback: @escaping (_ result: KeychainOperationResult)->(Void)) -> Void {
let query: NSDictionary = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: kGoNativeKeychainService,
]
DispatchQueue.global(qos: DispatchQoS.QoSClass.default).async {
let status = SecItemDelete(query)
DispatchQueue.main.async(execute: {
callback(self.statusToEnum(status))
})
}
}
@objc
func deleteSecret() {
let query: NSDictionary = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: kGoNativeKeychainService,
]
SecItemDelete(query);
}
func statusToEnum(_ status: OSStatus) -> KeychainOperationResult {
switch status {
case errSecSuccess:
return .Success
case errSecDuplicateItem:
return .DuplicateItem
case errSecItemNotFound:
return .ItemNotFound
case errSecAuthFailed:
return .AuthenticationFailed
case errSecUserCanceled:
return .UserCanceled
case errSecUnimplemented:
return .Unimplemented
default:
return .GenericError
}
}
}