可以使用 NSURLConnection 委托方法获取证书信息:
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
That is:
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
BOOL result = [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
NSLog(@"<%p %@: %s line:%d> Result:%s", self, [[NSString stringWithUTF8String:__FILE__] lastPathComponent], __PRETTY_FUNCTION__, __LINE__, (result == YES) ? "YES" : "NO");
return result;
}
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
NSArray *trustedHosts = [NSArray arrayWithObject:@"encrypted.google.com"];
BOOL isAuthMethodServerTrust = [challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
NSLog(@"<%p %@: %s line:%d> Result:%s", self, [[NSString stringWithUTF8String:__FILE__] lastPathComponent], __PRETTY_FUNCTION__, __LINE__, (isAuthMethodServerTrust == YES) ? "YES" : "NO");
if (isAuthMethodServerTrust)
{
if ([trustedHosts containsObject:challenge.protectionSpace.host])
{
NSLog(@"<%p %@: %s line:%d> trustedHosts containsObject:challenge.protectionSpace.host", self, [[NSString stringWithUTF8String:__FILE__] lastPathComponent], __PRETTY_FUNCTION__, __LINE__);
NSURLCredential* urlCredential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
NSLog(@"<%p %@: %s line:%d> Url credential", self, [[NSString stringWithUTF8String:__FILE__] lastPathComponent], __PRETTY_FUNCTION__, __LINE__);
[challenge.sender useCredential:urlCredential forAuthenticationChallenge:challenge];
//Code to verify certificate info
SecTrustRef trustRef = [[challenge protectionSpace] serverTrust];
CFIndex count = SecTrustGetCertificateCount(trustRef);
for (CFIndex i = 0; i < count; i++)
{
SecCertificateRef certRef = SecTrustGetCertificateAtIndex(trustRef, i);
CFStringRef certSummary = SecCertificateCopySubjectSummary(certRef);
CFDataRef certData = SecCertificateCopyData(certRef);
NSLog(@"<%p %@: %s line:%d> Certificate summary:%@", self, [[NSString stringWithUTF8String:__FILE__] lastPathComponent], __PRETTY_FUNCTION__, __LINE__, (NSString*) certSummary);
NSLog(@"<%p %@: %s line:%d> Certificate data:%@", self, [[NSString stringWithUTF8String:__FILE__] lastPathComponent], __PRETTY_FUNCTION__, __LINE__, (NSString*) certData);
CFRelease(certData);
}
}
}
}
此代码为您提供以下与“https://encrypted.google.com”相关的信息:
在“certSummary”NSString 中证书的颁发者。
在证书的“certData”数据中。问题是,目前我不知道如何从此类数据中提取信息(到期日期、公钥……),因此欢迎任何帮助。