參考文章 iOS獲取SSL證書的sha1值和sha256值 感謝作者!
首先我們可以通過瀏覽器查看遠程https的sha256或者sha1
通過代碼獲取方法如下
初始化NSURLSession對象時指定代理
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc]init]];
實現(xiàn)如下代理方法
- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler
{
SecTrustRef serverTrust = [[challenge protectionSpace] serverTrust];
//這里取第一個值的論證,其實我沒找到,只是查到的都是取第一個值.如果有看到取第一個值的文獻,麻煩推薦一下.
SecCertificateRef certRef = SecTrustGetCertificateAtIndex(serverTrust, 0);
// CFStringRef certSummary = SecCertificateCopySubjectSummary(certRef);
CFDataRef certData = SecCertificateCopyData(certRef);
//此處CFDataRef可直接強轉(zhuǎn)NSData類型
NSData *myData = (__bridge NSData *)certData;
NSString *sha256 = [self sha256:myData];
NSLog(@"sha256=%@\n ---- certificateNo=%@",sha256,[YZTLoanDoor share].certificateNo);
BOOL result = [sha256 compare:remoteCerSha256 options:NSCaseInsensitiveSearch];(忽略大小寫的字符串對比)
if (result == NSOrderedSame) {
NSURLCredential *card = [[NSURLCredential alloc]initWithTrust:challenge.protectionSpace.serverTrust];
completionHandler(NSURLSessionAuthChallengeUseCredential , card);
} else {
NSURLCredential *card = [[NSURLCredential alloc]initWithTrust:challenge.protectionSpace.serverTrust];
completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge , card);
}
}
引入頭文件
#import <CommonCrypto/CommonDigest.h>
實現(xiàn)方法
- (NSString*)sha256:(NSData*)certData
{
unsigned char sha256Buffer[CC_SHA256_DIGEST_LENGTH];
CC_SHA256(certData.bytes, certData.length, sha256Buffer);
NSMutableString *fingerprint = [NSMutableString stringWithCapacity:CC_SHA256_DIGEST_LENGTH * 3];
for (int i = 0; i < CC_SHA256_DIGEST_LENGTH; ++i)
[fingerprint appendFormat:@"%02x",sha256Buffer[i]];
return [fingerprint stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
}
當(dāng)然如果需要sha1,使用一下方法
+(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]];
}