78 lines
2.6 KiB
Swift
78 lines
2.6 KiB
Swift
//
|
|
// DDKeychain.swift
|
|
// DDPersistenceKit_Private
|
|
// Created by DDIsFriend on 2023/9/21.
|
|
//
|
|
|
|
import Foundation
|
|
import Security
|
|
|
|
public let DDKC = DDKeychain.default
|
|
open class DDKeychain : NSObject {
|
|
public static let `default` = DDKeychain()
|
|
|
|
public struct Credentials {
|
|
var itemKey : String
|
|
var itemValue : String?
|
|
public init(itemKey: String, itemValue: String? = nil) {
|
|
self.itemKey = itemKey
|
|
self.itemValue = itemValue
|
|
}
|
|
}
|
|
|
|
public enum KeychainError : Int {
|
|
case success = 0
|
|
case failure = 1
|
|
}
|
|
|
|
public func addItem(credentials:Credentials) -> KeychainError {
|
|
let itemKey = credentials.itemKey
|
|
guard let itemValue = credentials.itemValue else {
|
|
return .failure
|
|
}
|
|
let itemValueData = itemValue.data(using: .utf8)!
|
|
let query : [String : Any] = [kSecValueData as String:itemValueData,kSecAttrAccount as String:itemKey,kSecClass as String:kSecClassGenericPassword]
|
|
let status = SecItemAdd(query as CFDictionary, nil)
|
|
if status == 0 {
|
|
return .success
|
|
}
|
|
return .failure
|
|
}
|
|
|
|
public func queryItem(credentials:Credentials) -> Data? {
|
|
let itemKey = credentials.itemKey
|
|
let query : [String : Any] = [kSecReturnData as String:true,kSecAttrAccount as String:itemKey,kSecClass as String:kSecClassGenericPassword]
|
|
|
|
var itemValueData : CFTypeRef?
|
|
let status = SecItemCopyMatching(query as CFDictionary, &itemValueData)
|
|
if status == 0 {
|
|
return itemValueData as? Data
|
|
}
|
|
return nil
|
|
}
|
|
|
|
public func updateItem(credentials:Credentials) -> KeychainError {
|
|
let query : [String : Any] = [kSecAttrAccount as String: credentials.itemKey,kSecClass as String:kSecClassGenericPassword]
|
|
guard let itemValue = credentials.itemValue else {
|
|
return .failure
|
|
}
|
|
let itemValueData = itemValue.data(using: .utf8)!
|
|
let attributes : [String : Any] = [kSecValueData as String:itemValueData]
|
|
|
|
let status = SecItemUpdate(query as CFDictionary, attributes as CFDictionary)
|
|
if status == 0 {
|
|
return .success
|
|
}
|
|
return .failure
|
|
}
|
|
|
|
public func deleteItem(credentials:Credentials) -> KeychainError {
|
|
let query : [String : Any] = [kSecClass as String:kSecClassGenericPassword,kSecAttrAccount as String:credentials.itemKey]
|
|
let status = SecItemDelete(query as CFDictionary)
|
|
if status == 0 {
|
|
return .success
|
|
}
|
|
return .failure
|
|
}
|
|
}
|