偷偷摘套内射激情视频,久久精品99国产国产精,中文字幕无线乱码人妻,中文在线中文a,性爽19p

iOS AFNetworking框架HTTPS請求配置

移動開發(fā) iOS
iOS在Apple公司的強制要求下,數(shù)據(jù)傳輸必須按照ATS(App Transefer Security)條款。關(guān)于AFNetworking框架傳輸HTTPS數(shù)據(jù)。

iOS AFNetworking框架HTTPS請求配置

【引自IamOkay的博客】 iOS在Apple公司的強制要求下,數(shù)據(jù)傳輸必須按照ATS(App Transefer Security)條款。關(guān)于AFNetworking框架傳輸HTTPS數(shù)據(jù)。

一.AllowsArbitraryLoads 白名單機制

NSAllowsArbitraryLoads是ATS推廣過程中的產(chǎn)物,當(dāng)然也許可持續(xù)很久甚至永久,為了訪問HTTP服務(wù),一般需要繞過ATS限制,需要配置info.plist文件

  1. <key>NSAppTransportSecurity</key
  2. <dict> 
  3.         <key>NSAllowsArbitraryLoads</key
  4.         <true/> 
  5.  </dict>  

這種機制實際上是允許了所有HTTP 和HTTPS的訪問,顯然,這種做法實際上很危險。設(shè)置為false就能避免繞開ATS,問題是我們真的需要完全關(guān)閉這個選項么?

比如某些文件服務(wù)器,CDN服務(wù)器配置HTTPS反而影響傳輸速度,這種情況下HTTP反而具有很高的優(yōu)越性。因此,對于這類服務(wù)器的HTTP傳輸,我們其實也可以使用如下方式(設(shè)置白名單),白名單之外的必須使用HTTPS協(xié)議。

  1. <key>NSAppTransportSecurity</key
  2.     <dict> 
  3.         <key>NSExceptionDomains</key
  4.         <dict> 
  5.             <key>lib.baidu.com</key
  6.             <dict> 
  7.                 <key>NSIncludesSubdomains</key
  8.                 <true/> 
  9.             </dict> 
  10.             <key>oss.fastdfs.cn</key
  11.             <dict> 
  12.                 <key>NSIncludesSubdomains</key
  13.                 <true/> 
  14.             </dict> 
  15.            </dict> 
  16.    </dict>  

二.免證書驗證

免證書驗證,一般來說是client證書庫不會把server傳輸來的證書進行校驗。

舉個例子

  1. AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; 
  2. //允許非權(quán)威機構(gòu)頒發(fā)的證書 
  3. manager.securityPolicy.allowInvalidCertificates = YES; 
  4. //也不驗證域名一致性 
  5. manager.securityPolicy.validatesDomainName = NO
  6. //關(guān)閉緩存避免干擾測試 
  7. manager.requestSerializer.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData; 
  8.  
  9. [manager GET:@"https://www.baidu.com/s?wd=https" parameters:nil progress:nil  
  10. success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) { 
  11.         NSLog(@"%@",responseObject); 
  12.     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { 
  13.         NSLog(@"%@",error); 
  14. }];  

這種方式導(dǎo)致我們的app容易遭到中間人攻擊,原因并不完全是我們設(shè)置了allowInvalidCertificates=YES 和validatesDomainName=NO,而是本地證書庫中沒有添加server的CA證書,只要是任意的https都能偽造為服務(wù)器。

因此,我們并不推薦使用這種方式。

三.證書驗證

3.1 加密標準分類

證書驗證分為2類,一類是單向認證,一類是雙認證。

此外,我們還需要區(qū)分證書與證書庫的區(qū)別,證書庫類型包括PKCS12,JKS,BKS等,其中,PKCS12是互聯(lián)網(wǎng)標準,可以跨平臺跨語言(支持Android,iOS,WP,PC,JAVA,PHP...),JKS是Java標準,只能在Java平臺和Java語言下使用,BKS是 Bouncy Castle公司的加密標準,作為Android平臺支持SSL/TLS加密套件PKCS12的補充,其加密強度很高,但是目前只用于Android平臺。證書的定義是保存在證書庫中的數(shù)字簽名信息或者單獨的證書文件,如crt,pem,cer等文件。在說加密之前,先來看看自簽名證書。

3.2 自簽名證書 vs 第三方權(quán)威機構(gòu)證書

有人可能會有疑問,自簽名證書和第三方權(quán)威機構(gòu)的證書的效用是否一樣?

實際上本人認為完全一樣,在互聯(lián)網(wǎng)中,基于B/S架構(gòu)的服務(wù)中,B端通常導(dǎo)入了第三方權(quán)威機構(gòu)的根證書(ROOT CA),實際上就是為了驗證網(wǎng)站的CA證書是不是安全的,并且驗證是不是由權(quán)威的安全機構(gòu)簽發(fā)的證書。問題是,我們的App與Server是C/S架構(gòu),每個app最多也就只能訪問有限的幾個網(wǎng)址,我們自己做的app實際上本身就是信任自己的所設(shè)置的站點URL的,也就是說我們自己人相信自己人。我們的證書只是為了數(shù)據(jù)安全傳輸,不被中間人攻擊,因此完全沒必要使用(ROOT CA),但是具體來說,到目前為止也沒人試過這種方式是否可以通過審核。

我試圖找第三方CA證書機構(gòu)交流,貌似他只是說這是蘋果的規(guī)定,實際上自簽名證書本質(zhì)上沒什么問題,只要密鑰長度,復(fù)雜度,加密方式等達到要求即可。

因此,蘋果如果真的要求必須使用第三方CA ROOT簽名的規(guī)則,本身是不合理的。這些問題也沒法避免,不過,如果蘋果允許自簽名證書的話,設(shè)置allowInvalidCertificates=YES即可。

3.3 單向認證

需要準備的文件:服務(wù)端證書庫 , 服務(wù)端導(dǎo)出的證書

單向認證,實際上說的是只有Client端對Server端的證書進行驗證,Server不需要驗證Client端的證書。

自定義類:MyAFNetworking

  1. + (AFHTTPSessionManager *)manager; 
  2.     static AFHTTPSessionManager *shareInstance = nil; 
  3.     static dispatch_once_t onceToken; 
  4.     dispatch_once(&onceToken, ^{ 
  5.  
  6.         NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; 
  7.         shareInstance = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:BaseHttpURLString] sessionConfiguration:configuration]; 
  8.         //設(shè)置請求參數(shù)的類型:JSON 
  9.         shareInstance.requestSerializer = [AFJSONRequestSerializer serializer]; 
  10.         //設(shè)置服務(wù)器返回結(jié)果的類型:JSON (AFJSONResponseSerializer,AFHTTPResponseSerializer) 
  11.         shareInstance.responseSerializer = [AFJSONResponseSerializer serializer]; 
  12.         //設(shè)置請求的超時時間 
  13.         shareInstance.requestSerializer.timeoutInterval = 20.0f; 
  14.         //設(shè)置ContentType 
  15.         shareInstance.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", @"text/json", @"text/plain", @"text/javascript", @"text/xml", @"image/jpeg",@"image/png", nil]; 
  16.  
  17.         // https配置 
  18.         NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"你的證書名" ofType:@"cer"]; 
  19.         NSData *certData = [NSData dataWithContentsOfFile:cerPath]; 
  20.         AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate withPinnedCertificates:[[NSSet alloc] initWithObjects:certData, nil]]; 
  21.  
  22.         NSSet *dataSet = [[NSSet alloc] initWithObjects:certData, nil]; //這里可以添加多個server的證書 
  23.  
  24.         // setPinnedCertificates 設(shè)置證書文件(可能不止一個證書) 
  25.         [securityPolicy setPinnedCertificates:dataSet]; 
  26.         // allowInvalidCertificates 是否允許無效證書 
  27.         [securityPolicy setAllowInvalidCertificates:NO]; 
  28.         // validatesDomainName 是否需要驗證域名 
  29.         [securityPolicy setValidatesDomainName:YES]; 
  30.  
  31.         shareInstance.securityPolicy = securityPolicy; 
  32.     }); 
  33.     return shareInstance; 

注意:以上說的證書是從服務(wù)器端到處的cer或者crt證書,這類證書是X509 Der格式的二進制編碼證書,不是X509 PAM格式的Base64編碼證書,關(guān)于自簽名證書的生成請參考如下地址

常見證書格式及相互轉(zhuǎn)換

iOS非對稱加解密

iOS 自簽名證書建立(self-signed)

3.4 雙向認證

iOS和Android一樣,客戶端證書庫類型可以是PKCS12類型的pfx證書,此類證書包含私鑰,公鑰和證書,并且由密碼。

雙向認證一般用于安全要求比較高的產(chǎn)品,比如金融類app,政府a(chǎn)pp等特殊行業(yè)。

需要準備的文件:服務(wù)端證書庫,服務(wù)端證書信任庫 , 服務(wù)端導(dǎo)出的證書,客戶端證書庫,客戶端證書

注[1]:服務(wù)端證書庫可以和服務(wù)端信任證書庫使用同一個證書庫,唯一要做的是把客戶端證書導(dǎo)入進行。

注[2]:客戶端證書一般使用跨平臺的PKCS12證書庫(pfx或p12),必須記住證書庫密鑰,此類證書庫同時包含私鑰,公鑰和證書。

3.4.1 信任服務(wù)器

本步驟用來校驗客戶端證書,和單向認證完全相同

自定義類:MyAFNetworking

  1. + (AFHTTPSessionManager *)manager; 
  2.     static AFHTTPSessionManager *shareInstance = nil; 
  3.     static dispatch_once_t onceToken; 
  4.     dispatch_once(&onceToken, ^{ 
  5.  
  6.         NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; 
  7.         shareInstance = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:BaseHttpURLString] sessionConfiguration:configuration]; 
  8.         //設(shè)置請求參數(shù)的類型:JSON 
  9.         shareInstance.requestSerializer = [AFJSONRequestSerializer serializer]; 
  10.         //設(shè)置服務(wù)器返回結(jié)果的類型:JSON (AFJSONResponseSerializer,AFHTTPResponseSerializer) 
  11.         shareInstance.responseSerializer = [AFJSONResponseSerializer serializer]; 
  12.         //設(shè)置請求的超時時間 
  13.         shareInstance.requestSerializer.timeoutInterval = 20.0f; 
  14.         //設(shè)置ContentType 
  15.         shareInstance.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", @"text/json", @"text/plain", @"text/javascript", @"text/xml", @"image/jpeg",@"image/png", nil]; 
  16.  
  17.         // https配置 
  18.         NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"你的證書名" ofType:@"cer"]; 
  19.         NSData *certData = [NSData dataWithContentsOfFile:cerPath]; 
  20.         AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate withPinnedCertificates:[[NSSet alloc] initWithObjects:certData, nil]]; 
  21.  
  22.         NSSet *dataSet = [[NSSet alloc] initWithObjects:certData, nil]; //這里可以添加多個server的證書 
  23.  
  24.         // setPinnedCertificates 設(shè)置證書文件(可能不止一個證書) 
  25.         [securityPolicy setPinnedCertificates:dataSet]; 
  26.         // allowInvalidCertificates 是否允許無效證書 
  27.         [securityPolicy setAllowInvalidCertificates:NO]; 
  28.         // validatesDomainName 是否需要驗證域名 
  29.         [securityPolicy setValidatesDomainName:YES]; 
  30.  
  31.         shareInstance.securityPolicy = securityPolicy; 
  32.     }); 
  33.     return shareInstance; 

 3.4.2 提供客戶端證書和證書庫

  1. /* 
  2. ** 
  3. * 創(chuàng)建服務(wù)器信任客戶端的認證條件 
  4. ** 
  5. */ 
  6. +(AFHTTPSessionManager *) createCredentialsClient 
  7. __block AFHTTPSessionManager * manager = [MyAFNetworking manager]; 
  8. [manager setSessionDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition(NSURLSession*session, NSURLAuthenticationChallenge *challenge, NSURLCredential *__autoreleasing*_credential) { 
  9.     NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling; 
  10.     __autoreleasing NSURLCredential *credential =nil; 
  11.     if([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) { 
  12.         if([manager.securityPolicy evaluateServerTrust:challenge.protectionSpace.serverTrust forDomain:challenge.protectionSpace.host]) { 
  13.             credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]; 
  14.             if(credential) { 
  15.                 disposition =NSURLSessionAuthChallengeUseCredential; 
  16.             } else { 
  17.                 disposition =NSURLSessionAuthChallengePerformDefaultHandling; 
  18.             } 
  19.         } else { 
  20.             disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge; 
  21.         } 
  22.     } else { 
  23.         // client authentication 
  24.         SecIdentityRef identity = NULL
  25.         SecTrustRef trust = NULL
  26.         NSString *p12 = [[NSBundle mainBundle] pathForResource:@"client"ofType:@"pfx"]; 
  27.         NSFileManager *fileManager =[NSFileManager defaultManager]; 
  28.  
  29.         if(![fileManager fileExistsAtPath:p12]) 
  30.         { 
  31.             NSLog(@"client.p12:not exist"); 
  32.         } 
  33.         else 
  34.         { 
  35.             NSData *PKCS12Data = [NSData dataWithContentsOfFile:p12]; 
  36.             #加載PKCS12證書,pfx或p12 
  37.             if ([MyAFNetworking extractIdentity:&identity andTrust:&trust fromPKCS12Data:PKCS12Data]) 
  38.             { 
  39.                 SecCertificateRef certificate = NULL
  40.                 SecIdentityCopyCertificate(identity, &certificate); 
  41.                 const void*certs[] = {certificate}; 
  42.                 CFArrayRef certArray =CFArrayCreate(kCFAllocatorDefault, certs,1,NULL); 
  43.                 credential =[NSURLCredential credentialWithIdentity:identity certificates:(__bridge  NSArray*)certArray persistence:NSURLCredentialPersistencePermanent]; 
  44.                 disposition =NSURLSessionAuthChallengeUseCredential; 
  45.             } 
  46.         } 
  47.     } 
  48.     *_credential = credential; 
  49.     return disposition; 
  50. }]; 
  51.  
  52. return manager; 
  53.  
  54. /** 
  55. **加載PKCS12證書,pfx或p12 
  56. **  
  57. **/ 
  58. +(BOOL)extractIdentity:(SecIdentityRef*)outIdentity andTrust:(SecTrustRef *)outTrust fromPKCS12Data:(NSData *)inPKCS12Data { 
  59.     OSStatus securityError = errSecSuccess; 
  60.     //client certificate password 
  61.     NSDictionary*optionsDictionary = [NSDictionary dictionaryWithObject:@"你的p12密碼" 
  62.                                                                 forKey:(__bridge id)kSecImportExportPassphrase]; 
  63.  
  64.     CFArrayRef items = CFArrayCreate(NULL, 0, 0, NULL); 
  65.     securityError = SecPKCS12Import((__bridge CFDataRef)inPKCS12Data,(__bridge CFDictionaryRef)optionsDictionary,&items); 
  66.  
  67.     if(securityError == 0) { 
  68.         CFDictionaryRef myIdentityAndTrust =CFArrayGetValueAtIndex(items,0); 
  69.         const void*tempIdentity =NULL
  70.         tempIdentity= CFDictionaryGetValue (myIdentityAndTrust,kSecImportItemIdentity); 
  71.         *outIdentity = (SecIdentityRef)tempIdentity; 
  72.         const void*tempTrust =NULL
  73.         tempTrust = CFDictionaryGetValue(myIdentityAndTrust,kSecImportItemTrust); 
  74.         *outTrust = (SecTrustRef)tempTrust; 
  75.     } else { 
  76.         NSLog(@"Failedwith error code %d",(int)securityError); 
  77.         return NO
  78.     } 
  79.     return YES; 

 通過以上方式,我們便能實現(xiàn)雙向認證了 

  1. AFHTTPSessionManager * manager = [MyAFNetworking createCredentialsClient];  
責(zé)任編輯:龐桂玉 來源: IamOkay的博客
相關(guān)推薦

2018-05-03 19:14:23

iOS開發(fā)框架API

2014-07-18 10:00:41

AFNetworkin

2024-03-26 12:08:20

加密NginxHTTP

2022-10-13 13:21:58

系統(tǒng)httpsCharles

2021-11-09 09:43:52

鴻蒙HarmonyOS應(yīng)用

2015-08-27 09:46:09

swiftAFNetworkin

2015-05-18 09:44:34

2016-03-18 09:36:13

ios基礎(chǔ)框架

2012-06-01 11:10:07

iOS基本框架圖示

2018-07-30 13:19:05

網(wǎng)站HTTPHTTPS

2011-08-18 11:10:49

Core Plot框架IOS開發(fā)

2021-06-02 08:37:33

HTTPSPCI DSS合安全檢測

2020-04-09 14:02:33

NginxHttps前端

2021-07-28 23:32:09

Nginx服務(wù)器Https

2023-07-10 09:48:30

Nginx反向代理

2015-05-05 10:32:15

iOS-MVVM框架

2015-10-22 10:32:52

AFNetworkin遷移

2022-04-07 09:18:18

JettyServlet服務(wù)器

2021-05-06 16:21:55

鴻蒙HarmonyOS應(yīng)用開發(fā)

2015-08-10 10:04:28

點贊
收藏

51CTO技術(shù)棧公眾號