iOS 中钥匙串的使用
2017-08-20 本文已影响35人
冰三尺
import Foundation
let KEY_IN_KEYCHAIN = "com.xxx......"
let KEY_PASSWORD = "com.xxx......"
class Keychain {
internal class func saveUuid(_ uuid: String) {
let saveDict = NSMutableDictionary()
saveDict.setObject(uuid, forKey: KEY_PASSWORD as NSCopying)
save(KEY_IN_KEYCHAIN, data: saveDict)
}
internal class func readUuid() -> AnyObject? {
let savedDict = load(KEY_IN_KEYCHAIN) as? NSDictionary
var result : AnyObject?
result = savedDict?.object(forKey: KEY_PASSWORD) as AnyObject?
return result
}
fileprivate class func getKeychainQuery(_ service: String) -> NSMutableDictionary {
let keychainDict : NSMutableDictionary = [kSecClass as String:kSecClassGenericPassword as String,
kSecAttrAccount as String:service,
kSecAttrService as String:service,
kSecAttrAccessible as String:kSecAttrAccessibleAfterFirstUnlock as String]
return keychainDict
}
fileprivate class func save(_ service: String, data:AnyObject) {
let keychainQuery = getKeychainQuery(service)
SecItemDelete(keychainQuery as CFDictionary)
keychainQuery.setObject(NSKeyedArchiver.archivedData(withRootObject: data), forKey: kSecValueData as String as String as NSCopying)
SecItemAdd(keychainQuery as CFDictionary, nil)
}
fileprivate class func load(_ service: String) -> AnyObject? {
let keychainQuery = getKeychainQuery(service)
keychainQuery.setObject(kCFBooleanTrue, forKey: kSecReturnData as! NSCopying)
keychainQuery.setObject(kSecMatchLimitOne, forKey: kSecMatchLimit as! NSCopying)
var keyData : AnyObject?
var result : AnyObject?
if SecItemCopyMatching(keychainQuery as CFDictionary, &keyData) == noErr{
result = NSKeyedUnarchiver.unarchiveObject(with: keyData as! Data) as AnyObject?
}
return result
}
fileprivate class func delete(_ service: String) {
let keychainQuery = getKeychainQuery(service)
SecItemDelete(keychainQuery as CFDictionary)
}
}