49 lines
1.5 KiB
Swift
49 lines
1.5 KiB
Swift
|
|
import Foundation
|
||
|
|
import Security
|
||
|
|
|
||
|
|
enum KeychainStore {
|
||
|
|
private static func key(for id: UUID) -> String {
|
||
|
|
"com.nasbackup.connection.\(id.uuidString)"
|
||
|
|
}
|
||
|
|
|
||
|
|
static func savePassword(_ password: String, for id: UUID) {
|
||
|
|
let account = key(for: id)
|
||
|
|
let data = Data(password.utf8)
|
||
|
|
|
||
|
|
let deleteQuery: [CFString: Any] = [
|
||
|
|
kSecClass: kSecClassGenericPassword,
|
||
|
|
kSecAttrAccount: account
|
||
|
|
]
|
||
|
|
SecItemDelete(deleteQuery as CFDictionary)
|
||
|
|
|
||
|
|
let addQuery: [CFString: Any] = [
|
||
|
|
kSecClass: kSecClassGenericPassword,
|
||
|
|
kSecAttrAccount: account,
|
||
|
|
kSecAttrAccessible: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly,
|
||
|
|
kSecValueData: data
|
||
|
|
]
|
||
|
|
SecItemAdd(addQuery as CFDictionary, nil)
|
||
|
|
}
|
||
|
|
|
||
|
|
static func loadPassword(for id: UUID) -> String? {
|
||
|
|
let query: [CFString: Any] = [
|
||
|
|
kSecClass: kSecClassGenericPassword,
|
||
|
|
kSecAttrAccount: key(for: id),
|
||
|
|
kSecReturnData: true,
|
||
|
|
kSecMatchLimit: kSecMatchLimitOne
|
||
|
|
]
|
||
|
|
var result: AnyObject?
|
||
|
|
guard SecItemCopyMatching(query as CFDictionary, &result) == errSecSuccess,
|
||
|
|
let data = result as? Data else { return nil }
|
||
|
|
return String(data: data, encoding: .utf8)
|
||
|
|
}
|
||
|
|
|
||
|
|
static func deletePassword(for id: UUID) {
|
||
|
|
let query: [CFString: Any] = [
|
||
|
|
kSecClass: kSecClassGenericPassword,
|
||
|
|
kSecAttrAccount: key(for: id)
|
||
|
|
]
|
||
|
|
SecItemDelete(query as CFDictionary)
|
||
|
|
}
|
||
|
|
}
|