公司有个项目是金融类Web APP.UIWebView的壳子,内部嵌套html.这也是国内最近流行起来的开发模式.
项目是手机银行,所以为了提高安全性,iOS原生端加了服务端证书校验功能,下面开始进入正题!
星爷镇楼尽管Https协议能够提供数据的加密、身份的认证等安全服务,但并不是没有漏洞。HTTPS协议安全隐患的存在可能使用户受到各种极具破坏力的网络攻击。其中中间人攻击(Man In The Middle, MITM)就是非常危险的一种攻击方式。
思想:将服务器信任的证书导入项目里面,每一次的网络请求都要校验是不是服务端信任的证书.否则终止网页加载!
欲哭无泪,只能学习步骤1:通过谷歌浏览器获取信任证书
步骤2:直接上代码
2.1.协议遵守
@interface TargetViewController : UIViewController<UIWebViewDelegate, NSURLConnectionDelegate, NSURLConnectionDataDelegate>
2.2.将信任证书添加到数组中
NSArray *trustCerts = [NSMutableArray arrayWithObjects: @"TrustAsiaTLSRSACA.crt",@"gsorganizationvalsha2g2r1.crt", nil];
self.trustedCerts = [NSMutableArray array];
for(NSString*fileintrustCerts) {
NSString*fpath = [[NSBundlemainBundle]pathForResource:fileofType:nil];
NSData* cerData = [NSDatadataWithContentsOfFile:fpath];
SecCertificateRefcertificate =SecCertificateCreateWithData(NULL, (__bridgeCFDataRef)(cerData));
[self.trustedCertsaddObject:CFBridgingRelease(certificate)];
}
2.3:添加Https站点处理逻辑
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType
{
NSLog(@"Did start loading: %@ auth:%d", [[request URL] absoluteString], _authenticated);
NSURL*url1 = [requestURL];
NSString*schema = [[url1scheme]lowercaseString];
//未有过证书验证,将失败的请求纪录下来
if([schemaisEqualToString:@"https"]){
if(!_authenticated) {
NSLog(@"Authenticated failed!");
[self.indexWebViewstopLoading];
[[[NSURLConnectionalloc]initWithRequest:requestdelegate:self]start] ;
returnNO;
}
}
return YES;
}
2.4:实现证书验证
- (void)connection:(NSURLConnection*)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge*)challenge;
{
NSLog(@"WebController Got auth challange via NSURLConnection");
if([challengepreviousFailureCount] ==0)
{
_authenticated = YES;
NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
[challenge.senderuseCredential:credentialforAuthenticationChallenge:challenge];
}else
{
[[challengesender] cancelAuthenticationChallenge:challenge];
}
}
- (void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)response;
{
NSLog(@"WebController received response via NSURLConnection");
_authenticated = YES;
[self.indexWebView loadRequest:_request];
[_urlConnection cancel];
}
如有问题,请留言评论! WKWebView的证书校验,有实现了或者想实现的话,一起研究下啊!
感谢论坛作者:http://www.cnblogs.com/lijizhuang/p/4884868.html
感谢家里的老父老母!
再次鄙视我的SB室友!
有点想念没良心的前女友了!
网友评论