将密钥项添加到macOS密钥链时出错

时间:2017-05-04 15:19:06

标签: swift 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(表示该项已存在。) 我该怎么做才能使这段代码有效?

1 个答案:

答案 0 :(得分:1)

如果您错过了强制属性,也可能会返回错误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)