问题 获取SSL证书详细信息


我想检查那个SSL证书 -(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge 收到,我有以下代码片段,它给我发行人通用名称和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);
}

另外我想得到指纹和签名。 我的SSL知识并不那么深刻;我可以从DER表示中提取上述内容吗?

文档没有帮助。 http://developer.apple.com/library/ios/#documentation/Security/Reference/certifkeytrustservices/Reference/reference.html


9126
2017-10-23 21:16


起源

我很惊讶他们没有提供使用DER表示的工具(另见“ASN.1”和“X.509”),因为如果你不经常这样做,它真的很复杂。 - Donal Fellows
我惊讶地发现Cocoa无法获得这些重要信息,我不得不“深入”并使用CF ......我将看看我可以从DER中提取的内容;复杂与否必须要做...... - Alexandros Chalatsis


答案:


你可以像这样获得sha1指纹。

// #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]]; 
}

可以以类似的方式获得md5指纹。以这种方式获得的sha1和md5哈希值与Safari和Chrome显示的指纹相匹配,以获得不受信任的证书。


13
2017-12-16 14:54



有没有办法获取证书的开始和到期日期。如果是,请分享代码。提前致谢。 - Shiv Jaiswal