HTTPS related
Since Apple announced January 1, 2017 the mandatory use of HTTPS, Htpps slowly become one of the objects of discussion, not to say that the previous HTTPS did not appear, but this decision to let developers unexpectedly, Bo in 15 when the interface has been HTTPS, know the depth of the pit, The reason is that their own knowledge of this area with less information on the Internet, in addition to the blog do not know the right and wrong to each other, resulting in the Internet almost can not find the code to use, this point, Bo Master said no exaggeration.
In view of this, Bo Master has always wanted to fill out this pit, add some correct code, for the vast number of developers to use, and later has been shelved, after trying, bloggers will now put together a good code published here, hoping to help the anxiously looking for the developer.
1. First of all, how did the old afnetworking2.x come true?
Bloggers in the online read a few posts, which said some of the methods are correct, but not all, because of the few blogs almost the same, Bo master is not sure who wrote the earliest, so the following method is explained below:
1) pour client.p12 certificate;
2) make configuration in plist file:
The meaning of each item represents please read this blog, Bo Master wrote very detailed: http://blog.csdn.net/zhouzhoujianquan/article/details/53401506 In addition to some instructions, the other side also provides some code, We can take each other to confirm;
3) in afnetworking, modify a class:
Find this file and add a method inside it:
-(Osstatus) Extractidentity: (cfdataref) inp12data toidentity: (secidentityref*) Identity {osstatus Securityerror = ErrS ecsuccess; Cfstringref Password = cfstr ("Certificate Password");Constvoid *keys[] = {Ksecimportexportpassphrase};Constvoid *values[] = {password}; Cfdictionaryref options = Cfdictionarycreate (null, keys, values, 1, NULL, null); Cfarrayref items = cfarraycreate (null, 0, 0, null); securityerror = Secpkcs12import (inP12Data, Options, &items); if (securityerror = 0) {Cfdictionaryref ident = Cfarraygetvalueatindex (Items,0); const void *tempidentity = NULL; Tempidentity = Cfdictionarygetvalue (ident, ksecimportitemidentity); *identity = (secidentityref) tempidentity; } if (options) {cfrelease (options);} return securityerror;}
Modify one More method:
Replace the code with the same name in nsurlconnectiondelegate with the following code,-(void) Connection: (Nsurlconnection *) Connectionwillsendrequestforauthenticationchallenge: (Nsurlauthenticationchallenge *) challenge{NSString *thepath = [[NSBundle Mainbundle] pathforresource:@"Client" oftype:@"P12"];Pour certificate NSLog (@ "thepath===========%@", thepath); NSData *pkcs12data = [[NSData alloc] initwithcontentsoffile:thepath]; Cfdataref Inpkcs12data = (__bridge cfdataref) pkcs12data; Secidentityref identity =NULL;Extract the ideneity from the certificate [Self Extractidentity:inpkcs12data toidentity:&identity]; Seccertificateref certificate =NULL; Secidentitycopycertificate (identity, &certificate);const void *certs[] = {certificate}; //Cfarrayref Certarray = Cfarraycreate (Kcfallocatordefault, certs, 1, NULL); //Create a credential from the certificate and ideneity, then reply to the challenge with the credential //nslog ( @ "identity=========%@", identity); Nsurlcredential *credential = [nsurlcredential credentialwithidentity:identity certificates:nil Persistence: Nsurlcredentialpersistencepermanent]; //credential = [nsurlcredential credentialwithidentity:identity certificates: (__bridge NSArray*) CertArray Persistence:nsurlcredentialpersistencepermanent]; [Challenge. Sender usecredential:credential Forauthenticationchallenge:challenge];}
4) Initiating the request
NSString *url = @"Xxxxxxxxxx";1. Get request Manager Afhttprequestoperationmanager *mgr = [Afhttprequestoperationmanager manager];//2 Set HTTPS request Afsecuritypolicy *securitypolicy = [Afsecuritypolicy policywithpinningmode: Afsslpinningmodecertificate]; SecurityPolicy. allowinvalidcertificates = YES; Mgr. securitypolicy = securitypolicy; //3. Send POST Request [Mgr Post:url parameters:Nil success:^ (afhttprequestoperation * _nonnull operation, ID _ Nonnull responseobject) { NSLog (@"Responseobject:%@", Responseobject);} failure:^ (Afhttprequestoperation * _ Nonnull operation, Nserror * _nonnull error) { NSLog (@"error:%@", error);}];
To this, the old version of the afnetworking request HTTPS interface two-way verification is done, but there is a problem, here need to change afnetworking code, not to mention the new afnetworking already have, in order to maintain the vitality of the code, the old should be abandoned, and update pods after the code is definitely replaced, is also a problem, do not worry, the following is how to use the new afnetworking, and solve the problem of replacing the code by Pods update.
Finally, the use of the old AF to request, only the use of the Client.p12 file, and no use of server.cer, in the new inside is useful, speculation may be the client chooses to trust any certificate caused, it becomes a one-way verification.
Demo on the Last
2. How does the new afnetworking3.x come about?
1) pour client.p12 and server.cer files
2) The settings within the plist, which are the same as above:
The meaning of each item represents please read this blog, Bo Master wrote very detailed: http://blog.csdn.net/zhouzhoujianquan/article/details/53401506 In addition to some instructions, the other side also provides some code, We can take each other to confirm;
3) There is no need to modify the code inside the class, but here is a way to rewrite it:
NSString *url = @"Https://test.niuniuhaoguanjia.com/3.0.0/?service=City.GetCityList";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; _manager = [Afhttpsessionmanager manager]; _manager. securitypolicy = policy; _manager. Requestserializer = [Afhttprequestserializer serializer]; _manager. Responseserializer = [Afhttpresponseserializer serializer]; _manager. Responseserializer. acceptablecontenttypes = [Nsset setwithobjects:@"Application/json", @"Text/json", @"Text/javascript", @"Text/plain",NIL];Turn off cache to avoid interference test R _manager. Requestserializer. CachePolicy = Nsurlrequestreloadignoringlocalcachedata; [_manager setsessiondidbecomeinvalidblock:^ (Nsurlsession * _nonnull session,Nserror * _nonnull error) {NSLog (@"Setsessiondidbecomeinvalidblock"); }];Client request validation Override Setsessiondidreceiveauthenticationchallengeblock method __Weak typeof (Self) weakself =Self [_manager setsessiondidreceiveauthenticationchallengeblock:^nsurlsessionauthchallengedisposition (NSURLSession* Session, Nsurlauthenticationchallenge *challenge, nsurlcredential *__autoreleasing*_credential) { nsurlsessionauthchallengedisposition disposition = nsurlsessionauthchallengeperformdefaulthandling; __autoreleasing nsurlcredential *credential =Nilif ([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 {Client Authentication 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; }}} *_credential = credential; return disposition;}];
About this code, in fact, and the old AF inside the reason for the change is the same, you can read this article: Http://www.jianshu.com/p/9e573607be13
4) Initiating the request
The third step and this step of code are put together, please note oh [_manager get:url parameters:Nil progress:^ (nsprogress * _nonnull downloadprogress) {} success:^ (Nsurlsessiondatatask * _nonnull task,id _nullable responseobject) {nsdictionary *dic = [Nsjsonserialization jsonobjectwithdata:responseobject Options:NS Jsonreadingmutablecontainers error:nil]; nslog (@ "JSON:%@", DIC);} failure:^ (Nsurlsessiondatatask * _ Nullable task, nserror * _nonnull error) {nslog (@ "error:%@", error); NSData *data = [Error.userinfo objectforkey:@ " Com.alamofire.serialization.response.error.data "]; nsstring *str = [[nsstring alloc]initwithdata:data encoding : Nsutf8stringencoding]; nslog (@ "%@", str);}];
Another way to do this is to add a method:
+(BOOL) Extractidentity: (secidentityref*) outidentity andtrust: (sectrustref *) outtrust frompkcs12data: (NSData *) Inpkcs12data {Osstatus securityerror = errsecsuccess;Client certificate PasswordNsdictionary*optionsdictionary = [Nsdictionary dictionarywithobject:@"Certificate Password" Forkey: (__bridgeID) ksecimportexportpassphrase]; Cfarrayref items = cfarraycreate (Null0,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;}
You'll find Http://www.jianshu.com/p/9e573607be13 the code here is redundant, yes, we're going to encapsulate it, but how do we encapsulate it? Bo Master tried to concentrate have failed, really baffled, believe that the developer of the initiative to package will also encounter the package after the request failed, perhaps you succeed, but here need to pay attention to a block within the use of variables, specific can go to see how the blogger package.
Here, the new AF request HTTPS is over, want to see the package, the demo put in the last.
3. One-way verification
Speaking of this, have to say a lot of online methods, all the one-way verification as a two-way, in fact, does not understand its principle, about the principle, please see here
The code implementation AF is the same:
//AF加上这句和下面的方法 _manager.securityPolicy = [self customSecurityPolicy];/**** SSL Pinning ****/- (AFSecurityPolicy*)customSecurityPolicy { NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"server" ofType:@"cer"]; NSData *certData = [NSData dataWithContentsOfFile:cerPath]; AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate]; [securityPolicy setAllowInvalidCertificates:YES]; NSSet *set = [NSSet setWithObjects:certData, nil]; [securityPolicy setPinnedCertificates:@[certData]]; /**** SSL Pinning ****/ return securityPolicy;}
4.Demo Download Benefits
Because of certificate security issues, the Demo in the certificate blogger deleted, please forgive me, please put your own certificate.
Old AF Access Httpsdemo
New AF Access Httpsdemo
iOS development-use afnetworking for HTTPS one-way verification, two-way verification