2017-05-04 45 views
0

我有以下代碼:錯誤添加鍵值項,以MacOS的鑰匙串

let keyData = UUID().uuidString.data(using: .utf8)! 

var attributes: [NSString: Any] = [ 
    kSecClass: kSecClassKey, 
    kSecAttrApplicationTag: keyData, 
] 
let st1 = SecItemDelete(attributes as CFDictionary) 
attributes[kSecValueData] = keyData 
let st2 = SecItemAdd(attributes as CFDictionary, nil) 

我試圖項添加到類型kSecClassKey的鑰匙串。由於某些原因,此代碼在iOS中完美工作,並且在macOS中不起作用。 在macOS中,st1是-25300(表示找不到該項目),而st2是-25299(表示該項目已存在。) 如何才能使此代碼有效?

回答

1

如果您錯過了強制屬性,例如,如果您嘗試添加kSecClassGenericPassword密鑰而沒有設置kSecAttrService,則也可能會返回錯誤errSecDuplicateItem(-25299)。

在你的情況,我想知道你爲什麼試圖將UUID作爲密鑰存儲(kSecClassKey)。將它作爲通用密碼存儲(kSecClassGenericPassword)就足夠了。

let keyData = UUID().uuidString.data(using: .utf8)! 

var attributes: [NSString: Any] = [ 
    kSecClass: kSecClassGenericPassword, 
    kSecAttrService: "YourApp-UUID", // Determines the purpose/context of the used password/value 
    kSecAttrLabel: "YourApp (UUID)", // Name of the Keychain item 
    kSecValueData: keyData, // Actual value, that will be stored securely 
] 
let status = SecItemAdd(attributes as CFDictionary, nil)