我已经解决了我之前将 XML RSA 私钥转换为 PEM 文件的问题,但是我遇到了另一个问题,即在导入 P12 私钥时我得到空数据。以下是我的步骤:
将 PEM 文件转换为 P12 文件
openssl> pkcs12 -export -in rsa.pem -inkey rsa.pem -out rsa.p12 -nocerts
将 P12 文件读取到 iOS 项目
NSString *path = [[NSBundle bundleForClass:[self class]] pathForResource:@"MyPrivateKey" ofType:@"p12"]; NSData *p12data = [NSData dataWithContentsOfFile:path]; if (![self getPrivateKeyRef]) RSAPrivateKey = getPrivateKeywithRawKey(p12data);
导入 P12 私钥
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; }
以为没有错误(OSStatus 值为 0),但 items 数组没有得到任何身份数据。我想知道我是否由于错误的 OpenSSl 使用而没有得到正确的 p12 文件格式。有人成功导入p12文件吗?困扰这个问题好几天了,如果你有线索,请给我建议,谢谢!
休伯特