簡體   English   中英

將關鍵項添加到macOS鑰匙串時出錯

[英]Error adding Key item to macOS keychain

我有以下代碼:

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(這意味着該項目已經存在)。如何使此代碼起作用?

錯誤errSecDuplicateItem (-25299),也可能是如果你錯過了一個強制屬性,例如,如果你嘗試添加返回kSecClassGenericPassword鍵沒有kSecAttrService集。

在您的情況下,我想知道為什么您嘗試將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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM