HTTPS Learning Summary

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

1 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
1 openssl x509 -in <你的服务器证书>.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.

1234567891011 AFSecurityPolicy * securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];//allowInvalidCertificates 是否允许无效证书(也就是自建的证书),默认为NO//如果是需要验证自建证书,需要设置为YESsecurityPolicy.allowInvalidCertificates = YES;//validatesDomainName 是否需要验证域名,默认为YES;//假如证书的域名与你请求的域名不一致,需把该项设置为NO;如设成NO的话,即服务器使用其他可信任机构颁发的证书,也可以建立连接,这个非常危险,建议打开。//置为NO,主要用于这种情况:客户端请求的是子域名,而证书上的是另外一个域名。因为SSL证书上的域名是独立的,假如证书上注册的域名是www.google.com,那么mail.google.com是无法验证通过的;当然,有钱可以注册通配符的域名*.google.com,但这个还是比较贵的。//如置为NO,建议自己添加对应域名的校验逻辑。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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253 - (void)testClientCertificate {  SecIdentityRef identity = NULL;  SecTrustRef trust = NULL;  NSString*p12 = [[NSBundlemainBundle] pathForResource:@"testClient"ofType:@"p12"];  NSData*PKCS12Data = [NSDatadataWithContentsOfFile:p12];  [[selfclass] 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 = [selfsignWithSignKey:@"test"params:dic];  NSMutableData*body = [postData mutableCopy];  NSLog(@"%@", [[NSStringalloc] initWithData:body encoding:NSUTF8StringEncoding]);  url = [NSStringstringWithFormat: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 = [NSSetsetWithArray:@[@"application/json",                                                                            @"text/plain"]];  manager.securityPolicy = [selfcustomSecurityPolicy];  [manager POST:url parameters:dic success:^(AFHTTPRequestOperation *operation, idresponseObject) {    NSLog(@"JSON: %@", responseObject);  } failure:^(AFHTTPRequestOperation *operation, NSError*error) {    NSLog(@"Error: %@", error);  }];}// 下面这段代码是处理SSL安全性问题的:/**** SSL Pinning ****/- (AFSecurityPolicy*)customSecurityPolicy {  NSString*cerPath = [[NSBundlemainBundle] pathForResource:@"testClient"ofType:@"cer"];  NSData*certData = [NSDatadataWithContentsOfFile:cerPath];  AFSecurityPolicy *securityPolicy = [AFSecurityPolicy defaultPolicy];  [securityPolicy setAllowInvalidCertificates:YES];  [securityPolicy setPinnedCertificates:@[certData]];  [securityPolicy setSSLPinningMode:AFSSLPinningModeCertificate];  /**** SSL Pinning ****/  returnsecurityPolicy;}

  

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

HTTPS Learning Summary

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.