在iOS中,如何连接到使用https和服务器上的自签名证书的服务器?(In iOS, how to

2019-06-27 05:24发布

我开发的iOS 5和真的不希望,所以我选择了这个,而不是实现使用AFNetworking的自己使用未弧形码。 也因此我把它分成两个较小的部分,这可能是一个大问题。

1)连接到使用在IOS 5.我使用来自“iOS 5的编程超越极限”在这里提取出的码HTTPS服务器。 因为我为iOS 5开发我不会用在我的项目过时方法。 “RNSecTrustEvaluateAsX509”是重新评估证书作为一个简单的X.509证书,而不是作为SSL握手的一部分的方法。

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

    NSURLProtectionSpace *protSpace =  challenge.protectionSpace;
    SecTrustRef trust = protSpace.serverTrust;
    SecTrustResultType result = kSecTrustResultFatalTrustFailure;

    OSStatus status = SecTrustEvaluate(trust, &result);

    if (status == errSecSuccess && result == kSecTrustResultRecoverableTrustFailure) {
        SecCertificateRef cert = SecTrustGetCertificateAtIndex(trust, 0);
        CFStringRef subject = SecCertificateCopySubjectSummary(cert);

        NSLog(@"Trying to access %@. Got %@.", protSpace.host,
              (__bridge id)subject);
        CFRange range = CFStringFind(subject, CFSTR("192.168.1.100"), kCFCompareAnchored|kCFCompareBackwards);
        if (range.location != kCFNotFound) {
            NSLog(@"Creating new trust certificate.Ignoring the hostname.");
            status = RNSecTrustEvaluateAsX509(trust, &result);
        }
        CFRelease(subject);
    }

    if (status == errSecSuccess) {
        switch (result) {
            case kSecTrustResultInvalid:
            case kSecTrustResultDeny:
            case kSecTrustResultFatalTrustFailure:
            case kSecTrustResultOtherError:
            case kSecTrustResultRecoverableTrustFailure: {
                NSLog(@"Failing due to result: %lu", result);
                [challenge.sender cancelAuthenticationChallenge:challenge];
            }

                break;
            case kSecTrustResultProceed:
            case kSecTrustResultUnspecified: {
                NSLog(@"Successing with result: %lu", result);
                NSURLCredential *cred = [NSURLCredential credentialForTrust:trust];
                [challenge.sender useCredential:cred forAuthenticationChallenge:challenge];
            }
                break;
            default:
                NSAssert(NO,@"Unexpected result from trust evaluation: %d", result);
                break;
        }
    }
    else {
        // Something was broken
        NSLog(@"Complete failure with code: %lu", status);
        [challenge.sender cancelAuthenticationChallenge:challenge];
    }

}

它连接到服务器,但我总是得到一个错误说“该操作无法完成(NSURLErrorDomain错误-1012)”。 和控制台显示“因失败导致5”,这意味着我得到了kSecTrustResultRecoverableTrustFailure。 我怀疑这是因为我在服务器上使用自签名证书。 这导致了第二个问题如下。

2)自签名证书导致的问题。 所以我添加这些行

// Self-signed certificates need to be validated manually.
NSArray *anchors = [self serverAnchors];

SecTrustSetAnchorCertificates(trust, (__bridge CFArrayRef)anchors);
SecTrustSetAnchorCertificatesOnly(trust, YES);

之前

OSStatus status = SecTrustEvaluate(trust, &result);

在上述方法willSendRequestForAuthenticationChallenge。 我也创建了一个方法:

- (NSArray *)serverAnchors
{
    static NSArray *anchors = nil;
    if (!anchors) {
        NSData *caData = [CA_CERTS dataUsingEncoding:NSUTF8StringEncoding];
        SecCertificateRef caRef = SecCertificateCreateWithData(kCFAllocatorDefault, (__bridge CFDataRef) caData);

        anchors = [NSArray arrayWithObjects:(__bridge id)caRef,  nil];

        if (caRef) {
            CFRelease(caRef);   
        }
    }

    return anchors;
}

我定义CA_CERTS为“DER”格式的证书数据,这是一个的NSString我从通过SecCertificateCopyData服务器了。 但我仍然不断收到kSecTrustResultRecoverableTrustFailure。 我真的不知道,如果我在这里做正确的事情。 我如何可以手动验证使用自己的数据服务器的自签名证书? 更具体地讲,如何从iOS的获取其数据?

Answer 1:

我建议纳入OpenSSL的到你的项目用于处理证书和授权的挑战! 然后在“连接:didReceiveAuthenticationChallenge:”在“NSURLConnectionDelegate”协议的方法做这样的事情:

- (void) connection:(NSURLConnection*) connection didReceiveAuthenticationChallenge: (NSURLAuthenticationChallenge*) challenge {
if ([[[challenge protectionSpace] authenticationMethod] isEqualToString: NSURLAuthenticationMethodServerTrust]) {
    SecTrustRef trust = [[challenge protectionSpace] serverTrust];

    NSMutableArray* certificates = [NSMutableArray array];

    NSData* certificate2Data = // your certificate data
    NSData* certificate3Data = // even more certificate data if needed
    SecCertificateRef certificate2 = SecCertificateCreateWithData(NULL, (CFDataRef) certificate2Data);
    SecCertificateRef certificate3 = SecCertificateCreateWithData(NULL, (CFDataRef) certificate3Data);
    [certificates addObject: (id) certificate2];
    [certificates addObject: (id) certificate3];
    CFRelease(certificate2);
    CFRelease(certificate3);

    SecTrustSetAnchorCertificates(trust, (CFArrayRef) certificates);
    SecTrustSetAnchorCertificatesOnly(trust, true);

    SecTrustResultType      trust_result;
    SecTrustEvaluate(trust, &trust_result);
    if (trust_result == kSecTrustResultUnspecified) {
        if (SecTrustGetCertificateCount(trust) > 0) {
            SecCertificateRef leafCertificate = SecTrustGetCertificateAtIndex(trust, 0);

            NSData* leafCertificateData = (NSData*) SecCertificateCopyData(leafCertificate);

            const unsigned char* certificateDataBytes = (const unsigned char *)[leafCertificateData bytes];
            X509* certificateX509 = d2i_X509(NULL, &certificateDataBytes, [leafCertificateData length]);

            CFRelease(leafCertificateData);

            X509_NAME *issuerX509Name = X509_get_issuer_name(certificateX509);
            X509_NAME *subjectX509Name = X509_get_subject_name(certificateX509);

            /*
             with issuerX509Name and subjectX509Name you could check some properties of the certificate and cancel the 
             authentication challenge f.e.!

             if ([[self valueWithKey: @"CN" inName: subjectX509Name cert: certificateX509] isEqualToString: @"xxxx"] == NO) {
                [[challenge sender] cancelAuthenticationChallenge: challenge];
                return;
             }


            */

            NSURLCredential* credential = [NSURLCredential credentialForTrust: trust];
            [[challenge sender] useCredential: credential forAuthenticationChallenge: challenge];
        } else {
            [[challenge sender] cancelAuthenticationChallenge: challenge];
        }
    } else {
        [[challenge sender] cancelAuthenticationChallenge: challenge];
    }
}}


文章来源: In iOS, how to connect to a server using https with self-signed certificate on the server?