在真实设备上进行单元测试时尝试生成随机密钥对时出错 iOS Swift

Error trying to generate a random key pair when unit testing on a real device iOS Swift

当我尝试 运行 在真实设备上进行单元测试时,它失败了。

返回的错误是

-25293 ("The user name or passphrase you entered is not correct.").

这是我失败的代码:

let accessControl = SecAccessControlCreateWithFlags(
  kCFAllocatorDefault,
  kSecAttrAccessibleAfterFirstUnlock,
  [.privateKeyUsage],
  nil)

let privateKeyAttrs = [
  kSecAttrIsPermanent as String    : true,
  kSecAttrApplicationTag as String : tag,
  kSecAttrAccessControl as String  : accessControl
  ] as [String : Any]

let generationQuery: [String: Any] = [
  kSecAttrKeyType as String       : kSecAttrKeyTypeRSA,
  kSecAttrKeySizeInBits as String : 2048,
  kSecPrivateKeyAttrs as String   : privateKeyAttrs]

var error: Unmanaged<CFError>?
    guard let privateKey = SecKeyCreateRandomKey(generationQuery as CFDictionary, &error) else {
        throw <MyError>
    }

即使我将可访问保护更改为 kSecAttrAccessibleAlways 或 kSecAttrAccessibleWhenUnlocked,SecKeyCreateRandomKey 也会失败,如果我只是从我的 privateKeyAttrs 中删除 kSecAttrAccessControl,我的测试就会通过。

More details: If I run my tests on a simulator it pass; I'm using Xcode 11.6 and swift 5.

.privateKeyUsage 专门用于创建存储在 Secure Enclave 中的密钥对:

An attempt to use this constraint while generating a key pair outside the Secure Enclave fails.

放弃那个选项。如果您只是想在钥匙串中创建密钥对,则不需要(也不能使用)。