在基于服务器采用https通讯时候,客户端通过获取服务器的证书,进行一系列验证,那么应该如何获取服务器的证书呢?
可以通过以下代码实现
#import "ViewController.h"
@interface ViewController ()<NSURLSessionDelegate>
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
其中以https://www.baidu.com为例
NSURL *testURL = [NSURL URLWithString:@"https://www.baidu.com"]
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
NSURLSessionDataTask *task = [session dataTaskWithRequest:[NSURLRequest requestWithURL:testURL]];
[task resume];
}
#pragma mark - NSURLSessionDelegate
- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * __nullable credential))completionHandler{
SecTrustRef serverTrust = challenge.protectionSpace.serverTrust;
NSArray *serverCertificates = CertificateTrustChainForServerTrust(serverTrust);
获取服务器证书
NSString *base64string = [serverCertificates[0] base64EncodedStringWithOptions:0];
NSLog(@"证书---%@",base64string);
}
static NSArray * CertificateTrustChainForServerTrust(SecTrustRef serverTrust) {
CFIndex certificateCount = SecTrustGetCertificateCount(serverTrust);
NSMutableArray *trustChain = [NSMutableArray arrayWithCapacity:(NSUInteger)certificateCount];
for (CFIndex i = 0; i < certificateCount; i++) {
SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, i);
[trustChain addObject:(__bridge_transfer NSData *)SecCertificateCopyData(certificate)];
}
return [NSArray arrayWithArray:trustChain];
}
@end