There are situations where security considerations require HTTPS requests, but in many cases the IP is used to prevent domain name resolution from being accessed. The General Service does not request the certificate for the IP, so we can implement the SSL login process to ensure the security of the request.
First, you need to generate the SSL certificate locally and build a local service.
MAC Apache locally configured SSL certificate and IOS OTA deployment: Http://www.jianshu.com/p/bd016015efe7
Methods for converting a generated CRT into a CER
OpenSSL X509- in Test.crt-out Test.cer-outform der
Two. Implementing the Code
Initialize the nsurlsession to import the certificate into the corresponding Xcode project
Nsurlsessionconfiguration *configuration ==*session = [nsurlsession Sessionwithconfiguration:configuration delegate: Self delegatequeue:[[ Nsoperationqueue alloc] [init]];
The generated SSL certificate requires the IP to be set, and the IP is verified when it is verified. But more often than not to verify the IP, because there may be only one certificate inside the code, but the service may have multiple sets of deployment, if the verification of IP, will limit the extension of services (many projects will do their own DNS policy, IP will often change).
- (void) Urlsession: (Nsurlsession *) session Didreceivechallenge: (Nsurlauthenticationchallenge *) Challenge Completionhandler: (void(^) (nsurlsessionauthchallengedisposition disposition, nsurlcredential *_nullable credential)) completionhandler{NSString*host =Challenge.protectionSpace.host; BOOL isIp=[self _isip:host]; if([Challenge.protectionSpace.authenticationMethod isequaltostring:nsurlauthenticationmethodservertrust]) {if(isIp) {//GetNSData *certdata =[nsdata datawithcontentsoffile:[[nsbundle Mainbundle] Pathforresource:@"Server"OfType:@"cer"]]; if(certdata) {Sectrustref Trust=[[Challenge Protectionspace] servertrust]; Nsmutablearray*policies =[Nsmutablearray array];
If you need to verify the IP, you need to open the following comments, the following X509 this code commented out
[Policies AddObject: (__bridge_transfer ID) Secpolicycreatessl (True, (__bridge cfstringref) domain)]; [Policies AddObject: (__bridge_transferID) SecPolicyCreateBasicX509 ()]; Sectrustsetpolicies (trust, (__bridge cfarrayref) policies); Seccertificateref Rootcert=Seccertificatecreatewithdata (Kcfallocatordefault,cfbridgingretain (certdata)); Const void*array[1] ={Rootcert}; Cfarrayref certs= Cfarraycreate (NULL, Array,1, &kcftypearraycallbacks); interr; Sectrustresulttype Trustresult=0; Err=sectrustsetanchorcertificates (trust, certs); if(Err = =NOERR) {Err= Sectrustevaluate (trust,&Trustresult); } BOOL Trusted= (Err = = NOERR) && ((Trustresult = = ksectrustresultproceed) | | (Trustresult = =ksectrustresultunspecified)); if(!trusted) {nsurlcredential*credential =[Nsurlcredential CredentialForTrust:challenge.protectionSpace.serverTrust]; Completionhandler (nsurlsessionauthchallengeusecredential, credential); } Else { //If the checksum fails, verify the certificate data, generally do not recommend this logic, because the service is not guaranteed to be safeNsmutablearray *pinnedcertificates =[Nsmutablearray array]; [Pinnedcertificates addobject: (__bridge_transferID) Seccertificatecreatewithdata (NULL, (__bridge cfdataref) certdata)]; Sectrustsetanchorcertificates (trust, (__bridge cfarrayref) pinnedcertificates); Nsarray*servercertificates =[self _certificatetrustchainforservertrust:trust]; for(NSData *trustchaincertificateinch[Servercertificates Reverseobjectenumerator]) { if([Certdata isequaltodata:trustchaincertificate]) {nsurlcredential*credential =[Nsurlcredential CredentialForTrust:challenge.protectionSpace.serverTrust]; Completionhandler (nsurlsessionauthchallengeusecredential, credential); } } } }}Else{nsurlcredential*credential =[Nsurlcredential CredentialForTrust:challenge.protectionSpace.serverTrust]; Completionhandler (nsurlsessionauthchallengeusecredential, credential); } }}-(BOOL) _isip: (nsstring*) ahost{NSString*regex =@"((2[0-4]\\d|25[0-5]|[ 01]?\\d\\d?) \\.) {3} (2[0-4]\\d|25[0-5]| [01]?\\d\\d?]"; Nspredicate*pred = [Nspredicate predicatewithformat:@"Self MATCHES%@", regex]; return[pred evaluatewithobject:ahost];}-(Nsarray *) _certificatetrustchainforservertrust: (sectrustref) servertrust{cfindex certificatecount=Sectrustgetcertificatecount (Servertrust); Nsmutablearray*trustchain =[Nsmutablearray arraywithcapacity: (Nsuinteger) Certificatecount]; for(Cfindex i =0; i < Certificatecount; i++) {SECCERTIFICATEREF certificate=Sectrustgetcertificateatindex (Servertrust, i); [Trustchain addobject: (__bridge_transfer nsdata*) Seccertificatecopydata (certificate)]; } return[Nsarray arraywitharray:trustchain];}
HTTPS Request Build
Nsmutableurlrequest *request = [nsmutableurlrequest requestwithurl:[nsurl urlwithstring:@ "https:// 127.0.0.1:443/index.html"]; *task = [_session datataskwithrequest:request completionhandler:^ (NSData * _nullable data, Nsurlresponse * _nullable response, Nserror * _nullable error) { Completionhandler (((nshttpurlresponse*) response). StatusCode, data? [[NSString alloc] Initwithdata:data encoding:nsutf8stringencoding]: nil, error); }]; [Task resume];
There are many examples on the web, but many do not consider the scenario of not verifying the IP. I hope this article can give you a reference
iOS built-in certificate, verifying HTTPS requests