当我从服务器下载p12文件并将其设置为NSURLCredential时:
- (NSURLCredential *)getCredential
{
NSURLCredential *credential = nil;
NSString *thePath = //Certificate path
NSData *PKCS12Data = [[NSData alloc]
initWithContentsOfFile:thePath];
CFDataRef inPKCS12Data = (__bridge CFDataRef)PKCS12Data;
OSStatus status = 1; // an error
SecIdentityRef myIdentity;
SecTrustRef myTrust;
if (PKCS12Data)
status = extractIdentityAndTrust(inPKCS12Data, &myIdentity, &myTrust);
if (status == noErr) {
SecCertificateRef myCert = NULL;
status = SecIdentityCopyCertificate (myIdentity, &myCert);
if (status == noErr) {
SecPolicyRef myPolicy = SecPolicyCreateBasicX509();
SecCertificateRef certArray[1] = { myCert };
CFArrayRef myCerts = CFArrayCreate(NULL, (void *)certArray, 1, NULL);
status = SecTrustCreateWithCertificates(myCerts, myPolicy, &myTrust);
SecTrustResultType trustResult;
if (status == noErr) {
status = SecTrustEvaluate(myTrust, &trustResult);
}
if (status == noErr) {
credential = [NSURLCredential credentialWithIdentity:myIdentity
certificates:(__bridge NSArray *)myCerts
`enter code here`persistence:NSURLCredentialPersistenceNone];
}
CFRelease(myCerts);
}
}
return credential;
}
// extractIdentityAndTrust方法
OSStatus extractIdentityAndTrust(CFDataRef inPKCS12Data, SecIdentityRef *outIdentity, SecTrustRef *outTrust)
{
OSStatus securityError = errSecSuccess;
NSString* password = gDataManager.certPass;//CFSTR("qqqqq11");
const void *keys[] = { kSecImportExportPassphrase };
const void *values[] = { (__bridge const void *)(password) };
CFDictionaryRef optionsDictionary = CFDictionaryCreate(NULL, keys, values, 1, NULL, NULL);
CFArrayRef items = CFArrayCreate(NULL, 0, 0, NULL);
securityError = SecPKCS12Import(inPKCS12Data, optionsDictionary, &items);
if (securityError == 0) {
CFDictionaryRef myIdentityAndTrust = CFArrayGetValueAtIndex (items, 0);
const void *tempIdentity = NULL;
tempIdentity = CFDictionaryGetValue (myIdentityAndTrust, kSecImportItemIdentity);
*outIdentity = (SecIdentityRef)tempIdentity;
const void *tempTrust = NULL;
tempTrust = CFDictionaryGetValue (myIdentityAndTrust, kSecImportItemTrust);
*outTrust = (SecTrustRef)tempTrust;
} else {
NSError *error = [NSError errorWithDomain:NSOSStatusErrorDomain code:securityError userInfo:nil];
NSLog(@"Error: %@", [error description]);
}
if (optionsDictionary)
CFRelease(optionsDictionary);
return securityError;
}
当我这样做时,它不起作用。但如果我关闭并打开应用程序,它的工作正常。有人知道如何解决这个问题吗?
谢谢!