iOS supports HTTPS

Source: Internet
Author: User
Tags cas go daddy ssl certificate asymmetric encryption

Http://oncenote.com/2014/10/21/Security-1-HTTPS/?hmsr=toutiao.io&utm_medium=toutiao.io&utm_source= Toutiao.io

1. HTTPS

In fact, HTTPS from the end of the data analysis, and HTTP is not any difference, HTTPS is to put the HTTP protocol packets into the SSL/TSL layer encryption, the TCP/IP layer constitutes a data datagram to transmit, in order to ensure the security of the transmission of data, and for the receiver, in the ssl/ When the TSL decrypts the received packets, it passes the data to the HTTP protocol layer, which is the normal HTTP data. Both HTTP and SSL/TSL are in the application layer of the OSI model. Switching from HTTP to HTTPS is a very simple process, and we need to understand a few concepts before doing a specific switching operation:

Ssl/tsl

About SSL/TSL, Nanyi's two blog posts are a good introduction:

    • Overview of the operating mechanism of SSL/TLS protocol
    • Graphical SSL/TLS protocol

Simply put, SSL/TSL through four handshake, the main exchange of three information:

    1. Digital Certificate : The certificate contains information such as the public key, which is usually sent to the client by the server, and the receiver verifies whether the certificate is trusted by a trusted CA or is relative to the local certificate, and if two-way authentication is required, Both the server and the client need to send a digital certificate to the other party for verification;
    2. three random numbers : These three random numbers form the " conversation key "that is used to decrypt the data for symmetric encryption during subsequent communication.
      First the client first sends the first random number N1, then the server returns to the second random number N2 (this process also sends the previously mentioned certificate to the client), both of which are plaintext, and the third random number N3 (this random number is called Premaster secret), The client uses the public key of the digital certificate for asymmetric encryption to the server, and the server decrypts it with the private key that it knows only, obtaining a third random number. In this way, both the server and the client have three random number n1+n2+n3, and then use these three random numbers to generate a "conversation key", after which the communication is to use this "dialogue key" for symmetric encryption and decryption. Because of this process, the server's private key is only used to decrypt the third random number, never transmitted over the network, so long as the private key is not compromised, then the data is safe.
    3. Encrypted Communication protocol : It is the two sides to negotiate which encryption method, if the two supported encryption method does not match, then can not communicate;

There is a common question about why a random number should be three? Only the last random number N3, okay?

This is due to the SSL/TLS design, it is assumed that the server does not believe that all clients can provide a full random number, if a client provides random number is not random, it greatly increases the "dialogue key" is the risk of being cracked, so the random number of three groups to form the final random number, to ensure the randomness of the stochastic number, This ensures that the dialog key security is generated for each build.

Digital certificates

A digital certificate is an electronic document that contains information about the holder, a public key, and a digital signature that proves that the certificate is valid. The PKI (Public Key Infrastructure) specification system is composed of digital certificates and related public key management and authentication technologies. In general, digital certificates are issued and managed by a digital certificate authority (Certificate Authority, CA), and assume responsibility for the legality of public key in the PKI system; There are many types of digital certificates, and HTTPS uses SSL certificates.

How do you verify that the digital certificate was issued by a CA and not by a third party? Before answering this question, we need to understand the organizational structure of the CA first. First, the CA organizational structure, the topmost is the root CA, the root CA can be authorized to multiple level two CAs, and the level two CA can also authorize multiple three-level CAs, so the CA's organizational structure is a tree structure. For the SSL certificate market, it is mainly carved up by Symantec (with VeriSign and GeoTrust), Comodo SSL, Go Daddy and GlobalSign. After understanding the organization of the CA, take a look at the issuance process for digital certificates:

A digital certificate issuing agency CA, after receiving the applicant's information, checks and determines the true validity of the information, and then produces a document that complies with the standards of the previous year. The certificate content contained in the certificate of the holder information and public key are provided by the applicant, and the digital signature is the CA authority to hash the contents of the certificate obtained, and this digital signature is that we verify that the certificate is a trusted CA-issued data.

Assume that the certificate was issued by a certificate authority, CA1.

1) received a copy of the digital certificate Cer1, the contents of the certificate to do hash to get H1;

2) Find the public key from the CA1 certificate of the institution that issued the certificate, decrypt the digital signature on the certificate, get the hash digest H2 of the certificate Cer1 signature;

3) Comparing H1 and H2, such as equality, indicates that the certificate has not been tampered with.

4) But this time still do not know whether the CA is legal, we see in the CA agency digital certificate, this certificate is public, everyone can get to. The digital signature in this certificate is generated on the previous level, so it can be verified recursively until the root CA. The root CA is self-validating, that is, his digital signature is generated by his own private key. A legitimate root CA is added to the list of authoritative trusted CAs by the browser and the operating system, which completes the final validation. So, be sure to protect your environment (browser/operating system) in the root CA trust list, trust the root CA is to trust all the root CA under all the child CA issued certificates, do not arbitrarily add the root CA certificate.

The general operating system and browser only contains the certificate of the root CA authority, while configuring the Web server HTTPS, will also configure the entire certificate chain, so the entire verification process from the last leaf node certificate, with the parent node check child nodes, a layer of validation of the entire certificate chain credibility.

A metaphor: parent (Root CA digital certificate)-Child (CA digital certificate)-grandchild (digital certificate) Three generations, assuming that the father has no other brothers (equivalent to the root CA is unique), if the child and the parent DNA paternity test, detection of DNA site (i.e. certificate signature) the same, it is basically determined that the child is born by the father , Sun and son. This makes it possible to make sure that the sun is a parent, the rightful heir to the parent (Root CA digital certificate). The verification of digital certificates is based on the same principle.

2. implement HTTPS Support

First of all, you need to be clear about the use of Http/https, because OSX and iOS platform provides a variety of APIs to support different purposes, the official document "Making HTTP and HTTPS requests" has detailed instructions, and the document "HTTPS Server Trust Evaluation The knowledge of HTTPS authentication in detail, here is not much to say. This article mainly explains our most commonly used nsurlconnection support HTTPS implementation (Nsurlsession implementation method is similar, just require authorization to prove that the callback is not the same), And how to use afnetworking this very popular third-party library to support HTTPS. This article assumes that you have sufficient knowledge of HTTP and Nsurlconnection interfaces.

Verify that the certificate API

The relevant API in the security framework, the validation process is as follows:

1). The first step is to obtain the trust object that needs to be validated. This trust object is not the same in different application scenarios, and for nsurlconnection, it is-connection from the delegate method: Willsendrequestforauthenticationchallenge: Callback back in the parameter challenge gets ([Challenge.protectionspace serverTrust]).

2). Use the system default authentication method to verify the trust Object. Sectrustevaluate will evaluate the validity of the certificate by verifying the validity of each level of digital signature on the certificate chain (explained in the previous section), based on the authentication strategy of the Trust object, first-level upwards.

3). If the second step verification is passed, the general security requirements can be directly verified through, into the next step: Use Trust object to generate a voucher ([nsurlcredential credentialfortrust:servertrust]), The sender of the incoming challenge ([Challenge.sender usecredential:cred forauthenticationchallenge:challenge]) processes and establishes the connection.

4). If there is a stronger security requirement, you can continue to validate the trust object more rigorously. A common way is to import the certificate locally to verify that the Trust object matches the imported certificate. There are more ways to view enforcing stricter Server Trust Evaluation, which is explained in the Afnetworking source code.

5). If the validation fails, cancel the Challenge-response authentication verification process and reject the connection request.

PS: If it is a self-built certificate, then the second system default authentication method is not used, because the digital signature of the root CA of the self-built certificate is not in the operating system trust list.

The API and process for iOS authorization validation is probably understood, and below, let's look at the code implementation in Nsurlconnection:

Use nsurlconnection Support HTTPS the implementation

Now start the connection

Nsurl * Httpsurl = [Nsurl urlwithstring:@ "https://www.google.com"];

Self.connection = [nsurlconnection connectionwithrequest:[nsurlrequest requestwithurl:httpsurl] delegate:self];

Callback

-(void) connection: (Nsurlconnection *) connection Willsendrequestforauthenticationchallenge: ( Nsurlauthenticationchallenge *) Challenge {

1) Get the Trust object

Sectrustref Trust = Challenge.protectionSpace.serverTrust;

Sectrustresulttype result;

2) Sectrustevaluate the trust to verify

Osstatus status = Sectrustevaluate (trust, &result);

if (status = = Errsecsuccess &&

(Result = = Ksectrustresultproceed | |

result = = ksectrustresultunspecified)) {

3) Verify success, generate Nsurlcredential voucher cred, tell challenge sender to use this credential to continue connection

Nsurlcredential *cred = [nsurlcredential credentialfortrust:trust];

[Challenge.sender usecredential:cred Forauthenticationchallenge:challenge];

} else {

5) Verification failure, cancel this verification process

[Challenge.sender Cancelauthenticationchallenge:challenge];

}

}

Above is the code that validates the certificate through the system default validation process. What if we were the self-built certificate? In this way, the certificate of the server inside the trust object is not issued by a trusted CA, so it is not successful to authenticate directly with Sectrustevaluate. Or, even if the certificate returned by the server is issued by a trusted CA, how do you determine if the certificate is the specific certificate we want? This requires the local import of the certificate, set to participate in the validation of the anchor Certificate (anchor certificate, through the Sectrustsetanchorcertificates set up to participate in the verification of the anchor Point certificate, If the verified digital certificate is a child node of this anchor certificate, that is, the verified digital certificate is issued by the corresponding CA or sub-CA of the anchor Point certificate, or the certificate itself, then the certificate is trusted, and then called Sectrustevaluate to verify. The code is as follows

Import the certificate first

NSString * Cerpath = ...; Path to the certificate

NSData * Cerdata = [NSData Datawithcontentsoffile:cerpath];

Seccertificateref certificate = seccertificatecreatewithdata (NULL, (__bridge cfdataref) (Cerdata));

Self.trustedcertificates = @[cfbridgingrelease (certificate)];

Callback

-(void) connection: (Nsurlconnection *) connection Willsendrequestforauthenticationchallenge: ( Nsurlauthenticationchallenge *) Challenge {

1) Get the Trust object

Sectrustref Trust = Challenge.protectionSpace.serverTrust;

Sectrustresulttype result;

Note: Here the previously imported certificate is set to the anchor certificate of the Trust object as verified below

Sectrustsetanchorcertificates (trust, (__bridge cfarrayref) self.trustedcertificates);

2) Sectrustevaluate will find the certificate set by the previous sectrustsetanchorcertificates or the default certificate provided by the system to verify the trust.

Osstatus status = Sectrustevaluate (trust, &result);

if (status = = Errsecsuccess &&

(Result = = Ksectrustresultproceed | |

result = = ksectrustresultunspecified)) {

3) Verify success, generate Nsurlcredential voucher cred, tell challenge sender to use this credential to continue connection

Nsurlcredential *cred = [nsurlcredential credentialfortrust:trust];

[Challenge.sender usecredential:cred Forauthenticationchallenge:challenge];

} else {

5) Verification failure, cancel this verification process

[Challenge.sender Cancelauthenticationchallenge:challenge];

}

}

It is recommended to validate the certificate in a way that imports the certificate locally to ensure sufficient security. For more verification methods, please see the Official document "HTTPS Server Trust Evaluation"

Use afnetworking to support HTTPS

Afnetworking is one of the most popular third-party open source repositories developed by Ios/osx, the author of the very famous IOS/OSX developer Mattt Thompson, whose blog Nshipster is also a great place for IOS/OSX developers to learn and broaden their technical horizons. Afnetworking has already encapsulated the above logic code, even more perfect, in the Afsecuritypolicy file, interested in reading the code of this module;

Configuring HTTPS support on Afnetworking is simple:

Nsurl * url = [nsurl urlwithstring:@ "https://www.google.com"];

Afhttprequestoperationmanager * Requestoperationmanager = [[Afhttprequestoperationmanager alloc] InitWithBaseURL:url ];

dispatch_queue_t requestqueue = Dispatch_create_serial_queue_for_name ("Krequestcompletionqueue");

Requestoperationmanager.completionqueue = Requestqueue;

Afsecuritypolicy * securitypolicy = [Afsecuritypolicy policywithpinningmode:afsslpinningmodecertificate];

Allowinvalidcertificates whether to allow invalid certificates (that is, self-built certificates), default to No

If you need to validate your self-built certificate, you need to set it to Yes

Securitypolicy.allowinvalidcertificates = YES;

Validatesdomainname If you need to verify the domain name, the default is yes;

If the domain name of the certificate does not match the domain name you requested, you need to set the entry to no, and if it is set to No, the server can also establish a connection by using a certificate issued by another trusted authority, which is very dangerous and is recommended to be opened.

Set to No, mainly used in this case: the client is requesting a subdomain, and the certificate is a different domain name. Because the domain name on the SSL certificate is independent, if the domain name registered on the certificate is www.google.com, then mail.google.com cannot be verified; Of course, the rich can register the wildcard name *.google.com, but this is still relatively expensive.

If set to No, it is recommended that you add the check logic for the corresponding domain name.

Securitypolicy.validatesdomainname = YES;

Validatescertificatechain whether to validate the entire certificate chain, the default is Yes

Set to Yes, the certificate chain on the trust object returned by the server is compared to the locally imported certificate, which means that if your certificate chain is this:

GeoTrust Global CA

Google Internet Authority G2

*.google.com

Then, in addition to importing *.google.com, you also need to import all CA certificates on the certificate chain (GeoTrust Global CA, Google Internet Authority G2);

If the certificate is self-built, it can be set to Yes, enhanced security, if it is a certificate issued by a trusted CA, it is recommended to turn off the authentication, because the entire certificate chain one by one is not necessary (see source code);

Securitypolicy.validatescertificatechain = NO;

Requestoperationmanager.securitypolicy = securitypolicy;

This is afnetworking to support the main configuration of HTTPS, Afhttpsessionmanager with the Basic agreement, will not repeat.

Use ASIHTTPRequest to support HTTPS

A method

ASIHTTPRequest *request = [asihttprequestrequestwithurl:[nsurlurlwithstring:bodystring]];

[Request Setdelegate:self];

Request.timeoutseconds = 20;

[Request setrequestmethod:@ "POST"];

[Request addrequestheader:@ "Content-type" value:@ "APPLICATION/XML;CHARSET=UTF-8;"];

[Request setvalidatessecurecertificate:no];//when requesting HTTPS, set this property

[Request startasynchronous];

Two different methods

Asiformdatarequest *request = [asiformdatarequest requestwithurl:[nsurl urlwithstring:bodystring];

[Request Setdelegate:self];

Request.timeoutseconds = 20;

[Request setvalidatessecurecertificate:no];//when requesting HTTPS, set this property

[Request setrequestmethod:@ "POST"]; [Request addrequestheader:@ "Content-type" value:@ "Application/xml;charset=utf-8"]; request.defaultresponseencoding = nsutf8stringencoding;

Use ASIHTTPRequest to support HTTPS

A method
ASIHTTPRequest *request = [asihttprequestrequestwithurl:[nsurlurlwithstring:bodystring]];

[Request Setdelegate:self];

Request.timeoutseconds = 20;

[Request setrequestmethod:@ "POST"];

[Request addrequestheader:@ "Content-type" value:@ "APPLICATION/XML;CHARSET=UTF-8;"];

[Request setvalidatessecurecertificate:no];//when requesting HTTPS, set this property

[Request startasynchronous];

Two different methods
Asiformdatarequest *request = [asiformdatarequest requestwithurl:[nsurl urlwithstring:bodystring];
[Request Setdelegate:self];
Request.timeoutseconds = 20;
[Request setvalidatessecurecertificate:no];//when requesting HTTPS, set this property
[Request setrequestmethod:@ "POST"]; [Request addrequestheader:@ "Content-type" value:@ "Application/xml;charset=utf-8"]; request.defaultresponseencoding = nsutf8stringencoding;

iOS supports HTTPS

Related Article

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.