Study Summary of HTTPS

Source: Internet
Author: User

Overview of HTTPS Learning Summary

HTTPS vs. HTTP has a security layer of SSL/TLS, specifically verifying the server's certificate and encrypting the content.

Let's take a look at the difference between HTTP and HTTPS
I use AFN to access the Httpbin.org/image/png under HTTP
Then use Charles to grab the bag and see the pictures that were transferred.

Then access the https://httpbin.org/image/png under HTTPS
Catch the packet again, see the data is garbled, this is the data after encryption

About cryptographic algorithms

1) Symmetric encryption: The key is only one, encryption and decryption for the same password, and the decryption speed is fast, the typical symmetric encryption algorithm has DES, AES and so on;

2) Asymmetric encryption: An asymmetric encryption algorithm requires two keys: Public key (PublicKey) and private key (Privatekey). Public key and private key is a pair, if the data encrypted with public key, only with the corresponding private key to decrypt, if the private key to encrypt the data, then only the corresponding public key can be decrypted. Because encryption and decryption use two different keys, this algorithm is called an asymmetric encryption algorithm.

The process is like this when we use GitHub, our computer generates a private key and a public key, the public key is uploaded to GitHub, the private key is added to our computer's SSH, so GitHub transmits data to us using the public key we upload to encrypt it, and when we get the data, we use the private key to decrypt it.

What is SSL/TLS

TLS is the abbreviation for Transport Layer Security, the Transport Layer Safety protocol, and SSL is the abbreviation for Secure Sockets layer, the Security sokects layer protocol. SSL/TLS has many benefits, powerful validation, flexible algorithm, easy deployment and use. The disadvantage is that it increases the burden on the processor, but consumes less performance and is negligible compared to security.

Communication process

The communication process has a handshake of four times.
1, the client sends the request, the server returns the public key to the client;
2, the client generates a symmetric encryption key, which is encrypted with the public key and returned to the server;
3, the server received, the use of the private key to unlock the symmetric encryption key, save;
4, after the interaction is the use of symmetric encrypted data to interact.

Advantages of HTTPS communication
1) The client-generated key can be obtained only by the client and the server;

2) encrypted data can only be plaintext by client and server;

3) client-to-server communication is secure.

How to obtain a certificate 1. Request a certificate from a CA

E-Commerce Certification authority (CA, Certificate Authority), also known as e-commerce Certification Center, is responsible for the issuance and management of digital certification authority.
There is no detail here.

2. Self-made certificate

Another way is to make a self-made certificate, the certificate of the self-made certificate is generated with OpenSSL. OpenSSL is a powerful Secure Sockets Layer cipher library that includes key cryptographic algorithms, common key and certificate encapsulation management functions, and SSL protocols, and is already open source on GitHub.

Various instructions for OpenSSL

The command for a self-made certificate is

OpenSSL req-x509-newkey rsa:2048-keyout key.pem-out cert.pem-days XXX

The first input command will automatically generate KEY.PEM
Entering the command will let you enter the password, country, province, organization (company), name and other information
The input is completed and a certificate is generated CERT.PEM

Some options for commands:

    • Req is a certificate request and a generated program
    • -x509 a certificate standard
    • -newkey Arg,arg is a parameter, for example rsa:2048 is the generation of 2048-bit RSA key
    • -keyout filename output root certificate file name
    • -out filename output of the standard certificate file?
    • -day N to specify the number of days to validate, by default 30
    • *

Preview Cert.pem To see the information you just entered

PEM can be converted to CER format and can be used with commands
OpenSSL x509-in < Your server certificate >.pem-outform der-out server.cer

You can also double-click Cert.pem, which is the import to keychain, open keychain to export the CER format certificate.

The above part of the self-made certificate information reference is StackOverflow this problem

About the security framework

Looking at Apple's official documentation, the security framework is written in C and provides some API for managing identifiers, certificates, digital signatures, trusts, and so on.
Here are a few common objects to consider. SecIdentityRefcode An identifier object, a struct type, that contains a SecKeyRef type and a SecCertificateRef type. SecKeyRefis an asymmetric key object. SecCertificateRefis a certificate object that adheres to the standards of the previous month. If these two objects are not stored in keychain, converting them to SecKeychainItemRef objects also causes Keychain services to return an error.

To generate the P12 certificate, it reminds me that when I configure a push certificate, when I export the certificate, I convert the certificate in the CER format to a certificate in the P12 format.

iOS for HTTPS transport

Because the projects are all used AFN, so it is probably next to the AFN implementation method
If it is a CA-certified certificate, it is available directly with the AFN request.

Afsecuritypolicy * securitypolicy = [Afsecuritypolicy policywithpinningmode:afsslpinningmodecertificate];// Allowinvalidcertificates whether to allow invalid certificates (that is, self-built certificates), the default is no//if you need to verify your self-built certificate, you need to set it to Yessecuritypolicy.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; If you set no, that is, the server uses certificates issued by other trusted institutions, you can also establish a connection. This is very dangerous, it is recommended to open. 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;

  

In the case of a self-made certificate, the client needs to import the server's public key, drag the public key into the XOCDE, and use it to convert the certificate from PEM to P12 format, see the method above
2. Modify the authentication method

-(void) Testclientcertificate {secidentityref identity = NULL;  Sectrustref Trust = NULL;  NSString *P12 = [[NSBundle mainbundle] pathforresource:@ "testclient" oftype:@ "P12"];  NSData *pkcs12data = [NSData DATAWITHCONTENTSOFFILE:P12];  [Self class] extractidentity:&identity andtrust:&trust Frompkcs12data:pkcs12data];  NSString *url = @ "https://218.244.131.231/manicureshop/api/order/pay/%@";                            Nsdictionary *dic = @{@ "Request": @{@ "OrderNo": @ "1409282102222110030643",  @ "type": @ (2)}};  _signstring = nil; NSData *postdata = [nsjsonserialization datawithjsonobject:dic options  : nsjsonwritingprettyprinted Error:nil];  NSString *sign = [self signwithsignkey:@ "test" params:dic];  Nsmutabledata *body = [PostData mutablecopy]; NSLog (@ "%@", [[NSString alloc] Initwithdata:boDY encoding:nsutf8stringencoding]);  url = [NSString stringwithformat:url, sign];  Afhttprequestoperationmanager *manager = [Afhttprequestoperationmanager manager];  Manager.requestserializer = [Afjsonrequestserializer serializer];  Manager.responseserializer = [Afjsonresponseserializer serializer];  [Manager.requestserializer setvalue:@ "Application/json" forhttpheaderfield:@ "Accept"];  [Manager.requestserializer setvalue:@ "Application/json" forhttpheaderfield:@ "Content-type"];                                                                            Manager.responseSerializer.acceptableContentTypes = [Nsset setwitharray:@[@ "Application/json",  @ "Text/plain"];  Manager.securitypolicy = [self customsecuritypolicy]; [Manager Post:url Parameters:dic success:^ (afhttprequestoperation *operation, id responseobject)  {NSLog (@ "JSON:%@", responseobject);  } failure:^ (Afhttprequestoperation *operation, Nserror *error) {NSLog (@ "error:%@", error); }];} The following code is dealing with SSL security issues:/**** SSL PInning ****/-(afsecuritypolicy*) customsecuritypolicy {nsstring *cerpath = [[NSBundle mainbundle] pathForResource:@ "  TestClient "oftype:@" CER "];  NSData *certdata = [NSData Datawithcontentsoffile:cerpath];  Afsecuritypolicy *securitypolicy = [Afsecuritypolicy defaultpolicy];  [SecurityPolicy Setallowinvalidcertificates:yes];  [SecurityPolicy Setpinnedcertificates:@[certdata]];  [SecurityPolicy setsslpinningmode:afsslpinningmodecertificate]; /**** SSL pinning ****/return securitypolicy;}

  

This code is from reference 3, well written, no need to say it again.

Summarize

Security is becoming more and more important now that the network is becoming more and more developed. Not much to say, HTTPS is a trend.

Resources:
1. Chat about network encryption/Tenzianghong in IOS

One of the 2.iOS Safety series: Https/jaminzzhang

3.iOS Access HTTPS SSL and TLS bi-directional encryption/Brother technology Blog

4. Apple-related official documents

Study Summary of HTTPS

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.