Objective c 从SSL证书中知道公共名称
我是这个领域的新手…我想检查SSL服务器证书中的CN…我如何实现这一点?我正在使用NSURLConnection委托方法CanAuthenticationAgainstProtectionSpace和didReceiveAuthenticationChallenge。使用下面的两种委托方法,包括Security.framework,并用您的证书通用名替换KNOWN-COMMON-NAMEObjective c 从SSL证书中知道公共名称,objective-c,Objective C,我是这个领域的新手…我想检查SSL服务器证书中的CN…我如何实现这一点?我正在使用NSURLConnection委托方法CanAuthenticationAgainstProtectionSpace和didReceiveAuthenticationChallenge。使用下面的两种委托方法,包括Security.framework,并用您的证书通用名替换KNOWN-COMMON-NAME -(void)connection:(NSURLConnection *)connection didRec
-(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];
}
自iOS 10.3以来,已有一个可用的安全框架:
CFStringRef commonNameRef = NULL;
// Check if function is available (iOS 10.3 and above)
if (SecCertificateCopyCommonName) {
SecCertificateCopyCommonName(certificateRef, &commonNameRef);
}
NSString *commonName = CFBridgingRelease(commonNameRef);
为什么选择SecCertificateCopySubjectSummary而不是SecCertificateCopyCommonName?因为SecCertificateCopyCommonName在iOS中不可用(仅在OSX中)