iOS HTTPS自建证书的适配

作者: 苦可乐 | 来源:发表于2017-01-05 13:42 被阅读365次

即使苹果已经推迟ATS,但是也是早晚的事,此次就根据项目记录项目中是怎么支持https自建证书的

后台给到的证书是.crt格式的,但是项目需要的是der格式的
采用的命令行是:openssl x509 -in /Users/nikkilin/Desktop/server.crt -out /Users/nikkilin/Desktop/server.der -outform DER

接着将der证书拉入项目中
修改AFN网络请求工具类


+ (instancetype)sharedTools {
    static NetworkTools *instance;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [NetworkTools new];
        [instance initSessionManager];
    });
    
    return instance;
}

- (void)initSessionManager{
    _sessionManager = [AFHTTPSessionManager manager];
    _sessionManager.requestSerializer.timeoutInterval = 15;
    
    _sessionManager.requestSerializer.cachePolicy = NSURLRequestUseProtocolCachePolicy;
    _sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/plain", @"*/*", nil];
    
    AFImageDownloader *imageDownloader = [AFImageDownloader defaultInstance];
    AFHTTPSessionManager *sessionManager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:nil];
    sessionManager.responseSerializer = [AFImageResponseSerializer serializer];
    imageDownloader.sessionManager = sessionManager;
    
    [self setSecurityPolicyWithManager:_sessionManager];
    [self setSecurityPolicyWithManager:sessionManager];
    
    [UIButton setSharedImageDownloader:imageDownloader];
}

-(void) setSecurityPolicyWithManager:(AFHTTPSessionManager *)manager
{
    AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
    policy.allowInvalidCertificates = YES;// 是否允许自建证书或无效证书
    policy.validatesDomainName = NO;
    manager.securityPolicy = policy;
    
    __weak AFHTTPSessionManager *weakManager = manager;
    [manager setSessionDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition(NSURLSession * _Nonnull session, NSURLAuthenticationChallenge * _Nonnull challenge, NSURLCredential *__autoreleasing  _Nullable * _Nullable credential) {
        
        SecTrustRef serverTrust = [[challenge protectionSpace] serverTrust];
        NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"server" ofType:@"cer"];
        NSData *caData = [NSData dataWithContentsOfFile:cerPath];
        
        weakManager.securityPolicy.pinnedCertificates = [NSSet setWithObject:caData];
        
        SecCertificateRef caRef = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)caData);
        NSArray *caArray = @[(__bridge id)(caRef)];
        OSStatus status = SecTrustSetAnchorCertificates(serverTrust, (__bridge CFArrayRef)caArray);
        SecTrustSetAnchorCertificatesOnly(serverTrust,NO);
        
        if (errSecSuccess == status) {
            NSCAssert(YES, @"SecTrustSetAnchorCertificates failed");
        }
        
        NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling;
        
        if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
            
            if ([weakManager.securityPolicy evaluateServerTrust:challenge.protectionSpace.serverTrust forDomain:challenge.protectionSpace.host]) {
                //创建质询证书
                NSURLCredential * credential = [NSURLCredential credentialForTrust:serverTrust];
                
                if (credential) {
                    disposition = NSURLSessionAuthChallengeUseCredential;
                } else {
                    disposition = NSURLSessionAuthChallengePerformDefaultHandling;
                }
            } else {
                //取消质询
                disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge;
            }
        }
        
        return disposition;
    }];
}

接着常用的第三方SDWebImage就加载不了https的图片了,简单粗暴的办法就是使用sd的这个方法,忽略证书,options设置

SDWebImageAllowInvalidSSLCertificates[self.imageV sd_setImageWithURL:[NSURL URLWithString:item.photo_source] placeholderImage:nil options:SDWebImageAllowInvalidSSLCertificates];

如果嫌每个地方都要添加options麻烦,那么可以给SDWebImage添加一个Category

@implementation SDWebImageDownloader (CXXSecurityValidate)
- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
 completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler
{
    SecTrustRef serverTrust = [[challenge protectionSpace] serverTrust];
    NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"dev_merchant" ofType:@"cer"];
    NSData *caData = [NSData dataWithContentsOfFile:cerPath];
    
    SecCertificateRef caRef = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)caData);
    NSArray *caArray = @[(__bridge id)(caRef)];
    OSStatus status = SecTrustSetAnchorCertificates(serverTrust, (__bridge CFArrayRef)caArray);
    SecTrustSetAnchorCertificatesOnly(serverTrust,NO);
    
    if (errSecSuccess == status) {
        NSCAssert(YES, @"SecTrustSetAnchorCertificates failed");
    }
    
    NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling;
    
    NSURLCredential * credential = [NSURLCredential credentialForTrust:serverTrust];
    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
        
        if ([[NetworkTools sharedTools].sessionManager.securityPolicy evaluateServerTrust:challenge.protectionSpace.serverTrust forDomain:challenge.protectionSpace.host]) {
            
            if (credential) {
                disposition = NSURLSessionAuthChallengeUseCredential;
            } else {
                disposition = NSURLSessionAuthChallengePerformDefaultHandling;
            }
        } else {
            //取消质询
            disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge;
        }
    }
    if (completionHandler) {
        completionHandler(disposition, credential);
    }
}
@end

相关文章

  • iOS HTTPS自建证书的适配

    即使苹果已经推迟ATS,但是也是早晚的事,此次就根据项目记录项目中是怎么支持https自建证书的 接着将der证书...

  • iOS HTTPS自建证书验证

    前言 公司项目由HTTP转为HTTPS,需要对网络请求进行自建证书验证。主要是AFNetWorking、SDWeb...

  • https:自建证书

    苹果针对ATS逐渐收紧了政策,最近看了一些https的资料,自建证书主要用到openssl。根据苹果的政策,自建证...

  • nginx配置https

    nginx配置https自建证书 最近需要给内部服务添加https支持,首先考虑使用自建的证书来实现https的配...

  • 证书生成过程及自建CA(一)

    关键字: 自建CA, openssl, https证书,带有多域名 需求 自建CA并签发证书,可以将自建CA的根证...

  • https/tcp ssh/tls

    针对非自建证书 AFN中调整https的处理方法 GCDAsyncSocket中 TLS调整 正对自建证书使用以下...

  • 网站 ssl自建证书

    由于项目需求在某网站8数据,发现该网站用的是https自建证书,于是将证书下载下来发现是crt后缀的,但是iOS自...

  • iOS适配https证书问题 allowInvalidCerti

    近日将http转为https 1.准备证书 首先找后台要一个证书(SSL证书,一般你跟后台说要弄https,然后让...

  • 对于iOS https自建签名证书的处理

    1、验证域名2、验证域名通过,则忽略证书;域名不通过,则默认策略 参考:HTTPS(含SNI)业务场景“IP直连”...

  • 证书生成过程及自建CA(二)

    关键字: 自建CA, openssl, https证书,带有多域名 通过自建CA签发证书 准备创建目录保存新生成的...

网友评论

本文标题:iOS HTTPS自建证书的适配

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