How do I programmatically import a certificate int

2019-03-12 14:15发布

问题:

I am working on an iOS5 application that will facilitate mobile payments between two users. As part of the payment process, the sender and the recipient need to communicate with a server. The server requires that both parties present their identities when an authentication challenge is initiated upon connection.

Currently, I have hard-coded the certificate process by utilizing the following two methods in my code:

NSURLConnection Delegate didReceiveAuthenticationChallenge

(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:    (NSURLAuthenticationChallenge *)challenge
{
NSLog(@"Authentication challenge");

// Load Certificate
NSString *path = [[NSBundle mainBundle] pathForResource:@"PKCS12" ofType:@"p12"];
NSData *p12data = [NSData dataWithContentsOfFile:path];
CFDataRef inP12data = (__bridge CFDataRef)p12data;

SecIdentityRef myIdentity;
SecTrustRef myTrust;
extractIdentityAndTrust(inP12data, &myIdentity, &myTrust);

SecCertificateRef myCertificate;
SecIdentityCopyCertificate(myIdentity, &myCertificate);
const void *certs[] = { myCertificate };
CFArrayRef certsArray = CFArrayCreate(NULL, certs, 1, NULL);

NSURLCredential *credential = [NSURLCredential credentialWithIdentity:myIdentity certificates:(__bridge NSArray*)certsArray persistence:NSURLCredentialPersistencePermanent];

[[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
}

C Method extractIdentityAndTrust

OSStatus extractIdentityAndTrust(CFDataRef inP12data, SecIdentityRef *identity, SecTrustRef *trust)
{
OSStatus securityError = errSecSuccess;

CFStringRef password = CFSTR("password");
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;
}

I have tested this code numerous times and have been successful. Now I am trying to move on and allow the appropriate identity to be stored and then retrieved from the app's keychain. My objective is to allow users to import their P12 files via iTunes File Sharing or Dropbox and save them to the keychain.

I have looked at Apple's documentation for Getting and Using Persistent Keychain References and have been unable to figure out how to import the identity. Their code is a little confusing to me as they use undeclared variables/references (specifically the

&persistent_ref

variable). If anyone could help decipher it, that would be greatly appreciated.

TL;DR: How do I save the contents of a P12 file into my iOS5 app's keychain and retrieve it later to hand off to an NSURLConnection didReceiveAuthenticationChallenge method?

回答1:

The following code should do the trick :

NSMutableDictionary *secIdentityParams = [[NSMutableDictionary alloc] init];
[secIdentityParams setObject:(id)myIdentity forKey:(id)kSecValueRef];
OSStatus status = SecItemAdd((CFDictionaryRef) secIdentityParams, NULL);

You interact with the Keychain by passing in a dictionary of key-value pairs that you want to find or create. Each key represents a search option or an attribute of the item in the keychain. Keys are pre-defined constants that you must use depending on the type of data to be stored. Those keys can be found in Apple's developer doc.

I think Apple's source code is indeed missing the allocation of persistentRef. They should have added such declaration at the beginning of the method :

NSData *persistentRef = nil; 

Note that use of persistent reference is not mandatory. The above code should work just fine. As Apple explains it well :

Because a persistent reference remains valid between invocations of your program and can be stored on disk, you can use one to make it easier to find a keychain item that you will need repeatedly

source : https://developer.apple.com/library/ios/#documentation/Security/Conceptual/CertKeyTrustProgGuide/iPhone_Tasks/iPhone_Tasks.html#//apple_ref/doc/uid/TP40001358-CH208-DontLinkElementID_10



回答2:

Swift 4.0

 if let url = Bundle.main.url(forResource: "XXX", withExtension: "pem") {

            let PKCS12Data = NSData(contentsOf: url)
            let inPKCS12Data = CFDataCreate(kCFAllocatorDefault, PKCS12Data!.bytes.assumingMemoryBound(to: UInt8.self), (PKCS12Data?.length)!)

            let keys: [CFString] = [kSecImportExportPassphrase]
            let values: [CFTypeRef] = []

            let keysPointer = UnsafeMutablePointer<UnsafeRawPointer?>.allocate(capacity: keys.count)
            keysPointer.initialize(to: keys)

            let valuesPointer = UnsafeMutablePointer<UnsafeRawPointer?>.allocate(capacity: values.count)
            valuesPointer.initialize(to: values)

            let optionsDictionary = CFDictionaryCreate(kCFAllocatorDefault, keysPointer, valuesPointer, 1, nil, nil)

            var items = CFArrayCreate(kCFAllocatorDefault, UnsafeMutablePointer<UnsafeRawPointer?>.allocate(capacity: 0), 0, nil)
            let securityError = SecPKCS12Import(inPKCS12Data!, optionsDictionary!, &items)
            if (securityError == 0) {
                print("Certificate installed Successfully")
            } else {
                print("Certificate installation failed")
            }

    }