miibpa
miibpa

Reputation: 235

How to add SecIdentityRef to iOS keychain,swift

I am reading a p12 file and obtaining a SecIdentityRef and then add this Identity to keychain as follows

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)
}

This seems to work fine and returns 0 as status code, but when I try to read this item from the keychain:

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

I receive a -25300 error code (not found item) and nil in identity, I am using iOS 9.1 as base SDK, what am I doing wrong?

UPDATE: Tested in 8.1,8.4 and 9.1 simulators and in 9.1 real device, code is working. It's failing with an iPhone with version 8.4.1, anybody have an idea of what's happening?

Upvotes: 1

Views: 1237

Answers (1)

miibpa
miibpa

Reputation: 235

Finally reinstalling the app and cleaning keychain with SecItemDelete solved the problem.

Hope this helps!!

Upvotes: 1

Related Questions