Forked from pallavtrivedi03/CertificatePinning.swift
Created
February 11, 2022 18:15
-
-
Save EvolverSwiftUI/43ae8cf21fff7d81e8e5fb7ae7b42033 to your computer and use it in GitHub Desktop.
Implementation of SSL pinning (using certifcate)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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