项目中怎么支持https自建证书

作者: 马戏团小丑 | 来源:发表于2016-12-30 10:54 被阅读797次
即使苹果已经推迟ATS,但是也是早晚的事,此次就根据项目记录项目中是怎么支持https自建证书的
  • 后台给到的证书是.crt格式的,但是项目需要的是der格式的(AFN3.0以上支持的是.der,3.0以下支持的是.cer)


转.der采用的命令行是:
openssl x509 -in /Users/nikkilin/Desktop/server.crt -out /Users/nikkilin/Desktop/server.der -outform DER

转.cer采用的命令行是:
openssl x509 -in /Users/nikkilin/Desktop/server.crt -out /Users/nikkilin/Desktop/server.cer -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

相关文章

  • 项目中怎么支持https自建证书

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

  • iOS HTTPS自建证书的适配

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

  • nginx配置https

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

  • https:自建证书

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

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

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

  • https/tcp ssh/tls

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

  • 简单的自建ipa在线安装服务

    1.材料 (必须)支持https的站点(要么用免费证书自建,要么使用coding.net的page服务)(必须)打...

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

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

  • 基于 OpenSSL 自建 CA 和颁发 SSL 证书

    更多精彩文章https://deepzz.comDesc:基于 openssl,自建 CA,颁发证书 自建 CA ...

  • AFNetworking 3.0 支持https自建证书单向认证

    先贴上苹果中国客服电话:有什么问题都可以询问。 这是 我拨打苹果客服回复的邮件:大家可以参考下 接下来说明一些 ...

网友评论

  • NateLam:网上好像都说的是.cer, 楼主要不确认一下? 因为我也在做这个, 不是很有把握
    马戏团小丑:cer der都一样 只是afn版本支持问题 文章已补充修改
  • 1这场雨:🦄🍊
  • 仁伯:证书der么,不是cer么???
    仁伯:@CoderQun 好吧,我孤陋寡闻啦!谢谢
    马戏团小丑:要转 好像是afn支持的是der
  • Camoufleur:简单,粗暴:+1:

本文标题:项目中怎么支持https自建证书

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