我想连接到使用自定义CA签名的证书的HTTPS服务器。我想在我的IOS应用程序中将认证的权限CA证书硬连线。我试过这段代码:
- (void)viewDidLoad {
[super viewDidLoad];
.....
NSString *rootCertPath = [[NSBundle mainBundle] pathForResource:@"qfixca"
ofType:@"der"];
self.rootCertData = [NSData dataWithContentsOfFile:rootCertPath];
.....
NSMutableURLRequest *theRequest=[NSMutableURLRequest requestWithURL:
[NSURL URLWithString:url] cachePolicy:
NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0];
[theRequest setValue:userAgent forHTTPHeaderField:@"User-Agent"];
NSURLConnection *theConnection=[[NSURLConnection alloc]
initWithRequest:theRequest delegate:self];
if (theConnection) {
NSLog(@"Connection establisted successfully");
} else {
NSLog(@"Connection failed.");
}
}
- (void)connection:(NSURLConnection *)connection
willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
SecTrustRef trust = challenge.protectionSpace.serverTrust;
CFDataRef certDataRef = (__bridge_retained CFDataRef)self.rootCertData;
SecCertificateRef cert = SecCertificateCreateWithData(NULL, certDataRef);
// Establish a chain of trust anchored on our bundled certificate.
CFArrayRef certArrayRef = CFArrayCreate(NULL, (void *)&cert, 1, NULL);
SecTrustSetAnchorCertificates(trust, certArrayRef);
SecTrustResultType result;
OSStatus status = SecTrustEvaluate(trust, &result);
if (status == errSecSuccess &&
(result == kSecTrustResultProceed ||
result == kSecTrustResultUnspecified))
{
NSURLCredential *cred = [NSURLCredential credentialForTrust:trust];
[challenge.sender useCredential:cred forAuthenticationChallenge:challenge];
NSLog(@"sending response");
}
else {
[challenge.sender cancelAuthenticationChallenge:challenge];
}
}
问题是我将根CA证书添加为
的锚点后SecTrustSetAnchorCertificates
呼叫
[challenge.sender useCredential:cred forAuthenticationChallenge:challenge];
不能像我预期的那样工作。我得到这个服务器的证书是无效的错误。当我跳过将我的CA证书添加为锚点并直接调用
时[challenge.sender useCredential:cred forAuthenticationChallenge:challenge];
它有效,但我无法验证服务器证书。我究竟做错了什么?非常感谢!
亚当