【发布时间】: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