secItemAdd 在 swift 中保持 return -50 错误

secItemAdd keep return -50 error in swift

尝试在安全链中添加项目时,一直得到 -50。

    var query = [String:AnyObject]()
    query[kSecClass as String] = kSecClassGenericPassword
    query[kSecAttrAccount as String] = "a"
    query[kSecValueData as String] = "b"
    let result = SecItemAdd(query as CFDictionary, nil);

结果是-50。不明白为什么,需要帮助..在此先感谢。

我认为 kSecValueData 键的值需要是 NSData,而不是 String 或 NSString。尝试将您的字符串编码为数据(例如使用 UTF-8 编码)。未经测试的片段:

query[kSecValueData as String] = "b".dataUsingEncoding(NSUTF8StringEncoding)

为了将来参考,错误代码 -50 对应于 errSecParam,SecBase.h 头文件的含义为:"One or more parameters passed to a function were not valid." 如果您再次看到此错误,请尝试更改值您正在使用查询字典传递。

稍微更新了 Swift 5 版本的添加 to/remove 从钥匙串功能:

@discardableResult
func addToKeychain(_ value: Data, tag: Data) -> Bool {
    let attributes: [String: Any] = [
        String(kSecClass): kSecClassKey,
        String(kSecAttrApplicationTag): tag,
        String(kSecValueData): value
    ]

    var result: CFTypeRef? = nil
    let status = SecItemAdd(attributes as CFDictionary, &result)
    if status == errSecSuccess {
        print("Successfully added to keychain.")
    } else {
        if let error: String = SecCopyErrorMessageString(status, nil) as String? {
            print(error)
        }

        return false
    }

    return true
}

@discardableResult
func removeFromKeychain(_ value: Data, tag: Data) -> Bool {
    let attributes: [String: Any] = [
        String(kSecClass): kSecClassKey,
        String(kSecAttrApplicationTag): tag,
        String(kSecValueData): value
    ]

    let status = SecItemDelete(attributes as CFDictionary)
    if status == errSecSuccess {
        print("Successfully removed from keychain.")
    } else {
        if let error: String = SecCopyErrorMessageString(status, nil) as String? {
            print(error)
        }

        return false
    }

    return true
}

可以这样使用:

let value: Data = "key".data(using: .utf8)!
let tag: Data = "com.test.key".data(using: .utf8)!

removeFromKeychain(value, tag: tag)
addToKeychain(value, tag: tag)