Skip to content

Instantly share code, notes, and snippets.

@pallavtrivedi03
Created September 3, 2021 10:02
Show Gist options
  • Save pallavtrivedi03/ef13f9b719d6cd845c9515871bf0117c to your computer and use it in GitHub Desktop.
Save pallavtrivedi03/ef13f9b719d6cd845c9515871bf0117c to your computer and use it in GitHub Desktop.
Implementation of SSL pinning (using certifcate)
func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
guard let serverTrust = challenge.protectionSpace.serverTrust else {
completionHandler(.cancelAuthenticationChallenge, nil);
return
}
let certificate = SecTrustGetCertificateAtIndex(serverTrust, 0)
// SSL Policies for domain name check
let policy = NSMutableArray()
policy.add(SecPolicyCreateSSL(true, challenge.protectionSpace.host as CFString))
//evaluate server certifiacte
let isServerTrusted = SecTrustEvaluateWithError(serverTrust, nil)
//Local and Remote certificate Data
let remoteCertificateData:NSData = SecCertificateCopyData(certificate!)
let pathToCertificate = Bundle.main.path(forResource: "mocky", ofType: "cer")
let localCertificateData:NSData = NSData(contentsOfFile: pathToCertificate!)!
//Compare certificates
if(isServerTrusted && remoteCertificateData.isEqual(to: localCertificateData as Data)){
let credential:URLCredential = URLCredential(trust:serverTrust)
print("Certificate pinning is successfully completed")
completionHandler(.useCredential,nil)
}
else {
DispatchQueue.main.async {
self.showAlert(text: "SSL Pinning", message: "Pinning failed")
}
completionHandler(.cancelAuthenticationChallenge,nil)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment