如何将 SecIdentityRef 添加到 iOS 钥匙串,swift

How to add SecIdentityRef to iOS keychain,swift

我正在读取一个 p12 文件并获得一个 SecIdentityRef 然后将这个身份添加到钥匙串如下

let certData: NSData = NSFileManager.defaultManager().contentsAtPath(filePath)!
let passDictionary: NSMutableDictionary = NSMutableDictionary()
passDictionary.setValue("pass", forKey: kSecImportExportPassphrase as String)
print(kSecImportExportPassphrase as String)
var items: CFArray?
let error = SecPKCS12Import(certData, passDictionary, &items)
let unwrappedItems:CFArray = items!
if error == noErr && CFArrayGetCount(items) > 0 {
    let certChain = unwrappedItems as [AnyObject] as NSArray
    let certificateDict = certChain.objectAtIndex(0)
    var privateKeyRef : SecKeyRef? = nil
    var certificateRef: SecCertificate? = nil
    let secIdentity:SecIdentityRef = certificateDict.valueForKey(kSecImportItemIdentity as String) as! SecIdentityRef
    let subject:NSString=SecCertificateCopySubjectSummary(certificateRef!)

    let keyChainQuery:NSMutableDictionary = NSMutableDictionary(
        objects: [String(kSecClassIdentity),subject,kCFBooleanTrue,String(kSecAttrAccessibleAlwaysThisDeviceOnly),secIdentity],
        forKeys: [String(kSecClass),String(kSecAttrLabel), String(kSecAttrCanSign),String(kSecAttrAccessible),String(kSecValueRef)])
    let status:OSStatus = SecItemAdd(keyChainQuery as CFDictionaryRef, nil)
}

这似乎工作正常并且 returns 0 作为状态代码,但是当我尝试从钥匙串中读取此项时:

var identity: AnyObject?
let searchQuery: NSMutableDictionary = NSMutableDictionary(objects: [String(kSecClassIdentity), kCFBooleanTrue], forKeys: [String(kSecClass),String(kSecReturnRef)])
let status:OSStatus = SecItemCopyMatching(searchQuery as CFDictionaryRef, &identity)

我在身份中收到 -25300 错误代码(未找到项目)nil,我正在使用 iOS 9.1 作为基础 SDK,这是什么我做错了吗?

更新:在 8.1、8.4 和 9.1 模拟器以及 9.1 真实设备中测试,代码正常运行。 8.4.1 版本的 iPhone 失败,有人知道发生了什么吗?

最终重新安装应用程序并使用 SecItemDelete 清理钥匙串解决了问题。

希望对您有所帮助!!