我正在创建一个使用TLS与Web服务器通信的iOS应用程序。当我访问Web服务器时,它会向我的设备提供证书,并且我想验证我可以信任它。手动验证TLS证书(ios objective-c)
我有作为der文件嵌入在我的xcode项目中的根证书。到目前为止,我的代码在NSURLConnection的委托函数中获取了两个证书的NSString版本以进行身份验证。
关于如何手动验证的任何想法?
这里是我当前的代码:
- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
NSLog(@"Certificate challenge");
if (self.stageNum==0) {
id <NSURLAuthenticationChallengeSender> sender=challenge.sender;
NSURLProtectionSpace *protectionSpace=challenge.protectionSpace;
SecTrustRef trust=[protectionSpace serverTrust];
//Get server certificate
SecCertificateRef certificate=SecTrustGetCertificateAtIndex(trust, 0);
NSData *serverCertificateData=(__bridge NSData *)SecCertificateCopyData(certificate);
NSString *serverBase64Certificate=[serverCertificateData base64EncodedStringWithOptions:0];
//Get our certificate
NSData *certData1 = [[NSData alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"SUMOSRoot" ofType:@"der"]];
NSString *certBase64=[certData1 base64EncodedStringWithOptions:0];
//Heres where I need to compare the certificates
//
//
[sender useCredential:[NSURLCredential credentialForTrust:protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
}
}
这会起作用,但它并不理想,因为证书最终会过期并重新生成,因此将不再匹配预期的散列值。最好从信任对象中获取公钥并将其与预期的密钥进行比较。这样,即使管理员重新生成证书(假设管理员不更改密钥),它仍将继续信任服务器。 – dgatwood
感谢您的链接!我会看看 –
这个链接是否工作? – Harsh