證書信息可以使用NSURLConnection的委託方法獲得:
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
即:
- (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」數據中。問題是,目前我不知道如何從這樣的數據中提取信息(截止日期,公鑰,...),所以任何幫助都會受到歡迎。
非常感謝您的代碼! 我目前正在嘗試使用UIWebView控制器通過HTTPS連接對服務器證書進行指紋驗證。 我打算使用OpenSSL函數來完成剩餘的驗證。一旦擁有了certData,就可以使用OpenSSL解析X509證書並執行剩餘的驗證。 讓OpenSSL進入你的項目可能有點麻煩。 – Pada