我有一个函数,它使用以下方法在iOS密钥链中创建一个新密钥:
func initialize(_ keyTag: String) throws -> DeviceBindingParameters {
let tag = keyTag.data(using: .utf8)!
let attributes: [String: Any] =
[kSecAttrKeyType as String: kSecAttrKeyTypeECSECPrimeRandom,
kSecAttrKeySizeInBits as String: 256,
kSecPrivateKeyAttrs as String: [
kSecAttrIsPermanent as String: true,
kSecAttrLabel as String: tag,
kSecAttrApplicationTag as String: tag
]
]
... other stuff
}
此外,还有一个函数可以检查该键是否存在:
open func doesKeyExist(_ keyTag: String) -> Bool {
let tag = keyTag.data(using: .utf8)!
let query: [String: Any] = [
kSecClass as String : kSecAttrKeyType,
kSecAttrLabel as String : tag,
kSecAttrApplicationTag as String: tag,
kSecAttrKeyType as String: kSecAttrKeyTypeECSECPrimeRandom,
kSecReturnRef as String: true
]
var item: CFTypeRef?
let status = SecItemCopyMatching(query as CFDictionary, &item)
let errorDescription = SecCopyErrorMessageString(status,nil)
print(errorDescription)
return status == noErr
}
我简单地一个接一个地调用这个方法(为了快速测试,我从AppDelegate.swift
调用这个方法)
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
do {
try crypto.initialize("rohan-key")
let keyStatus = try crypto.doesKeyExist("rohan-key")
print("Key status: \(keyStatus)")
} catch {
print("errors")
}
我总是得到这样的输出:
Optional(The specified item does not appear to be a valid keychain item.)
Key status: false
第一条消息是通过在SecCopyErrorMessageString
状态下调用SecItemCopyMatching
来打印的。此外,我非常确信密钥生成是有效的,因为我使用密钥来签署规范消息,通过线路发送它,然后在基于Java的后端上验证签名--所以这些部分都是完全正确的。我只是不知道为什么这个项目不坚持在密钥库中。
发布于 2020-10-06 09:04:35
https://stackoverflow.com/questions/64177547
复制相似问题