11

I want to examine the SSL certificate that -(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge receives and I have the following snippet which gives me the Issuer Common Name, and the DER.

SecTrustRef trustRef = [[challenge protectionSpace] serverTrust];
SecTrustEvaluate(trustRef, NULL);
CFIndex count = SecTrustGetCertificateCount(trustRef); 

for (CFIndex i = 0; i < count; i++)
{
    SecCertificateRef certRef = SecTrustGetCertificateAtIndex(trustRef, i);
    CFStringRef certSummary = SecCertificateCopySubjectSummary(certRef);
    CFDataRef certData = SecCertificateCopyData(certRef);
}

In addition I would like to get the fingerprint and the signature. My SSL knowledge isn't that deep; can I perhaps extract the above from the DER representation?

The documentation doesn't help. http://developer.apple.com/library/ios/#documentation/Security/Reference/certifkeytrustservices/Reference/reference.html.

  • I'm surprised they don't provide tools for working with the DER representation (see also “ASN.1” and “X.509”) as it's really quite complex if you're not doing this on a regular basis. – Donal Fellows Oct 23 '11 at 21:31
  • I was surprised to find that such vital information weren't available through Cocoa and I had to "go deeper" and use CF… I will look what I can extract from the DER; complex or not it has to be done... – Alexandros Chalatsis Oct 26 '11 at 15:44

1 Answers1

13

You can obtain the sha1 fingerprint like this.

// #import <CommonCrypto/CommonDigest.h>
+(NSString*)sha1:(NSData*)certData {
    unsigned char sha1Buffer[CC_SHA1_DIGEST_LENGTH]; 
    CC_SHA1(certData.bytes, certData.length, sha1Buffer); 
    NSMutableString *fingerprint = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 3]; 
    for (int i = 0; i < CC_SHA1_DIGEST_LENGTH; ++i) 
        [fingerprint appendFormat:@"%02x ",sha1Buffer[i]]; 
    return [fingerprint stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; 
}

The md5 fingerprint can be obtained in a similar manner. The sha1 and md5 hashes obtained this way match the fingerprints displayed by Safari and Chrome for an untrusted certificate.

Bart Whiteley
  • 1,426
  • 12
  • 10