【问题标题】:iOS: Error when creating encryption keys in unit testiOS:在单元测试中创建加密密钥时出错
【发布时间】:2018-01-24 04:11:26
【问题描述】:

我有以下代码在安全飞地中创建密钥对。

let access = SecAccessControlCreateWithFlags(kCFAllocatorDefault,                                            
                                             kSecAttrAccessibleWhenUnlockedThisDeviceOnly,
                                             .privateKeyUsage,
                                             nil)!

var attributes: [String: Any] = [
    kSecAttrKeyType as String: encryptionType,
    kSecAttrKeySizeInBits as String: encryptionBits,
    kSecPrivateKeyAttrs as String: [
       kSecAttrIsPermanent as String: true,
       kSecAttrApplicationTag as String: "abc".data(using: .utf8) as Any,
       kSecAttrAccessControl as String: access,
    ],
]

if Device.hasSecureEnclave {
    attributes[kSecAttrTokenID as String] = kSecAttrTokenIDSecureEnclave
}

var error: Unmanaged<CFError>?
SecKeyCreateRandomKey(attributes as CFDictionary, &error)

在模拟器或设备上运行时,它工作得很好。但是当我在单元测试中运行它时,SecKeyCreateRandomKey 调用返回了一个错误:

Error Domain=NSOSStatusErrorDomain Code=-50 
"Key generation failed, error -50" UserInfo={NSDescription=Key generation failed, error -50}

在尝试了几件事后,我发现问题出在attributes 字典中的kSecAttrIsPermanent 键。如果我删除它,单元测试运行良好。

我读过的所有文档都表明它应该没问题,但每次都失败了。

有人知道为什么吗?

【问题讨论】:

    标签: ios swift security encryption


    【解决方案1】:

    您可能已经看过这个: http://www.openradar.me/36809637

    我遇到了完全相同的问题,Xcode 9.3(测试版)发行说明中没有任何内容表明它已得到修复。

    【讨论】:

    • 谢谢。我开始认为这是我的麻烦。你有没有找到解决方法? Xcode 9.3
    • 问题是kSecAttrIsPermanent as String: true。 Xcode 中的单元测试不允许您这样做。但是,您可以创建一个主机应用程序,以便单元测试有一个模拟器来执行SecAccessControl* 类似的功能。然后从 General 选项卡上的 TARGETS 中选择测试项目,选择 Host Application。这将使单元测试能够在宿主应用程序中执行。
    猜你喜欢
    • 1970-01-01
    • 2014-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多