iOS 12:使用URLSession验证本地证书

Vla*_*mir 5 objective-c ssl-certificate ios

我在局域网中有一项服务,该服务使用自定义签名证书进行HTTPS连接。我有证书(cer,p12,der等),它们都可以相互转换。问题是,收到NSURLAuthenticationMethodClientCertificate的挑战时,我应该在didReceiveChallenge中写什么?

不,我不想使用NSAllowsArbitraryLoads,那将是一个安全漏洞。到目前为止,我将要使用NSAllowsLocalNetworking。

- (void)URLSession:(NSURLSession*)session
    didReceiveChallenge:(NSURLAuthenticationChallenge*)challenge
      completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential* _Nullable))completionHandler {
    bool handled = false;

    // Always trust any server name (which is an IP address actually)
    NSLog(@"method: %@", challenge.protectionSpace.authenticationMethod);
    if (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust) {
        SecTrustRef trust = challenge.protectionSpace.serverTrust;
        if (trust != nullptr) {
            completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:trust]);
            handled = true;
        }
    }
    else if (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodClientCertificate) {
        NSString* cerFile = [NSBundle.mainBundle pathForResource:@"dev" ofType:@"der"];
        NSData* data = [NSData dataWithContentsOfFile:cerFile];
        SecCertificateRef cert = SecCertificateCreateWithData(nil, (CFDataRef)data);


        // here I have to somehow validate using existing certificate...

    }

    if (!handled) {
        completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
    }

}
Run Code Online (Sandbox Code Playgroud)

Art*_*tem 0

我认为,“证​​书固定”就是您所寻求的。例如,它在这里和那里都有很好的描述,所以也有答案。

如果您对应用程序中服务器的硬编码公钥有疑问(如第一个链接中所述),那么我认为这是完全可以的,因为公钥是公开的。