Skip to content

Instantly share code, notes, and snippets.

@hjuutilainen
Created June 11, 2014 19:48
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hjuutilainen/928d5fcd2d5261e80504 to your computer and use it in GitHub Desktop.
Save hjuutilainen/928d5fcd2d5261e80504 to your computer and use it in GitHub Desktop.
SecPKCS12Import fiddling
OSStatus extractIdentityAndTrust(CFDataRef inP12data, SecIdentityRef *identity, SecTrustRef *trust)
{
OSStatus securityError = errSecSuccess;
CFStringRef password = CFSTR("ThePassword");
const void *keys[] = { kSecImportExportPassphrase };
const void *values[] = { password };
CFDictionaryRef options = CFDictionaryCreate(NULL, keys, values, 1, NULL, NULL);
CFArrayRef items = CFArrayCreate(NULL, 0, 0, NULL);
securityError = SecPKCS12Import(inP12data, options, &items);
if (securityError == 0) {
CFDictionaryRef myIdentityAndTrust = CFArrayGetValueAtIndex(items, 0);
const void *tempIdentity = NULL;
tempIdentity = CFDictionaryGetValue(myIdentityAndTrust, kSecImportItemIdentity);
*identity = (SecIdentityRef)tempIdentity;
const void *tempTrust = NULL;
tempTrust = CFDictionaryGetValue(myIdentityAndTrust, kSecImportItemTrust);
*trust = (SecTrustRef)tempTrust;
}
if (options) {
CFRelease(options);
}
return securityError;
}
- (NSURLCredential *)credentials
{
SecCertificateRef certificateCA = nil;
NSString *thePath = @"/path/to/ca.pem";
NSData *caData = [[NSData alloc] initWithContentsOfFile:thePath];
CFDataRef inPEMData = (__bridge CFDataRef)caData;
certificateCA = SecCertificateCreateWithData(nil, inPEMData);
NSString *clientCertPath = @"/path/to/the/cert.p12";
NSData *inP12data = [[NSData alloc] initWithContentsOfFile:clientCertPath];
SecIdentityRef myIdentity;
SecTrustRef myTrust;
extractIdentityAndTrust((__bridge CFDataRef)inP12data, &myIdentity, &myTrust);
const void *certs[] = { certificateCA };
CFArrayRef certsArray = CFArrayCreate(NULL, certs, 1, NULL);
NSURLCredential *credential = [NSURLCredential credentialWithIdentity:myIdentity certificates:(__bridge NSArray*)certsArray persistence:NSURLCredentialPersistencePermanent];
return credential;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment