0

曾经有一种方法可以解决 iOS 坚持使用有效证书的 HTTPS。我对在这种状态下将应用程序提交到商店不感兴趣,我只想在开发应用程序时与 Charles 一起嗅探网络操作。

谢谢

我试过了

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

...以及网上常见的所有其他变体。

一定有办法...

4

1 回答 1

0

您可以使用 URLSessionRequest 在下面的代码中使用 SSL 请求,

 fileprivate func SSLCertificateCreateTrustResult(_ serverTrust: SecTrust)->SecTrustResultType {
        let certificate: SecCertificate = SecTrustGetCertificateAtIndex(serverTrust, 0)!
        let remoteCertificateData = CFBridgingRetain(SecCertificateCopyData(certificate))!
        var certName = "certName"

        let cerPath: String = Bundle.main.path(forResource: certName, ofType: "der")!
        let localCertificateData = NSData(contentsOfFile:cerPath)!

        let certDataRef = localCertificateData as CFData
        let cert = (SecCertificateCreateWithData(nil, certDataRef))
        let certArrayRef = [cert] as CFArray
        SecTrustSetAnchorCertificates(serverTrust, certArrayRef)
        SecTrustSetAnchorCertificatesOnly(serverTrust, false)
        let trustResult: SecTrustResultType = SecTrustResultType.invalid
        return trustResult
    }
    func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
        if challenge.protectionSpace.authenticationMethod == (NSURLAuthenticationMethodServerTrust) {
            let serverTrust:SecTrust = challenge.protectionSpace.serverTrust!
            var localCertificateTrust = SSLCertificateCreateTrustResult(serverTrust)
            SecTrustEvaluate(serverTrust, &localCertificateTrust)
            if localCertificateTrust == SecTrustResultType.unspecified || localCertificateTrust == SecTrustResultType.proceed || localCertificateTrust == SecTrustResultType.recoverableTrustFailure
            {
                let credential:URLCredential = URLCredential(trust: serverTrust)
                challenge.sender?.use(credential, for: challenge)
                completionHandler(URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust: challenge.protectionSpace.serverTrust!))

            } else {
                let properties = SecTrustCopyProperties(serverTrust)
                completionHandler(URLSession.AuthChallengeDisposition.cancelAuthenticationChallenge, nil)
            }
        }
        else
        {
            completionHandler(URLSession.AuthChallengeDisposition.cancelAuthenticationChallenge, nil);
        }
    }

状况良好

if localCertificateTrust == SecTrustResultType.unspecified || localCertificateTrust == SecTrustResultType.proceed || localCertificateTrust == SecTrustResultType.recoverableTrustFailure

以下类型适用于有效证书

SecTrustResultType.unspecified , SecTrustResultType.proceed

对于无效的证书SecTrustResultType.recoverableTrustFailure

我已经添加了以上三个||条件,以便使用有效和无效的证书,以防您想删除任何可以删除其他类型的证书

于 2019-03-15T05:25:38.210 回答