Created
November 13, 2016 19:56
-
-
Save B-Lach/4e12ce6239636e368d21f16e6ac492c7 to your computer and use it in GitHub Desktop.
Public Key Pinning 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
struct Constants { | |
static let resource = "certificate" | |
static let type = "der" | |
} | |
// https://infinum.co/the-capsized-eight/articles/how-to-make-your-ios-apps-more-secure-with-ssl-pinning | |
extension NetworkManager: URLSessionDelegate { | |
func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { | |
guard let serverTrust = challenge.protectionSpace.serverTrust, let certificate = SecTrustGetCertificateAtIndex(serverTrust, 0) else { return } | |
// Set SSL policies for domain name check | |
let policies = NSMutableArray(); | |
policies.add(SecPolicyCreateSSL(true, (challenge.protectionSpace.host as CFString?))) | |
SecTrustSetPolicies(serverTrust, policies); | |
// Evaluate server certificate | |
var result: SecTrustResultType = SecTrustResultType(rawValue: 0)! | |
SecTrustEvaluate(serverTrust, &result) | |
let isServerTrusted:Bool = result.rawValue == SecTrustResultType.unspecified.rawValue || result.rawValue == SecTrustResultType.proceed.rawValue | |
// Get local and remote cert data | |
let remoteCertificateData:NSData = SecCertificateCopyData(certificate) | |
let pathToCert = Bundle.main.path(forResource: Constants.resource, ofType: Constants.type) | |
let localCertificate:NSData = NSData(contentsOfFile: pathToCert!)! | |
// Compare Data | |
if (isServerTrusted && remoteCertificateData.isEqual(to: localCertificate as Data)) { | |
let credential = URLCredential(trust: serverTrust) | |
print("Certificate matching = true") | |
completionHandler(.useCredential, credential) | |
} else { | |
print("Certificate matching = false") | |
completionHandler(.cancelAuthenticationChallenge, nil) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment