為您解碼網(wǎng)站建設(shè)的點(diǎn)點(diǎn)滴滴
發(fā)表日期:2016-09 文章編輯:小燈 瀏覽次數(shù):2568
由于蘋果規(guī)定2017年1月1日以后,所有APP都要使用HTTPS進(jìn)行網(wǎng)絡(luò)請求,否則無法上架,因此研究了一下在iOS中使用HTTPS請求的實(shí)現(xiàn)。相信大家對HTTPS都或多或少有些了解,這里我就不再介紹了,主要功能就是將傳輸?shù)膱?bào)文進(jìn)行加密,提高安全性。
證書分為兩種,一種是花錢向認(rèn)證的機(jī)構(gòu)購買的證書,服務(wù)端如果使用的是這類證書的話,那一般客戶端不需要做什么,用HTTPS進(jìn)行請求就行了,蘋果內(nèi)置了那些受信任的根證書的。另一種是自己制作的證書,使用這類證書的話是不受信任的(當(dāng)然也不用花錢買),因此需要我們在代碼中將該證書設(shè)置為信任證書。
我這邊使用的是xca來制作了根證書,制作流程請參考http://www.2cto.com/Article/201411/347512.html,由于xca無法導(dǎo)出.jsk的后綴,因此我們只要制作完根證書后以.p12的格式導(dǎo)出就行了,之后的證書制作由命令行來完成。自制一個(gè)批處理文件,添加如下命令:
set ip=%1%
md %ip%
keytool -importkeystore -srckeystore ca.p12 -srcstoretype PKCS12 -srcstorepass 123456 -destkeystore ca.jks -deststoretype JKS -deststorepass 123456
keytool -genkeypair -alias server-%ip% -keyalg RSA -keystore ca.jks -storepass 123456 -keypass 123456 -validity 3650 -dname "CN=%ip%, OU=ly, O=hik, L=hz, ST=zj, C=cn"
keytool -certreq -alias server-%ip% -storepass 123456 -file %ip%\server-%ip%.certreq -keystore ca.jks
keytool -gencert -alias ca -storepass 123456 -infile %ip%\server-%ip%.certreq -outfile %ip%\server-%ip%.cer -validity 3650 -keystore ca.jks?
keytool -importcert -trustcacerts -storepass 123456 -alias server-%ip% -file %ip%\server-%ip%.cer -keystore ca.jks
keytool -delete -keystore ca.jks -alias ca -storepass 123456
將上面加粗的ca.p12改成你導(dǎo)出的.p12文件的名稱,123456改為你創(chuàng)建證書的密碼。
然后在文件夾空白處按住ctrl+shift點(diǎn)擊右鍵,選擇在此處打開命令窗口,在命令窗口中輸入“start.bat ip/域名”來執(zhí)行批處理文件,其中start.bat是添加了上述命令的批處理文件,ip/域名即你服務(wù)器的ip或者域名。執(zhí)行成功后會生成一個(gè).jks文件和一個(gè)以你的ip或域名命名的文件夾,文件夾中有一個(gè).cer的證書,這邊的.jks文件將在服務(wù)端使用.cer文件將在客戶端使用,到這里證書的準(zhǔn)備工作就完成了。
由于我不做服務(wù)端好多年,只會使用Tomcat,所以這邊只講下Tomcat的配置方法,使用其他服務(wù)器的同學(xué)請自行查找設(shè)置方法。
打開tomcat/conf目錄下的server.xml文件將HTTPS的配置打開,并進(jìn)行如下配置:
<Connector URIEncoding="UTF-8" protocol="org.apache.coyote.http11.Http11NioProtocol" port="8443" maxThreads="200" scheme="https" secure="true" SSLEnabled="true" sslProtocol="TLSv1.2" sslEnabledProtocols="TLSv1.2" keystoreFile="${catalina.base}/ca/ca.jks" keystorePass="123456" clientAuth="false" SSLVerifyClient="off" netZone="你的ip或域名"/>
keystoreFile是你.jks文件放置的目錄,keystorePass是你制作證書時(shí)設(shè)置的密碼,netZone填寫你的ip或域名。注意蘋果要求協(xié)議要TLSv1.2以上。
首先把前面生成的.cer文件添加到項(xiàng)目中,注意在添加的時(shí)候選擇要添加的targets。
1.使用NSURLSession進(jìn)行請求
代碼如下:
NSString *urlString = @"https://xxxxxxx";
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10.0f];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request];
[task resume];
需要實(shí)現(xiàn)NSURLSessionDataDelegate中的URLSession:didReceiveChallenge:completionHandler:方法來進(jìn)行證書的校驗(yàn),代碼如下:
- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
?completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler {
??? NSLog(@"證書認(rèn)證");
??? if ([[[challenge protectionSpace] authenticationMethod] isEqualToString: NSURLAuthenticationMethodServerTrust]) {
??????? do
??????? {
??????????? SecTrustRef serverTrust = [[challenge protectionSpace] serverTrust];
??????????? NSCAssert(serverTrust != nil, @"serverTrust is nil");
??????????? if(nil == serverTrust)
??????????????? break; /* failed */
??????????? /**
???????????? *? 導(dǎo)入多張CA證書(Certification Authority,支持SSL證書以及自簽名的CA),請?zhí)鎿Q掉你的證書名稱
???????????? */
??????????? NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"ca" ofType:@"cer"];//自簽名證書
??????????? NSData* caCert = [NSData dataWithContentsOfFile:cerPath];??????????? NSCAssert(caCert != nil, @"caCert is nil");
??????????? if(nil == caCert)
??????????????? break; /* failed */
???????????
??????????? SecCertificateRef caRef = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)caCert);
??????????? NSCAssert(caRef != nil, @"caRef is nil");
??????????? if(nil == caRef)
??????????????? break; /* failed */
???????????
??????????? //可以添加多張證書
??????????? NSArray *caArray = @[(__bridge id)(caRef)];
???????????
??????????? NSCAssert(caArray != nil, @"caArray is nil");
??????????? if(nil == caArray)
??????????????? break; /* failed */
???????????
??????????? //將讀取的證書設(shè)置為服務(wù)端幀數(shù)的根證書
??????????? OSStatus status = SecTrustSetAnchorCertificates(serverTrust, (__bridge CFArrayRef)caArray);
??????????? NSCAssert(errSecSuccess == status, @"SecTrustSetAnchorCertificates failed");
??????????? if(!(errSecSuccess == status))
??????????????? break; /* failed */
???????????
??????????? SecTrustResultType result = -1;
??????????? //通過本地導(dǎo)入的證書來驗(yàn)證服務(wù)器的證書是否可信
??????????? status = SecTrustEvaluate(serverTrust, &result);
??????????? if(!(errSecSuccess == status))
??????????????? break; /* failed */
??????????? NSLog(@"stutas:%d",(int)status);
??????????? NSLog(@"Result: %d", result);
???????????
??????????? BOOL allowConnect = (result == kSecTrustResultUnspecified) || (result == kSecTrustResultProceed);
??????????? if (allowConnect) {
??????????????? NSLog(@"success");
??????????? }else {
??????????????? NSLog(@"error");
??????????? }??????????? /* kSecTrustResultUnspecified and kSecTrustResultProceed are success */
??????????? if(! allowConnect)
??????????? {
??????????????? break; /* failed */
??????????? }
???????????
#if 0
??????????? /* Treat kSecTrustResultConfirm and kSecTrustResultRecoverableTrustFailure as success */
??????????? /*?? since the user will likely tap-through to see the dancing bunnies */
??????????? if(result == kSecTrustResultDeny || result == kSecTrustResultFatalTrustFailure || result == kSecTrustResultOtherError)
??????????????? break; /* failed to trust cert (good in this case) */
#endif
???????????
??????????? // The only good exit point
??????????? NSLog(@"信任該證書");
???????????
??????????? NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
??????????? completionHandler(NSURLSessionAuthChallengeUseCredential,credential);
??????????? return [[challenge sender] useCredential: credential
????????????????????????? forAuthenticationChallenge: challenge];
???????????
??????? }
??????? while(0);
??? }
???
??? // Bad dog
??? NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
??? completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge,credential);
??? return [[challenge sender] cancelAuthenticationChallenge: challenge];
}
此時(shí)即可成功請求到服務(wù)端。
注:調(diào)用SecTrustSetAnchorCertificates設(shè)置可信任證書列表后就只會在設(shè)置的列表中進(jìn)行驗(yàn)證,會屏蔽掉系統(tǒng)原本的信任列表,要使系統(tǒng)的繼續(xù)起作用只要調(diào)用SecTrustSetAnchorCertificates方法,第二個(gè)參數(shù)設(shè)置成NO即可。
2.使用AFNetworking進(jìn)行請求
AFNetworking首先需要配置AFSecurityPolicy類,AFSecurityPolicy類封裝了證書校驗(yàn)的過程。
/**
?AFSecurityPolicy分三種驗(yàn)證模式:
?AFSSLPinningModeNone:只是驗(yàn)證證書是否在信任列表中
?AFSSLPinningModeCertificate:該模式會驗(yàn)證證書是否在信任列表中,然后再對比服務(wù)端證書和客戶端證書是否一致
?AFSSLPinningModePublicKey:只驗(yàn)證服務(wù)端證書與客戶端證書的公鑰是否一致
*/AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
??? securityPolicy.allowInvalidCertificates = YES;//是否允許使用自簽名證書
??? securityPolicy.validatesDomainName = NO;//是否需要驗(yàn)證域名,默認(rèn)YES??? AFHTTPSessionManager *_manager = [AFHTTPSessionManager manager];
??? _manager.responseSerializer = [AFHTTPResponseSerializer serializer];
??? _manager.securityPolicy = securityPolicy;
??? //設(shè)置超時(shí)
??? [_manager.requestSerializer willChangeValueForKey:@"timeoutinterval"];
??? _manager.requestSerializer.timeoutInterval = 20.f;
??? [_manager.requestSerializer didChangeValueForKey:@"timeoutinterval"];
??? _manager.requestSerializer.cachePolicy = NSURLRequestReloadIgnoringCacheData;
??? _manager.responseSerializer.acceptableContentTypes? = [NSSet setWithObjects:@"application/xml",@"text/xml",@"text/plain",@"application/json",nil];
?
??? __weak typeof(self) weakSelf = self;
??? [_manager setSessionDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential *__autoreleasing *_credential) {
???????
??????? SecTrustRef serverTrust = [[challenge protectionSpace] serverTrust];
??????? /**
???????? *? 導(dǎo)入多張CA證書
???????? */
??????? NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"ca" ofType:@"cer"];//自簽名證書
??????? NSData* caCert = [NSData dataWithContentsOfFile:cerPath];
??????? NSArray *cerArray = @[caCert];
??????? weakSelf.manager.securityPolicy.pinnedCertificates = cerArray;
???????
??????? SecCertificateRef caRef = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)caCert);
??????? NSCAssert(caRef != nil, @"caRef is nil");
???????
??????? NSArray *caArray = @[(__bridge id)(caRef)];
??????? NSCAssert(caArray != nil, @"caArray is nil");
???????
??????? OSStatus status = SecTrustSetAnchorCertificates(serverTrust, (__bridge CFArrayRef)caArray);
??????? SecTrustSetAnchorCertificatesOnly(serverTrust,NO);
??????? NSCAssert(errSecSuccess == status, @"SecTrustSetAnchorCertificates failed");
???????
??????? NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling;
??????? __autoreleasing NSURLCredential *credential = nil;
??????? if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
??????????? if ([weakSelf.manager.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 {
??????????? disposition = NSURLSessionAuthChallengePerformDefaultHandling;
??????? }
???????
??????? return disposition;
??? }];
上述代碼通過給AFHTTPSessionManager重新設(shè)置證書驗(yàn)證回調(diào)來自己驗(yàn)證證書,然后將自己的證書加入到可信任的證書列表中,即可通過證書的校驗(yàn)。
由于服務(wù)端使用.jks是一個(gè)證書庫,客戶端獲取到的證書可能不止一本,我這邊獲取到了兩本,具體獲取到基本可通過SecTrustGetCertificateCount方法獲取證書個(gè)數(shù),AFNetworking在evaluateServerTrust:forDomain:方法中,AFSSLPinningMode的類型為AFSSLPinningModeCertificate和AFSSLPinningModePublicKey的時(shí)候都有校驗(yàn)服務(wù)端的證書個(gè)數(shù)與客戶端信任的證書數(shù)量是否一樣,如果不一樣的話無法請求成功,所以這邊我就修改他的源碼,當(dāng)有一個(gè)校驗(yàn)成功時(shí)即算成功。
當(dāng)類型為AFSSLPinningModeCertificate時(shí)
return trustedCertificateCount == [serverCertificates count] - 1;
為AFSSLPinningModePublicKey時(shí)
return trustedPublicKeyCount > 0 && ((self.validatesCertificateChain) || (!self.validatesCertificateChain && trustedPublicKeyCount >= 1));
去掉了第二塊中的trustedPublicKeyCount == [serverCertificates count]的條件。
這邊使用的AFNetworking的版本為2.5.3,如果其他版本有不同之處請自行根據(jù)實(shí)際情況修改。
demo地址:https://github.com/fengling2300/networkTest
日期:2018-04 瀏覽次數(shù):6774
日期:2017-02 瀏覽次數(shù):3448
日期:2017-09 瀏覽次數(shù):3674
日期:2017-12 瀏覽次數(shù):3542
日期:2018-12 瀏覽次數(shù):4839
日期:2016-12 瀏覽次數(shù):4592
日期:2017-07 瀏覽次數(shù):13658
日期:2017-12 瀏覽次數(shù):3522
日期:2018-06 瀏覽次數(shù):4278
日期:2018-05 瀏覽次數(shù):4454
日期:2017-12 瀏覽次數(shù):3568
日期:2017-06 瀏覽次數(shù):3993
日期:2018-01 瀏覽次數(shù):3957
日期:2016-12 瀏覽次數(shù):3922
日期:2018-08 瀏覽次數(shù):4439
日期:2017-12 瀏覽次數(shù):3726
日期:2016-09 瀏覽次數(shù):6443
日期:2018-07 瀏覽次數(shù):3220
日期:2016-12 瀏覽次數(shù):3240
日期:2018-10 瀏覽次數(shù):3392
日期:2018-10 瀏覽次數(shù):3501
日期:2018-09 瀏覽次數(shù):3591
日期:2018-02 瀏覽次數(shù):3609
日期:2015-05 瀏覽次數(shù):3536
日期:2018-09 瀏覽次數(shù):3316
日期:2018-06 瀏覽次數(shù):3444
日期:2017-02 瀏覽次數(shù):3882
日期:2018-02 瀏覽次數(shù):4346
日期:2018-02 瀏覽次數(shù):4190
日期:2016-12 瀏覽次數(shù):3586
Copyright ? 2013-2018 Tadeng NetWork Technology Co., LTD. All Rights Reserved.