年前的时候,关于苹果要强制https的传言四起,虽然结果只是一个“谣言”,但是很明显的这是迟早会到来的,间接上加速了各公司加紧上https的节奏,对于iOS客户端来说,上https需不需要改变一些东西取决于---------对,就是公司有没有钱。土豪公司直接买买买,iOS开发者只需要把http改成https完事。然而很不幸,我们在没钱的公司,选择了自签证书。虽然网上很多关于https的适配,然而很多都是已过时的,这里我们主要是讲一下https双向认证。
【证书选择】自签
【网络请求】原生NSURLSession或者AFNetworking3.0以上版本
【认证方式】双向认证
Https双向认证过程
先来了解一下双向认证的大体过程:(图片来自网络,如果是某位博主原创的请私信我)
下面我们一步步来实现
1、设置服务端证书
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;
2、处理挑战
原生的NSURLSession是在
- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(nonnull NSURLAuthenticationChallenge *)challenge completionHandler:(nonnull void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler
代理方法里面处理挑战的,再看看AFNetworking在该代理方法里处理的代码
if (self.taskDidReceiveAuthenticationChallenge) { disposition=self.taskDidReceiveAuthenticationChallenge(session, task, challenge, &credential); } else { ... }
我们只需要给它传递一个处理的block
[self.afnetworkingManager setSessionDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition(NSURLSession*session, NSURLAuthenticationChallenge *challenge, NSURLCredential *__autoreleasing*_credential) { ... }
根据传来的challenge生成disposition(应对挑战的方式)和credential(客户端生成的挑战证书)
3、服务端认证
当challenge的认证方法为NSURLAuthenticationMethodServerTrust时,需要客户端认证服务端证书
//评估服务端安全性 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; }
4、客户端认证
认证完服务端后,需要认证客户端
由于是双向认证,这一步是必不可省的
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; } }
+ (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; }
原生NSURLSession双向认证
在原生的代理方法里面认证就行,代码基本和AFNetworking的一致,注意最后需要调用
completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
来执行回调操作
关于UIWebView的Https双向认证
网上的资料大体上有几种解决方法
1:跳过Https认证(这还能跳过?没试过,不太靠谱)