Https安全通信(一)

2016-12-04  本文已影响67人  jiodg45

iOS 9.0之后苹果开始要求使用Https进行通信。ATS是iOS9和OS X El Capitan的一个新特性。开启该功能后,ATS对使用NSURLConnection, CFURL或NSURLSession 等APIs 进行的网络请求默认强制使用HTTPS加密传输,目标是提高Apple 操作系统以及应用程序的安全性。苹果公司官方文章指出,https必须符合ATS要求,服务器必须支持传输层安全(TLS)协议1.2以上版本;证书必须使用SHA256或更高的哈希算法签名,并使用2048位以上RSA密钥或256位以上ECC算法等等。

https概要

https图解

https通信详解

https实践

       + (AFSecurityPolicy*)configSecurityPolicy {
         NSString *cerPath = [[NSBundle mainBundle]                 pathForResource:@"https" ofType:@"cer"];//证书的路径
         NSData *certData = [NSData dataWithContentsOfFile:cerPath];
         AFSecurityPolicy* securityPolicy = [AFSecurityPolicy    policyWithPinningMode:AFSSLPinningModeCertificate];
         securityPolicy.allowInvalidCertificates = YES;  /**如果采用三方颁发的证书,则不使用自建证书验证服务器,由三方机构验证*/
         securityPolicy.validatesDomainName = YES;
         securityPolicy.pinnedCertificates  = [NSSet setWithObject:certData];
         mgr.securityPolicy = securityPolicy;
         return securityPolicy;
         }
      + (void)configSSLChallage {
       AFHTTPSessionManager* mgr = [self shareInstance];
       __weak typeof(*&mgr)weakmgr = mgr;
       [mgr setSessionDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition(NSURLSession * _Nonnull session, NSURLAuthenticationChallenge * _Nonnull challenge, NSURLCredential *__autoreleasing  _Nullable * _Nullable credential) {
          NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling;
           __autoreleasing NSURLCredential *_credential =nil;
        
           //server 端验证:
           if([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
            NSLog(@"authorMethod:%@",challenge.protectionSpace.authenticationMethod);
            if([weakmgr.securityPolicy evaluateServerTrust:challenge.protectionSpace.serverTrust forDomain:challenge.protectionSpace.host] ) {
             
               _credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
                if(credential) {
                    disposition =NSURLSessionAuthChallengeUseCredential;
                } else {
                    disposition =NSURLSessionAuthChallengePerformDefaultHandling;
                }
               } else {
                disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge;
                }
            } else {
              //client 客户端验证:

                    NSLog(@"authorMethod:%@",challenge.protectionSpace.authenticationMethod);
            // client authentication
            SecIdentityRef identity = NULL;
            SecTrustRef trust = NULL;
            NSString *p12 = [[NSBundle mainBundle] pathForResource:@"client"ofType:@"p12"];
            NSFileManager *fileManager =[NSFileManager defaultManager];
            
            if(![fileManager fileExistsAtPath:p12])
            {
                NSLog(@"client.p12:not exist");
            }
            else
            {
                NSData *PKCS12Data = [NSData dataWithContentsOfFile:p12];
                
                if ([PLMNetWorkTool extractIdentity:&identity andTrust:&trust fromPKCS12Data:PKCS12Data])
                {
                    if (extractIdentityAndTrust((__bridge CFDataRef)(PKCS12Data), &identity, &trust)== noErr) {
                        SecCertificateRef certificate = NULL;
                        SecIdentityCopyCertificate(identity, &certificate);
                        const void*certs[] = {certificate};
                        CFArrayRef certArray =CFArrayCreate(kCFAllocatorDefault, certs,1,NULL);
                        
                        _credential =[NSURLCredential credentialWithIdentity:identity certificates:(__bridge  NSArray*)certArray persistence:NSURLCredentialPersistencePermanent];
                        disposition =NSURLSessionAuthChallengeUseCredential;
                    }
                }
            }
         }
        *credential = _credential;
        return disposition;
         }];
 
        }

总结: https涉及的内容较多,如果不明白其中的具体原理,仅仅靠搬运一份代码,那么一段出现问题将是非常致命的。理解其中的缘由对于我们应对https证书伪造,域名劫持,或是https会话秘钥扩展,https安全通信双层加固非常重要。

参考文献: http://baike.baidu.com/link?url=QDGRYuHehLYwvUSNX_vH7xo8tQ8CJoDSSKeLP_PWzmohvk5E1E6RegmRGB0hERJW_0MqTBJn6sp6h65hLi_04a
http://www.ruanyifeng.com/blog/2014/02/ssl_tls.html

上一篇下一篇

猜你喜欢

热点阅读