知道SSL证书的通用名称

问题描述:

我对这个文件非常陌生...我想检查SSL服务器证书中的CN ...我该如何做到这一点?我使用NSURLConnection委托方法canAuthenticateAgainstProtectionSpace和didReceiveAuthenticationChallenge。知道SSL证书的通用名称

使用下面的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]; 
} 
+0

为什么SecCertificateCopySubjectSummary代替SecCertificateCopyCommonName? – 2012-03-08 05:46:53

+0

coz SecCertificateCopyCommonName在iOS中不可用(仅适用于OSX) – 2015-09-11 12:54:19

由于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);