I am working on a Swift app which does a TLS connection to a server. I want to set an identity, which the server will validate. I'm given a pkcs12 file. The cert is not trusted locally on my system, but the server can validate it.
First, I didn't need to import the cert - I just want to create an identity that I can use with my connection. I don't think that's possible, so I do this:
var importStatus = SecPKCS12Import(pkcs12Data as CFData, importOptions as CFDictionary, &importArray)
The first time I call this, it's successful. I have come to extract the identity (and certificate) from the importArray returned, but in my case, even though I get an errSecSuccess return status, the importArray is empty.
So first question: why would it be empty?
( if the code is run again, I get an errSecDuplicateItem
- I don't need to store it in the keychain but I guess I'm being forced to)
When I imported, I used a UUID as my identifier - I set it in the options:
let importOptions: [String: Any] = [
kSecImportExportPassphrase as String: password,
kSecImportItemLabel as String: identifier
]
So I try to retrieve the identity from the keychain:
let identityQuery = [
kSecClass: kSecClassIdentity,
kSecReturnRef: true,
kSecAttrLabel: identifier
] as NSDictionary
var identityItem: CFTypeRef?
let status = SecItemCopyMatching(identityQuery as CFDictionary, &identityItem)
where I pass the UUID as identifier, but I actually get back my apple identity, not the certificate. However, if I pass in the certificate's CN, (hard-coded for my testing) I get the right identity back.
So my second question: am I doing something wrong? If i pass an ItemLabel on import, can I retrieve the certificate using that same label?
So for me to get this working, I need to know the CN of my cert, or I need the ItemLabel to work so that I can just retrieve using a UUID.
To determine the CN of my cert, the only apple API I found is this:
SecCertificateCopyCommonName
which requires the cert to be in .der format, rather than .pkcs12. So I have a bit of a chicken and egg problem.
So my last question - is there a way to extract the CN from the pkcs12 file, or to convert the Data from .pkcs12 to .der?
Thanks!