gpt4 book ai didi

ios - 带有客户端证书的 SecTrustSetAnchorCertificates

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:15:20 25 4
gpt4 key购买 nike

我正在开发 iOS 应用程序。我们有自签名 ca-cert 的自定义证书颁发机构。证书颁发机构也为用户和 https 服务器颁发证书。我想创建 iOS 应用程序,它可以使用 ca 证书验证 https 服务器,也可以使用客户端证书与 https 服务器通信。我已经有了使用客户端证书与 https 服务器通信的代码,但我需要将 ca 证书导入系统 key 环。我想将 ca 证书硬编码到应用程序中。我的代码如下所示:

- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {

bool result=NO;
if ([protectionSpace authenticationMethod] == NSURLAuthenticationMethodServerTrust) {
result= YES;
} else if([protectionSpace authenticationMethod] == NSURLAuthenticationMethodClientCertificate) {
result = YES;
}
return result;
}

- (BOOL)shouldTrustProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
CFDataRef certDataRef = (__bridge_retained CFDataRef)self.rootCertData;
SecCertificateRef cert = SecCertificateCreateWithData(NULL, certDataRef);

SecTrustRef serverTrust = protectionSpace.serverTrust;

CFArrayRef certArrayRef = CFArrayCreate(NULL, (void *)&cert, 1, NULL);
SecTrustSetAnchorCertificates(serverTrust, certArrayRef);

SecTrustResultType trustResult;
SecTrustEvaluate(serverTrust, &trustResult);

return trustResult == kSecTrustResultUnspecified;
}

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {

NSLog(@"Did receive auth challange %@",[challenge debugDescription]);

NSURLProtectionSpace *protectionSpace = [challenge protectionSpace];

NSString *authMethod = [protectionSpace authenticationMethod];
if(authMethod == NSURLAuthenticationMethodServerTrust ) {
NSLog(@"Verifying The Trust");

NSURLCredential* cred=[NSURLCredential credentialForTrust:[protectionSpace serverTrust]];
if ([self shouldTrustProtectionSpace:challenge.protectionSpace]) {
[[challenge sender] useCredential:cred forAuthenticationChallenge:challenge];
NSLog(@"OK");
} else {
NSLog(@"FAILED");
[challenge.sender performDefaultHandlingForAuthenticationChallenge:challenge];
}

}
if(authMethod == NSURLAuthenticationMethodClientCertificate ) {
NSLog(@"Trying Certificate");
.....

一切都很顺利,直到服务器不需要客户端证书。此时我将收到错误消息此服务器的证书无效并且执行永远不会到达点

 NSLog(@"Trying Certificate");

当我将 .der ca-cert 加载到系统 key 环中时,一切正常,甚至客户端证书也被发送到服务器,并且服务器可以识别用户。我认为

SecTrustSetAnchorCertificates(serverTrust, certArrayRef);

以某种方式影响信任,因为当我跳过这个调用时,我可以简单地做:

[[challenge sender] useCredential:cred forAuthenticationChallenge:challenge];

没有任何错误,但在这种情况下我无法验证证书。

我做错了什么?

非常感谢,亚当

最佳答案

看看这段代码

https://github.com/dirkx/Security-Pinning-by-CA

它通过相​​当小心地将两个信任 block 分开(您似乎在混合)来做到这两点。

关于ios - 带有客户端证书的 SecTrustSetAnchorCertificates,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15326553/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com