iOS Development Series - HTTPS

HTTPS

Netscape created HTTPS in 1994 and used it in the Netscape Navigator browser. Originally, HTTPS was used with SSL; after SSL evolved to TLS.
Some differences between the HTTPS protocol and the HTTP protocol:

  • http is a hypertext transfer protocol, information is transmitted in clear text, and https is a secure ssl encrypted transfer protocol.
  • http and https use completely different connection methods and use different ports. The former is 80 and the latter is 443.

The process of sending an HTTPS request using NSURLSession in iOS is as follows:

The process on the figure is as follows

  1. First, the client sends an Https request to the server using NSURLSession. The server does not directly return the response data. Instead, return a protected space ( NSURLProtectionSpace ) in the NSURLSessionDataDelegate delegate method.
  2. There is a trust certificate of the server in the protected space, and the public key of the server is stored in the certificate.
  3. The client needs to tell NSURLSession how to handle certificates of type that the server trusts in the proxy method
  4. If you choose not to trust the request to cancel, if you trust it, the client and the server request to establish 保护空间. The content of the request sent by the client will be encrypted by the public key in the certificate and sent to the server to ensure the security of the data transmission process.

The following code is to call the certificate processing in NSURLSessionDataDelegate. Since there are many types of certificates, the certificate of the server trust type is processed here.

/**
 * 接收到HTTPS证书的询问是或安装证书
 */
- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler
{
    // 这里处理的是服务器信任类型的证书
    if (![challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) return;
    // 通过调动completionHandler这个Block告诉NSURLSession是否接受证书
    // 参数NSURLSessionAuthChallengeDisposition 如何处理安全证书
    // 参数NSURLCredential 是安全证书对象
    
    // 服务器的信任信息
    SecTrustRef  secTrustRef  = challenge.protectionSpace.serverTrust;
    // 创建服务界别证书对象
    NSURLCredential *credential = [NSURLCredential credentialForTrust:secTrustRef];
    if(completionHandler){
        completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
    }
    
}

提示:在开发中使用AFNetworking框架,该框架内部已经帮我们做了处理。

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324674477&siteId=291194637