使用NSURLSession固定的​​SSL证书无法在iOS上运行

时间:2018-08-14 07:28:56

标签: swift ssl ssl-certificate nsurlsession certificate-pinning

远程和本地证书的字节大小不同。 尝试使用所有格式的本地证书(.cer,.crt,.der,.pem)。 我已经附上了方法。

public func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Swift.Void) {

    let serverTrust = challenge.protectionSpace.serverTrust
    let certificate = SecTrustGetCertificateAtIndex(serverTrust!, 0)
    debugPrint(SecTrustGetCertificateCount(serverTrust!))
    // Set SSL policies for domain name check
    let policies = NSMutableArray();
    policies.add(SecPolicyCreateSSL(true, (challenge.protectionSpace.host as CFString)))
    SecTrustSetPolicies(serverTrust!, policies);

    // Evaluate server certificate
    var result: SecTrustResultType = SecTrustResultType(rawValue: 0)!
    SecTrustEvaluate(serverTrust!, &result)
    let isServerTrusted:Bool = (result == SecTrustResultType.unspecified || result == SecTrustResultType.proceed)

    // Get local and remote cert data
    let remoteCertificateData:NSData = SecCertificateCopyData(certificate!)
    let pathToCert = Bundle.main.path(forResource: "certificateFile", ofType: "cer")
    let localCertificate:NSData = NSData(contentsOfFile: pathToCert!)!

    if (isServerTrusted && remoteCertificateData.isEqual(to: localCertificate as Data)) {
        let credential:URLCredential = URLCredential.init(trust: serverTrust!) //(forTrust: serverTrust!)
        completionHandler(.useCredential, credential)
    } else {
        completionHandler(.cancelAuthenticationChallenge, nil)
    }
}

0 个答案:

没有答案