Skip to content

Instantly share code, notes, and snippets.

@vani2
Last active June 27, 2021 09:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vani2/819a45d0951af6ac62f7c6a7f0d8c263 to your computer and use it in GitHub Desktop.
Save vani2/819a45d0951af6ac62f7c6a7f0d8c263 to your computer and use it in GitHub Desktop.
SSL Pinning PK Example
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