AFNetworking 3.0 source code explanation: AFSecurityPolicy,

Source: Internet
Author: User

AFNetworking 3.0 source code explanation: AFSecurityPolicy,

This is a full network strategy (in fact, it is to verify whether the certificate is secure), https is actually to add an SSL coat to http, so that the transmission layer is more secure, because http is transmitted in plain text on the network.

HTTP:

1. the HTTP protocol is used for communication between the client and the server.

2. Communication through requests and corresponding exchanges

Client request:

Server Response:

3. HTTP is a protocol that does not save the status

HTTP itself does not save the request and the corresponding communication status. What does it mean? That is to say, when a new request comes, HTTP will generate a new response, and no storage will be made for the heat preservation information of the previous request and response. This is also designed to quickly process transactions and maintain good scalability.

4. Request URI to locate the resource

URI is a location index, so that you can easily access various resources on the Internet.

5. HTTP Method for notifying the server's intent

① GET: directly access the resource identified by the URI, that is, obtain the resource based on the URI.

② POST: used to transmit the entity.

③ PUT: used to transmit files.

④ HEAD: used to obtain the packet header, which is similar to the GET method, but the response part does not return the body content.

⑤ DELETE: DELETE an object, which is the opposite of PUT. Deletes resources at a specified position based on the requested URI.

⑥ OPTIONS: Query supported methods to query supported methods for resources specified by the request URI.

7. TRACE: TRACE path, which returns the request communication ring information from the server.

Expressconnect: you must use the tunnel protocol to CONNECT to the proxy. You must use the resume tunnel protocol to implement TCP communication when communicating with the proxy server. SSL (Secure Sockets Layer) and Transport Layer Security (TLS) encrypt the communication content and perform tunnel transmission.

6. Pipelines allow the server to have multiple requests

7. Cookie makes HTTP traceable

HTTP is a simple communication protocol, so it is very efficient. However, communication data is sent in plain text, which can be easily damaged after being intercepted. In the era of increasingly developed Internet, the security requirements for communication data are also increasing.

HTTPS

HTTPS is a communication security solution, which can be said to be relatively secure. Why is it a safe protocol? I will explain it below

HTTP + encryption + Authentication + Integrity Protection = HTTPS

In fact, HTTPS is an HTTP with an SSL shell. How can this sentence be understood?

We should all know that HTTP is the application layer protocol, but HTTPS is not a new protocol at the application layer, but the HTTP Communication Interface is partially replaced by the SSL or TLS protocol.

Generally, HTTP communicates directly with TCP, which is different when SSL is used. You must first communicate with SSL, and then communicate with TCP.

Here are some additional questions about encryption:

Nowadays, encryption and decryption algorithms are usually public. For example, a * B = 200, adding a is the password you know, B is the data to be encrypted, and 200 is the encrypted result. Here, this * is a simple encryption algorithm. This algorithm is so simple. However, it is difficult to crack a and B without knowing one of them. Even if we know 200 and get a B, it's hard. Assuming that B knows the password a, it is easy to calculate B = 200/.

In reality, the encryption algorithm is much more complex than this one.

Two common encryption methods are introduced:

1. Shared Key Encryption

2. Public Key Encryption

Shared key encryption is a common key for encryption and decryption, also known as symmetric encryption. The advantage is that encryption and decryption are fast. The disadvantage is that once the key is disclosed, other people can decrypt the data.

Public key encryption solves the difficulty of shared key encryption. The process is as follows:

① The sender uses the public key of the other party for encryption

② The receiver uses its own private key for decryption

The principle is the same. This is different from the example of a and B. Even if you know the result and public key, it is very difficult to crack the confidential data. This mainly involves complex mathematical theories.

HTTPS adopts a hybrid encryption mechanism

HTTPS uses a hybrid encryption mechanism that combines shared key encryption and public key encryption.

Now we know how HTTPS is encrypted. What is the mutual authentication process like?

========================================================== ======================================

========================================================== ======================================

Pay attention to the yellow part, which indicates a scenario we usually use. This article will take a long time, not only to explain HTTPS, but also to increase memory. When I want to see it later that day, I will be able to read this article to remember most of the HTTPS knowledge. The following describes more detailed HTTPS processes.

I. Analysis of header files

Let's first look at what is in the header file. To implement the authentication function, you must add system Security.

The following enumerated value indicates:

1. AFSSLPinningModeNone indicates that the server certificate is unconditionally trusted.

2. AFSSLPinningModePublicKey indicates that the PublicKey in the certificate returned by the server is verified. If it passes the verification, it passes. Otherwise, it fails.

3. AFSSLPinningModeCertificate indicates that all the certificates returned by the server and the local certificates are verified. If they pass the verification, they pass. Otherwise, they do not pass.

AFSecurityPolicy is used to evaluate whether secure network connections through X.509 (digital certificate standard) digital certificates and public keys are trustworthy. Adding an SSL certificate to an application can effectively prevent man-in-the-middle attacks and security vulnerabilities. It is strongly recommended that all network connections of applications involving user sensitive or private data or financial information use ssl https connections.

Returns the SSL Pinning type. The default value is AFSSLPinningModeNone.

This property stores a set of all certificates available for verification. By default, AFNetworking searches all. cer certificate files in the project. To create a certificate, use certificatesInBundle to load the certificate in the target path, and then call policyWithPinningMode: withPinnedCertificates to create a class object.

Note: As long as any verification in the certificate set passes, evaluateServerTrust: forDomain: returns true, that is, the verification is passed.

Invalid or expired certificates are allowed. By default, certificates are not allowed.

Whether to verify the domain name in the certificate

Returns the certificate in the specified bundle. If AFNetworking is used for certificate verification, you must implement this method and use the yywithpinningmode: withPinnedCertificates method to create instance objects.

The default instance object. The Default Authentication Settings are as follows:

1. invalid or expired certificates are not allowed

2. Verify the domain Name

3. The certificate and public key are not verified.

There is nothing to say about these two methods. They are all about creating security policies.

Core Method: This method is used. AFNetworking is called internally. This will be mentioned later.

1 AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; 2 3 AFSecurityPolicy *securityPolicy = [[AFSecurityPolicy alloc] init]; 4 [securityPolicy setAllowInvalidCertificates:NO]; 5 [securityPolicy setSSLPinningMode:AFSSLPinningModeCertificate]; 6 [securityPolicy setValidatesDomainName:YES];7 [securityPolicy setValidatesCertificateChain:NO]; 8 9 manager.securityPolicy = securityPolicy;
// Obtain the Public Key static id AFPublicKeyForCertificate (NSData * certificate) in the certificate. You only need to know more about this method. # Macros in import

_ Require_Quiet and _ Require_noErr_Quiet are two macro definitions.

_ Require_Quiet () is actually the code between the true execution tags, which is more convenient to use
_ Require_noErr_Quiet () is skipped when an exception occurs.

Convert key to datastatic NSData * AFSecKeyGetData (SecKeyRef key)

Static BOOL afseckeyis1_tokey (SecKeyRef key1, SecKeyRef key2)

SecKeyRef is a stuct struct, which must be converted to data for comparison.

1. User-defined, the success is kSecTrustResultProceed, And the failure is kSecTrustResultDeny

2. If it is not user-defined, kSecTrustResultUnspecified fails and kSecTrustResultRecoverableTrustFailure

It is not difficult to explain the last one or the judgment above.

Static NSArray * AFCertificateTrustChainForServerTrust (SecTrustRef serverTrust) Retrieves all the certificates returned by the server

Static NSArray * AFPublicKeyTrustChainForServerTrust (SecTrustRef serverTrust) retrieves the public key of all the certificates returned by the server

+ (NSSet *) certificatesInBundle :( NSBundle *) bundle obtains all. cer certificates in the project package.

+ (NSSet *) defaultPinnedCertificates

// Find the same public key and use 73 for (id trustChainPublicKey in publicKeys) {74 for (id pinnedPublicKey in self. pinnedPublicKeys) {75 if (aggregate (_ bridge SecKeyRef) trustChainPublicKey, (_ bridge SecKeyRef) pinnedPublicKey) {76 trustedPublicKeyCount + = 1; 77} 78} 79}

 

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.