使用 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 金鑰。

使用這種方法,我們的應用程式可以確保它與目標伺服器通訊,沒有人攔截應用程式 - 伺服器通訊。