使用 SSL 传输安全性

iOS 应用程序需要以一种方式编写,以便为通过网络传输的数据提供安全性。
SSL 是执行此操作的常用方法。

每当应用程序尝试调用 Web 服务以将数据提取或推送到服务器时,它应该使用 SSL over HTTP,即 HTTPS
要做到这一点,应用程序必须调用 https://server.com/part 这样的 Web 服务,而不是 http://server.com/part
在这种情况下,app 需要使用 SSL 证书信任服务器 server.com

以下是验证服务器信任的示例 -

URLSessionDelegate 实施为:

func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
    
    if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
        let serverTrust:SecTrust = challenge.protectionSpace.serverTrust!

        func acceptServerTrust() {
            let credential:URLCredential = URLCredential(trust: serverTrust)
            challenge.sender?.use(credential, for: challenge)
            completionHandler(.useCredential, URLCredential(trust: challenge.protectionSpace.serverTrust!))
        }
        
        let success = SSLTrustManager.shouldTrustServerTrust(serverTrust, forCert: "Server_Public_SSL_Cert")
        if success {
            acceptServerTrust()
            return
        }
    }
    else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodClientCertificate {
        completionHandler(.rejectProtectionSpace, nil);
        return
    }
    completionHandler(.cancelAuthenticationChallenge, nil)
}

这是信任经理:(找不到 Swift 代码)

@implementation SSLTrustManager
+ (BOOL)shouldTrustServerTrust:(SecTrustRef)serverTrust forCert:(NSString*)certName {
// Load up the bundled certificate.
NSString *certPath = [[NSBundle mainBundle] pathForResource:certName ofType:@"der"];
NSData *certData = [[NSData alloc] initWithContentsOfFile:certPath];
CFDataRef certDataRef = (__bridge_retained CFDataRef)certData;
SecCertificateRef cert = SecCertificateCreateWithData(NULL, certDataRef);

// Establish a chain of trust anchored on our bundled certificate.
CFArrayRef certArrayRef = CFArrayCreate(NULL, (void *)&cert, 1, NULL);
SecTrustSetAnchorCertificates(serverTrust, certArrayRef);

// Verify that trust.
SecTrustResultType trustResult;
SecTrustEvaluate(serverTrust, &trustResult);

// Clean up.
CFRelease(certArrayRef);
CFRelease(cert);
CFRelease(certDataRef);

// Did our custom trust chain evaluate successfully?
return trustResult == kSecTrustResultUnspecified;
}
@end

Server_Public_SSL_Cert.der 是服务器的公共 SSL 密钥。

使用这种方法,我们的应用程序可以确保它与目标服务器通信,没有人拦截应用程序 - 服务器通信。