Forked from pallavtrivedi03/CertificatePinning.swift
Created
January 29, 2023 21:40
-
-
Save dimebt/5371bac4d51ced72b2863aa1d82063e6 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