iOS积累用之iOS-学习笔记程序员技术栈

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

2016-12-30  本文已影响797人  马戏团小丑
即使苹果已经推迟ATS,但是也是早晚的事,此次就根据项目记录项目中是怎么支持https自建证书的

转.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

+ (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;
    }];
}
[self.imageV sd_setImageWithURL:[NSURL URLWithString:item.photo_source] placeholderImage:nil options:SDWebImageAllowInvalidSSLCertificates];
@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
上一篇下一篇

猜你喜欢

热点阅读