ios - iOS 上的 SSL 固定

标签 ios security ssl foundation

为了提高我的应用程序的安全性并保护用户免受 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

显然本地和远程证书之间的比较失败,因为数据的长度不同,因此也无法固定。

为什么会发生这种情况,我该如何解决这个问题?

最佳答案

我遇到了同样的问题。问题可能是因为您没有将 .crt 文件转换为正确的格式。 iOS 和 OSX 正在寻找您的证书以在 .der 中格式。您需要使用 openssl转换它。 Here是关于此主题的非常有用的文章。我的公共(public)证书来自 Apache 服务器(我假设你的也一样)。在查看了 openssl 文档之后,我能够弄清楚如何让它工作。

1) 打开终端并将目录更改为您的 .crt 的位置。

2) 执行这条命令:

openssl x509 -in your_cert.crt -outform der -out your_output_name.der

这将创建一个名为“your_output_file.der”的输出文件。您必须将其导入您的 xCode 项目并在

- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge

NSURLConnectionDelegate 实现的方法。

希望对您有所帮助!

关于ios - iOS 上的 SSL 固定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16694280/

相关文章:

android - 在 Android 应用程序中,将来自 Google API 的 client_secret.json 存储在哪里?

php - SSL 证书验证在 WordPress 更新中通过纯 HTTP(非 SSL)失败

c# - 无法为 Facebook 创建 SSL/TLS 安全通道

ios - 刷新控件 - 显示在电视上方

ios - 如何在 XCode 中以编程方式设置 UIImageView?

ios - 未调用 UISlider 值更改目标

asp.net - IIS Express http/https 绑定(bind)无法正常工作

ios - Google Analytics SDK 创建 SQLite 错误

maven - 如何排除hive-exec的所有漏洞,包括 “shaded”依赖项本身?

库中的java权限