我想连接到使用自定义 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];
它有效,但我无法验证服务器证书。我究竟做错了什么?非常感谢!
亚当