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

作者: 零距离仰望星空 | 来源:发表于2016-02-18 17:29 被阅读1102次
在基于服务器采用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
获取的服务器证书

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

相关文章

网友评论

  • 零距离仰望星空:你是想要验证服务器证书吗?我这里是把读取到的服务器的证书转换为 Base64字符串了
    bb24b3ea3d00:@零距离仰望星空 不是,我现在是想要获取证书里面的信息,要在页面里展示出来。
  • bb24b3ea3d00:楼主,我想问一下怎么获取证书中的信息,比如说:证书的序列号,证书的有效期等等。
    你这里打印出来这样的字符串,根本看不懂里面有什么信息啊
  • wxx8888:大神,如果是自签字证书呢,怎么才能像NSURLConnettion一样,用app本地证书来验证服务器证书呢?
    零距离仰望星空:@王宗寿 不好意思 这个没有研究过

本文标题:iOS开发探索-HTTPS传输签名证书的获取

本文链接:https://www.haomeiwen.com/subject/hnimkttx.html