Keychain Query Always Returns errSecItemNotFound After Upgrading to iOS 13

前端 未结 5 1428
春和景丽
春和景丽 2021-01-31 09:01

I am storing passwords into the iOS keychain and later retrieving them to implement a \"remember me\" (auto-login) feature on my app.

I implemented my own wrapper aroun

5条回答
  •  别跟我提以往
    2021-01-31 09:33

    We had the same issue when generating a key pair - works just fine on devices, but on simulator iOS 13 and above it cannot find the key when we try to retreive it later on.

    The solution is in Apple documentation: https://developer.apple.com/documentation/security/certificate_key_and_trust_services/keys/storing_keys_in_the_keychain

    When you generate keys yourself, as described in Generating New Cryptographic Keys, you can store them in the keychain as an implicit part of that process. If you obtain a key by some other means, you can still store it in the keychain.

    In short, after you create a key with SecKeyCreateRandomKey, you need to save this key in the Keychain using SecItemAdd:

    var error: Unmanaged?
    guard let key = SecKeyCreateRandomKey(createKeyQuery as CFDictionary, &error) else {
        // An error occured.
        return
    }
    
    let saveKeyQuery: [String: Any] = [
        kSecClass as String: kSecClassKey,
        kSecAttrApplicationTag as String: tag,
        kSecValueRef as String: key
    ]
    
    let status = SecItemAdd(saveKeyQuery as CFDictionary, nil)
    guard status == errSecSuccess else {
        // An error occured.
        return
    }
    
    // Success!
    

提交回复
热议问题