2012-02-08 4 views
1

Je suis très nouveau dans ce domaine ... Je veux vérifier le CN dans un certificat de serveur SSL ... comment puis-je y parvenir? J'utilise les méthodes de délégué NSURLConnection canAuthenticateAgainstProtectionSpace et didReceiveAuthenticationChallenge.Connaître le nom commun d'un certificat SSL

Répondre

5

Utilisez les deux méthodes de délégation ci-dessous et incluez le Security.amework, et remplacez KNOWN-COMMON-NAME par le nom commun de votre cert.

-(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

Pourquoi SecCertificateCopySubjectSummary au lieu de SecCertificateCopyCommonName? –

+0

coz SecCertificateCopyCommonName n'est pas disponible sous iOS (uniquement sous OSX) –

0

Depuis iOS 10.3 il a été function disponible dans le cadre de la sécurité:

CFStringRef commonNameRef = NULL; 

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

NSString *commonName = CFBridgingRelease(commonNameRef);