无法在AFNetworking 2中使用自签名证书

时间:2013-11-26 20:50:54

标签: ios apache ssl-certificate afnetworking-2

我将Apache服务器使用的.cer证书放在Xcode项目中。当应用程序尝试与服务器通信时,我在Xcode中收到此错误:

Assertion failure in id AFPublicKeyForCertificate(NSData *__strong)(),
/Users/../ProjectName/AFNetworking/AFSecurityPolicy.m:52
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', 
reason: 'Invalid parameter not satisfying: allowedCertificate'

以下是调用服务器的代码:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[self setSecurityPolicy:[AFSecurityPolicy policyWithPinningMode:AFSSLPinningModePublicKey]];
[manager POST:@"https://www.example.com/" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
//success
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//failure
}];

我将钉扎模式更改为AFSSLPinningModeCertificate,没有运气。

当我删除这一行时:

[self setSecurityPolicy:[AFSecurityPolicy policyWithPinningMode:AFSSLPinningModePublicKey]];

服务器响应错误消息:

"The operation couldn't be completed. (NSURLErrorDomain error -1012.)"

证书是使用OpenSSL创建的,我甚至尝试过StartSSL.com的免费证书

对于Apache Server端,这是虚拟主机配置:

# My custom host
<VirtualHost *:443>
    ServerName www.example.com
    DocumentRoot "/path/to/folder"
    SSLEngine on
    SSLCipherSuite HIGH:!aNULL:!MD5
    SSLCertificateFile /path/to/www.example.com.cer
    SSLCertificateKeyFile /path/to/www.example.com.key
    <Directory "/the/directory/">
        Options Indexes FollowSymLinks Includes ExecCGI
        AllowOverride All
        Require all granted
    </Directory>
    ErrorLog "logs/mysite.local-error_log"
</VirtualHost>

并且服务器确实侦听443端口

4 个答案:

答案 0 :(得分:9)

您的证书文件看起来格式不正确。您的代码在这些行(AFURLConnectionOperation/pinnedPublicKeys)处失败:

SecCertificateRef allowedCertificate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)data);
NSParameterAssert(allowedCertificate);

我有同样的错误(在AFNetworking 1.1上,但版本无关紧要),当我的证书看起来像这样:

-----BEGIN CERTIFICATE-----
..
-----END CERTIFICATE----- 

我设法通过使用this answer中的命令将证书转换为x509格式来解决此问题:

openssl x509 -in adn.crt -outform der -out "adn.der"

之后我将adn.der重命名为adn.cer('。''似乎是AFNetworking的预期扩展名),现在一切正常。

答案 1 :(得分:0)

问题不在于AFNetworkings,而是在iOS上:您需要在设备上安装自签名证书,因为iOS安全设置禁止连接到不受信任的来源。

您可以通过在iOS设备上打开证书(将其邮寄给自己并打开它)并按照安装说明将自签名证书添加为受信任的来源。

答案 2 :(得分:0)

如果需要,您可以通过更改安全策略来禁用无效的证书检查。

[self setAllowInvalidCertificates:YES];

请在文档中阅读更多内容:http://cocoadocs.org/docsets/AFNetworking/2.0.3/Classes/AFSecurityPolicy.html#//api/name/allowInvalidCertificates

您还可以固定证书:http://cocoadocs.org/docsets/AFNetworking/2.0.3/Classes/AFSecurityPolicy.html#//api/name/pinnedCertificates

答案 3 :(得分:0)