获取SSL证书详细信息

11

我想检查-(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge接收的SSL证书,以下代码片段可以给我颁发者公共名称和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

我很惊讶他们没有提供处理DER表示的工具(参见“ASN.1”和“X.509”),因为如果你不经常这样做,它真的非常复杂。 - Donal Fellows
我很惊讶地发现,这样重要的信息在Cocoa中并不可用,我必须“深入”并使用CF……我将查看我可以从DER中提取什么;无论复杂与否,都必须完成... - Alexandros Chalatsis
1个回答

13

你可以通过以下方式获取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显示的未受信任证书的指纹匹配。


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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接