Three kinds of side __https of HTTPS trust certificate

Source: Internet
Author: User
Tags openssl openssl x509 response code

The hard way I debug afnetworking send HTTPS request Bugs---------debug a morning and finally solved


Process of certificate trust:

The trust of a certificate is the process of trusting by proxy (Nsurlconnection and nsurlsession two ways to trust) the client trusts the certificate: 1. When the client wants to access the server, the server sends a protected trust Certificate of 2 to the client. The client determines whether to trust the certificate sent by the client, 3. If the trust. Then the client installs the public key on the client, and the server has the key to the protected certificate, each time the server requests data, the server will send the data to the key encryption, the client to the data transmitted through the public key to decrypt


Share some of your experiences here:

The first request data to trust the certificate before you can request data, but for Baidu, the Apple website such a large site does not require a certificate of trust,

You only need to trust a server certificate once

There are two ways to trust a certificate:

Familiar with the nsurlsession and nsurlconnection two kinds of trust certificates, I will focus on the third kind:

If you do not trust the certificate, you will report the following error:

Nsurlsession/nsurlconnection HTTP Load failed (Kcfstreamerrordomainssl,-9843)

Reason: No trust certificate
A. Nsurlsession way to trust a certificate is through a proxy:

1. Load the global session first:

@property (nonatomic, strong) nsurlsession *session;
-(Nsurlsession *) session {
    if (_session = = nil) {
        nsurlsessionconfiguration *config = [ Nsurlsessionconfiguration Defaultsessionconfiguration];
        _session = [nsurlsession sessionwithconfiguration:config delegate:self delegatequeue:nil];
    }
    return _session;
}

2. Initiating Data tasks

URL
    nsurl *url = [nsurl urlwithstring:@ "https://domain name"];
    
    initiating data Tasks
    [[Self.session datataskwithurl:url completionhandler:^ (NSData * _nullable data, Nsurlresponse * _Nullable Response, Nserror * _nullable error) {
        NSLog (@ "%@---%@", response,[[nsstring alloc] initwithdata:data encoding: Nsutf8stringencoding]);
    Resume];

3. Trust in the proxy method to implement the certificate-----------

-(void) Urlsession: (Nsurlsession *) session Task: (Nsurlsessiontask *) Task
Didreceivechallenge: ( Nsurlauthenticationchallenge *) Challenge
 Completionhandler: (void (^) (nsurlsessionauthchallengedisposition Disposition, nsurlcredential * __nullable credential)) Completionhandler {
     /* <nsurlprotectionspace: 0x7fef2b686e20>: 
     Host:mail.itcast.cn, 
     Server:https, 
     auth-scheme: Nsurlauthenticationmethodservertrust,
    //Determine if it is a trusted server certificate
    if ( Challenge.protectionSpace.authenticationMethod = = nsurlauthenticationmethodservertrust) {
        //Tell server, client trust certificate
        //Create credential Objects
        Nsurlcredential *credntial = [nsurlcredential credentialForTrust:challenge.protectionSpace.serverTrust];
        Tell the server trust certificate
        completionhandler (nsurlsessionauthchallengeusecredential,credntial) by Completionhandler
    ;
    NSLog (@ "protectionspace =%@", challenge.protectionspace);
}


two. Nsurlconnection Way to trust a certificate is also through the proxy way: 1. Send Request:

    URL
    nsurl *url = [Nsurl urlwithstring:@ "https://mail.itcast.cn"];
    
    Request
    Nsurlrequest *request = [Nsurlrequest requestwithurl:url];
    
    Send Request
    [nsurlconnection connectionwithrequest:request delegate:self];

2. Trust Certificate
#pragma mark-nsurlconnectiondatadelegate Proxy method
-(void) connection: (Nsurlconnection *) connection Willsendrequestforauthenticationchallenge: (Nsurlauthenticationchallenge *) Challenge {
    //Determine if it is a trusted server certificate if
    ( Challenge.protectionSpace.authenticationMethod = = nsurlauthenticationmethodservertrust) {
        //Tell server, client trust certificate
        //Create credential Objects
        Nsurlcredential *credntial = [nsurlcredential credentialForTrust:challenge.protectionSpace.serverTrust];
        Tell the server to trust the certificate
        [Challenge.sender usecredential:credntial forauthenticationchallenge:challenge];
    }

3. Get the requested data
-(void) connection: (Nsurlconnection *) connection didreceivedata: (NSData *) data {
    NSLog (@ "data =%@", [[NSString Alloc] Initwithdata:data encoding:nsutf8stringencoding]);
}

three. Trust the server certificate in a afnetworking way:First code:
    Afhttpsessionmanager *manager = [Afhttpsessionmanager manager];
    Manager.securityPolicy.validatesDomainName = NO;
    Manager.responseserializer = [Afhttpresponseserializer serializer];    manager.responseSerializer.acceptableContentTypes = [Nsset setwithobjects:@ "Application/json", @ "Text/json" , @ "Text/javascript", @ "text/html", nil];
    [Manager get:@ "https://domain name" parameters:nil progress:^ (nsprogress * _nonnull downloadprogress) {
        NSLog (@ "%@", downloadprogress);
    } success:^ (Nsurlsessiondatatask * _nonnull task, id  _nullable responseobject) {
        NSLog (@ "%@---%@", [ Responseobject class],responseobject);
        NSLog (@ "%@", [[NSString Alloc]initwithdata:responseobject encoding:nsutf8stringencoding]);
    } failure:^ (Nsurlsessiondatatask * _nullable task, Nserror * _nonnull error) {
        NSLog (@ "%@", error);
    


Note that the hole encountered: 1.https of the Protocol direct request will be reported the following error:

nsurlsession/nsurlconnection HTTP Load failed (Kcfstreamerrordomainssl, -9843)
2. Setting properties cannot set Validatesdomainname to No, you can make any request after setting to No, so set it to Yes (the default is YES)-----focus

Manager.securityPolicy.validatesDomainName =yes;

Afnetworking's security settings are set in Afsecuritypolicy, which defines three types of SSL pinning Mode:

Afsslpinningmodenone: You don't have to pack the thin with your APP, fully trust the server's thin certificate afsslpinningmodecertificate: is the thin certificate of the server to match your thin proof exactly? Afsslpinningmodepublickey: Matches only the public key to your thin certificate for the server thin

It's better to choose which mode to use.

Afsslpinningmodecertificate is more secure but also more annoying than the thin that you pack to the server thin proof. Because your thin is packaged with the app, it also means that if your thin is proven or changed, you'll get a new version of the app and the old version of the app's thin prove ineffective. You can also download the latest thin from a server every time the APP is powered up, and the download link will be dangerous at this point.

Afsslpinningmodepublickey is only the public key to the thin, so even if the server thin is changed, as long as the public key does not change, it will pass the verification.

So if you can make sure that every user is always using the latest version of the APP (for example, the company's business in-house), then consider Afsslpinningmodecertificate, or choose Afsslpinningmodepublickey is a more realistic approach.

Resolves the issue of certificate trust, which means that you can trust the certificate after you set the properties above


But the problem is not solved: the more frequently encountered problem is that the requested data printing is problematic,

Error domain=com.alamofire.error.serialization.response code=-1016 "Request failed:unacceptable content-type: Text/html "


Reason:

This is because afnetworking the response result as JSON by default (default Manager.responseserializer = [Afjsonresponseserializer serializer]), obviously, Our Request Baidu home page returns is not a JSON text, but an HTML page, but afnetworking does not know, it firmly believe that the result of the request is a JSON text! And then stubbornly parse it in JSON, Obviously there is no way to parse a Web page into a dictionary or array, so this error occurs.

However, we expect it to be able to handle this situation correctly, rather than prompting an error.
You have to tell afnetworking: Don't treat this page as JSON!


Solution:

Only need to add before sending the request: Manager.responseserializer = [Afhttpresponseserializer Serializer]

The above steps can be achieved with HTTPS certificate trust and correct access to such as Baidu.com home page HTML source code ...


Additional Instructions:

The data loaded on a webpage is essentially a string, and we can print the data in the form of a binary string by using the data obtained from the Web page:

NSLog (@ "%@", [[nsstringalloc]initwithdata:responseobjectencoding:nsutf8stringencoding]);




With the above solution is not do not know how to obtain the voucher can, do not worry, the following add how to obtain the certificate of the domain name:

Reference Links:

http://nelson.logdown.com/posts/2015/04/29/how-to-properly-setup-afnetworking-security-connection/


obtain security thin proof 1. Confirm the use of safety links

If you're with a remote server that is through an HTTP connection, it's not a secure link, and if it's HTTPS, it's a secure link. 2. Prepare the website security thin Proof

Next we need a thin certificate (certification file), whose name is. cer, and you can ask your website administrator, who usually knows how to get the file.

If your website administrator doesn't have a. cer file, only. crt files, then you can transfer through the following line of instructions, note that it is in the DER code format (please change the myWebsite to the name you want):

OpenSSL x509-in mywebsite.crt-out Mywebsite.cer-outform der

If it's unfortunate that your website administrator is not connected to a CRT file, you can also use this entire line of instructions to obtain thin from your website (please convert www.mywebsite.com to your Web site):

OpenSSL s_client-connect www.mywebsite.com:443 </dev/null 2>/dev/null | OpenSSL x509-outform DER > Mywebsite.cer

Now you have a thin witness. 3. Add thin to your patent case

Put your thin in your Xcode record and remember to tick the Copy items if needed with ADD to targets

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.