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

时间:2015-11-10 15:07:41

标签: ios swift certificate keychain

我正在阅读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)

这似乎工作正常,并返回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错误代码(未找到项目)且身份为零,我使用iOS 9.1作为基础SDK,我做错了什么?

更新:在8.1,8.4和9.1模拟器和9.1实际设备中测试,代码正在运行。它的版本为8.4.1的iPhone失败了,任何人都知道发生了什么?

1 个答案:

答案 0 :(得分:1)

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

希望这会有所帮助!!