了解SSL证书的通用名称

时间:2012-02-08 07:42:31

标签: objective-c

我对此提交的内容很新......我想在SSL服务器证书中查看CN ...我该如何实现?我正在使用NSURLConnection委托方法canAuthenticateAgainstProtectionSpace和didReceiveAuthenticationChallenge。

2 个答案:

答案 0 :(得分:5)

使用下面的2个委托方法并包含Security.framework,并将KNOWN-COMMON-NAME替换为您的通用名称。

-(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge{
if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]){
    SecTrustRef trustRef = [[challenge protectionSpace] serverTrust];
    SecTrustEvaluate(trustRef, NULL);
    CFIndex count = SecTrustGetCertificateCount(trustRef); 
    BOOL trust = NO;
    if(count > 0){
        SecCertificateRef certRef = SecTrustGetCertificateAtIndex(trustRef, 0);
        CFStringRef certSummary = SecCertificateCopySubjectSummary(certRef);
        NSString* certSummaryNs = (NSString*)certSummary;
        if([certSummaryNs isEqualToString:@"KNOWN-COMMON-NAME"]){ // split host n
            trust = YES;
        }else{
            NSLog(@"Certificate name does not have required common name");
        }
        CFRelease(certSummary);
    }
    if(trust){
        [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
    }else{
        [challenge.sender cancelAuthenticationChallenge:challenge];
    }
}
[challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
}

- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
    return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}

答案 1 :(得分:1)

iOS 10.3 以来,安全框架中提供了function

CFStringRef commonNameRef = NULL;

// Check if function is available (iOS 10.3 and above)
if (SecCertificateCopyCommonName) {
    SecCertificateCopyCommonName(certificateRef, &commonNameRef);
}

NSString *commonName = CFBridgingRelease(commonNameRef);