Last active
June 27, 2021 09:17
-
-
Save vani2/819a45d0951af6ac62f7c6a7f0d8c263 to your computer and use it in GitHub Desktop.
SSL Pinning PK Example
This file contains 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
override func urlSession( | |
_ session: URLSession, | |
didReceive challenge: URLAuthenticationChallenge, | |
completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { | |
// 1 | |
guard | |
challenge.protectionSpace.host == baseURL.host, | |
challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust, | |
let trust = challenge.protectionSpace.serverTrust | |
else { | |
completionHandler(.performDefaultHandling, nil) | |
return | |
} | |
// 2 | |
var error: CFError? | |
let success = SecTrustEvaluateWithError(trust, &error) | |
guard | |
success, | |
let serverCertificate = SecTrustGetCertificateAtIndex(trust, 0) | |
else { | |
completionHandler(.cancelAuthenticationChallenge, nil) | |
return | |
} | |
// 3 | |
let serverCertificateCFData = SecCertificateCopyData(serverCertificate) | |
guard | |
let serverCertData = CFDataGetBytePtr(serverCertificateCFData), | |
let filePath = Bundle.main.path(forResource: "production-api", ofType: "cer") | |
else { | |
completionHandler(.cancelAuthenticationChallenge, nil) | |
return | |
} | |
let fileURL = URL(fileURLWithPath: filePath) | |
let serverCert = Data(bytes: serverCertData, count: CFDataGetLength(serverCertificateCFData)) | |
// 4 | |
guard | |
let fileCert = try? Data(contentsOf: fileURL), | |
serverCert == fileCert | |
else { | |
completionHandler(.cancelAuthenticationChallenge, nil) | |
return | |
} | |
completionHandler(.performDefaultHandling, nil) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment