【发布时间】:2013-05-17 15:40:36
【问题描述】:
为了提高我的应用程序的安全性并保护用户免受 MITM 攻击,我正在尝试按照this post 的内容使用我的自签名证书进行 SSL 固定。
所以我使用以下代码来比较我从服务器获得的证书和应用程序中捆绑的证书。
- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
SecTrustRef serverTrust = challenge.protectionSpace.serverTrust;
SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, 0);
NSData *remoteCertificateData = CFBridgingRelease(SecCertificateCopyData(certificate));
NSLog(@"Remote Certificate Data Length: %d",[remoteCertificateData length]);
NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"apache" ofType:@"crt"];
NSData *localCertData = [NSData dataWithContentsOfFile:cerPath];
NSLog(@"Local Certificate Data Length: %d",[localCertData length]);
if ([remoteCertificateData isEqualToData:localCertData]) {
NSURLCredential *credential = [NSURLCredential credentialForTrust:serverTrust];
[[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
}
else {
[[challenge sender] cancelAuthenticationChallenge:challenge];
}
}
我的代码与我链接的博客文章中的代码之间唯一不同的是代表我的证书的资源的名称和扩展名(.cer 到 .crt)以及我添加的两个 NSLog,它们将派上用场稍后再说明问题所在。
事实上,当这段代码被执行时,我得到了这样的输出:
2013-05-22 16:08:53.331 HTTPS Test[5379:c07] Remote Certificate Data Length: 880
2013-05-22 16:09:01.346 HTTPS Test[5379:c07] Local Certificate Data Length: 1249
很明显Local和Remote证书比较失败,因为数据的长度不同,所以pinning也失败了。
为什么会发生这种情况,我该如何解决这个问题?
【问题讨论】:
-
您是否考虑过将返回的证书数据保存到文件中并使用它?否则,对数据进行比较,看看有什么不同。
-
不,我没想到!好主意,我马上试试!
-
如果您使用 Alamofire,请查看jayprakashdubey.blogspot.in/2017/07/…
标签: ios security ssl foundation