iOS实用篇:Https双向认证

dzfeibao 7年前
   <p>年前的时候,关于苹果要强制https的传言四起,虽然结果只是一个“谣言”,但是很明显的这是迟早会到来的,间接上加速了各公司加紧上https的节奏,对于iOS客户端来说,上https需不需要改变一些东西取决于---------对,就是公司有没有钱。土豪公司直接买买买,iOS开发者只需要把http改成https完事。然而很不幸,我们在没钱的公司,选择了自签证书。虽然网上很多关于https的适配,然而很多都是已过时的,这里我们主要是讲一下https双向认证。</p>    <p>【证书选择】自签</p>    <p>【网络请求】原生NSURLSession或者AFNetworking3.0以上版本</p>    <p>【认证方式】双向认证</p>    <p>Https双向认证过程</p>    <p>先来了解一下双向认证的大体过程:(图片来自网络,如果是某位博主原创的请私信我)</p>    <p><img src="https://simg.open-open.com/show/8f533165845017740287b671831f357d.png"></p>    <p>httpsLine.png</p>    <p>下面我们一步步来实现</p>    <p>1、设置服务端证书</p>    <pre>  <code class="language-objectivec">NSString *certFilePath = [[NSBundle mainBundle] pathForResource:@"server" ofType:@"cer"];      NSData *certData = [NSData dataWithContentsOfFile:certFilePath];      NSSet *certSet = [NSSet setWithObject:certData];      AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate withPinnedCertificates:certSet];      policy.allowInvalidCertificates = YES;      policy.validatesDomainName = NO;      self.afnetworkingManager.securityPolicy = policy;</code></pre>    <p>2、处理挑战</p>    <p>原生的NSURLSession是在</p>    <pre>  <code class="language-objectivec">- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(nonnull NSURLAuthenticationChallenge *)challenge completionHandler:(nonnull void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler</code></pre>    <p>代理方法里面处理挑战的,再看看AFNetworking在该代理方法里处理的代码</p>    <pre>  <code class="language-objectivec">if (self.taskDidReceiveAuthenticationChallenge) {          disposition = self.taskDidReceiveAuthenticationChallenge(session, task, challenge, &credential);      } else {          ...      }</code></pre>    <p>我们只需要给它传递一个处理的block</p>    <pre>  <code class="language-objectivec">[self.afnetworkingManager setSessionDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition(NSURLSession*session, NSURLAuthenticationChallenge *challenge, NSURLCredential *__autoreleasing*_credential) {          ...  }</code></pre>    <p>根据传来的challenge生成disposition(应对挑战的方式)和credential(客户端生成的挑战证书)</p>    <p>3、服务端认证</p>    <p>当challenge的认证方法为NSURLAuthenticationMethodServerTrust时,需要客户端认证服务端证书</p>    <pre>  <code class="language-objectivec">//评估服务端安全性  if([weakSelf.afnetworkingManager.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;              }</code></pre>    <p>4、客户端认证</p>    <p>认证完服务端后,需要认证客户端</p>    <p>由于是双向认证,这一步是必不可省的</p>    <pre>  <code class="language-objectivec">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 ([[weakSelf class]extractIdentity:&identity andTrust:&trust fromPKCS12Data:PKCS12Data])                  {                      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;                  }              }</code></pre>    <pre>  <code class="language-objectivec">+ (BOOL)extractIdentity:(SecIdentityRef*)outIdentity andTrust:(SecTrustRef *)outTrust fromPKCS12Data:(NSData *)inPKCS12Data {      OSStatus securityError = errSecSuccess;      //client certificate password      NSDictionary*optionsDictionary = [NSDictionary dictionaryWithObject:@"your p12 file pwd"                                                                   forKey:(__bridge id)kSecImportExportPassphrase];        CFArrayRef items = CFArrayCreate(NULL, 0, 0, NULL);      securityError = SecPKCS12Import((__bridge CFDataRef)inPKCS12Data,(__bridge CFDictionaryRef)optionsDictionary,&items);        if(securityError == 0) {          CFDictionaryRef myIdentityAndTrust =CFArrayGetValueAtIndex(items,0);          const void*tempIdentity =NULL;          tempIdentity= CFDictionaryGetValue (myIdentityAndTrust,kSecImportItemIdentity);          *outIdentity = (SecIdentityRef)tempIdentity;          const void*tempTrust =NULL;          tempTrust = CFDictionaryGetValue(myIdentityAndTrust,kSecImportItemTrust);          *outTrust = (SecTrustRef)tempTrust;      } else {          NSLog(@"Failedwith error code %d",(int)securityError);          return NO;      }      return YES;  }</code></pre>    <p>原生NSURLSession双向认证</p>    <p>在原生的代理方法里面认证就行,代码基本和AFNetworking的一致,注意最后需要调用</p>    <pre>  <code class="language-objectivec">completionHandler(NSURLSessionAuthChallengeUseCredential, credential);</code></pre>    <p>来执行回调操作</p>    <p>关于UIWebView的Https双向认证</p>    <p>网上的资料大体上有几种解决方法</p>    <p>1:跳过Https认证(这还能跳过?没试过,不太靠谱)</p>    <p>2:中断原有的请求步骤,将request拿出来,下载完整的HTML代码,让webView加载该代码(在单页面展示的情况下基本满足使用,但是在部分标签不是独立跳转https路径的时候,将出现无法加载的情况,不是很好用)</p>    <pre>  <code class="language-objectivec">- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {      NSString * urlString = [request.URL absoluteString];      if ([urlString containsString:URL_API_BASE]) {          [[SUHTTPOperationManager manager]REQUEST:request progress:nil handler:^(BOOL isSucc, id responseObject, NSError *error) {              NSString * htmlString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];              BASE_INFO_FUN(@"下载HTML完毕");              [self loadHTMLString:htmlString baseURL:nil];          }];          return NO;      }      return YES;  }</code></pre>    <p>3、中断原有的请求步骤,将request拿出来,完成鉴权认证之后,再让webView重新请求该request(这种方式理论上好像可以,我试过,没有成功,可能我打开的方式不正确)</p>    <p>4、或许,您有更好的解决方案 - -</p>    <p>关于代码</p>    <p>网上很多https双向认证的代码,基本是一样的,这里我们直接拿来用就可以,前提是我们不能单纯copy,而是在理解其实现的基础上,整合到工程中,遇到问题解决思路清晰,而不是一脸懵逼。</p>    <p>PS:大半年没更新文章了,也没怎么上简书,发现还是有很多人支持的,有朋友的私信也没回复,表示歉意。接下来如果可以我会试着分享一下FFmpeg编解码原理代码的个人理解(虽然我也是新手),最后坐标广州,寻找更好的机会,求带哦</p>    <p> </p>    <p>来自:http://www.jianshu.com/p/72bf60b5f94d</p>    <p> </p>