在 swift5 中更新和删除钥匙串时出现问题

Problem updating and deleting keychain in swift5

我在更新和删除钥匙串时遇到问题。

public func clearKeychain(username: String) throws -> Any?{
    let query: [String: Any] = [
        kSecClass as String: kSecClassGenericPassword,
        kSecAttrAccount as String: username
    ]
    let status = SecItemDelete(query as CFDictionary)

    if status != errSecSuccess {
        throw KeychainError.unhandledError(status: status)
    }
    print("Clear Keychain")
    return status
}

public func updateKeychain(username: String, password: String) throws -> Any?{
    let credentials = Credentials.init(username: username, password: password)
    let data = credentials.password.data(using: .utf8)!

    // store password as data and if you want to store username
    let query: [String: Any] = [kSecClass as String:  kSecClassGenericPassword,
                                kSecAttrAccount as String: username,
                                kSecValueData as String: data]
    let fields: [String: Any] = [
        kSecAttrAccount as String: username,
        kSecValueData as String: data
    ]
    let status = SecItemUpdate(query as CFDictionary, fields as CFDictionary)
    guard status == errSecSuccess else {
        throw KeychainError.unhandledError(status: status) }
    print("Updated Password")
    return status
}

用法:

let _ = (try? keychain.clearKeychain(username: "KeychainUser")) as Any?
let _ = (try? keychain.updateKeychain(username: "KeychainUser", password: "123456789")) as Any?

无法删除或更新钥匙串。我在创建和获取钥匙串的值时没有问题,但在更新或删除时遇到问题。没有显示错误。而状态 returns nil.

要更新和删除您的项目,您需要搜索特定类型的数据。所以你不需要在查询中传递数据。只需按照以下方式更新您的查询即可解决更新数据的问题。

let query: [String: Any] = [kSecClass as String:  kSecClassGenericPassword]

By default, keychain services deletes all keychain items that match the search parameters. If you want to delete a specific item that you already have a reference or persistent reference to, add that to the search dictionary as the value for the kSecMatchItemList key. In this way, you limit the deletion to only the specified item.