我目前有一个特定的场景。
在 didReceiveAuthenticationChallenge
上,对于 URLRequest 任务,我需要检查 CA 证书是否与我的应用程序包中的 CA 证书相同,如果没有正常评估链。
这是我的代码:
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didReceiveChallenge challenge: NSURLAuthenticationChallenge!, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void)!){
if let trust = challenge.protectionSpace.serverTrust, challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust, self.trust(chain: trust) {
completionHander(URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust: trust))
return
}
completionHander(URLSession.AuthChallengeDisposition.cancelAuthenticationChallenge, URLCredential(trust: challenge.protectionSpace.serverTrust!))
}
func trust(chain: SecTrust) -> Bool {
var trusted = false
if let certificate = SecTrustGetCertificateAtIndex(chain, 0) {
// HERE I NEED TO COMPARE THE CERTIFICATE WITH MY LOCAL CERTIFICATE
trusted = self.trust(certificate: certificate)
}
if !trusted {
// Evaluate normal chain
var secResult = SecTrustResultType.invalid
SecTrustEvaluate(chain, &secResult)
trusted = secResult == .proceed
}
return trusted
}
问题是:这个程序正确吗? 以及如何将服务器 CA 证书与本地证书进行比较?