iOS开发探索-HTTPS传输签名证书的获取

在基于服务器采用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
获取的服务器证书

在此感谢各位读者的来访,您的关注是我写作分享的最大动力。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容