Закрепление SSL-сертификата с NSURLSession не работает iOS

Размер байтов удаленных и локальных сертификатов различен. Пробовал со всеми форматами локального сертификата (.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 ответов

Другие вопросы по тегам