I've solved my previos problem of converting XML RSA private key to PEM file, but I run into another problem that I get null data when importing P12 private key. Following is my steps:
Convert PEM file to P12 file
openssl> pkcs12 -export -in rsa.pem -inkey rsa.pem -out rsa.p12 -nocerts
Read P12 file to iOS project
NSString *path = [[NSBundle bundleForClass:[self class]]
pathForResource:@"MyPrivateKey" ofType:@"p12"];
NSData *p12data = [NSData dataWithContentsOfFile:path];
if (![self getPrivateKeyRef])
RSAPrivateKey = getPrivateKeywithRawKey(p12data);
Import P12 Private Key
SecKeyRef getPrivateKeywithRawKey(NSData *pfxkeydata)
{
NSMutableDictionary * options = [[[NSMutableDictionary alloc] init] autorelease];
// Set the public key query dictionary
//change to your .pfx password here
[options setObject:@"MyPassword" forKey:(id)kSecImportExportPassphrase];
CFArrayRef items = CFArrayCreate(NULL, 0, 0, NULL);
OSStatus securityError = SecPKCS12Import((CFDataRef) pfxkeydata,
(CFDictionaryRef)options, &items);
CFDictionaryRef identityDict = CFArrayGetValueAtIndex(items, 0);
SecIdentityRef identityApp =
(SecIdentityRef)CFDictionaryGetValue(identityDict,
kSecImportItemIdentity);
//NSLog(@"%@", securityError);
assert(securityError == noErr);
SecKeyRef privateKeyRef;
SecIdentityCopyPrivateKey(identityApp, &privateKeyRef);
return privateKeyRef;
}
Thought there was no err(OSStatus value is 0), but the items array didn't get any identity data. I am wondering if i didn't get the correct p12 file format due to wrong OpenSSl usage. Has anyone successfully import p12 file? I've stuck in this problem for a couple of days, please give me advices if you got clues, thanks!
Hubert
I got some tips from the internet, and following is the steps to get iOS acceptable p12 key and certification file:
convert XML to PEM
Shell> compile XMLSpec2PEM.java
Shell> XMLSpec2PEM rsa.xml
save the output result to rsa.pem
(borrow from here)
convert PEM to RSA Private Key
OpenSSL> rsa -in rsa.pem -out rsaPrivate.key
Generate a certification request
OpenSSL> req -new -key rsaPrivate.key -out rsaCertReq.crt
(input some basic certification data)
Sign certification of the request
OpenSSL> x509 -req -days 3650 -in rsaCertReq.crt -signkey rsaPrivate.key -out rsaCert.crt
Convert the certification file format to DER (iOS acceptable format)
OpenSSL> x509 -outform der -in rsaCert.crt -out rsaCert.der
Generate PKCS12 Private key(iOS acceptable format)
OpenSSL> pkcs12 -export -out rsaPrivate.pfx -inkey rsaPrivate.key -in rsaCert.crt
No further steps, files generated in step 5 and 6 now can be used in iOS!
reference of OpenSSL instructions:
http://blogs.yaclife.com/?tag=ios%E3%80%80seckeyref%E3%80%80raw%E3%80%80key%E3%80%80rsa%E3%80%803des
http://devsec.org/info/ssl-cert.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With