Skip to content

Instantly share code, notes, and snippets.

@funky-monkey
Forked from mdelete/gist:d9dbc320d5de347c2a85
Last active October 6, 2016 08:22
Show Gist options
  • Save funky-monkey/b1db4b160688aca22c7cea200234f1c5 to your computer and use it in GitHub Desktop.
Save funky-monkey/b1db4b160688aca22c7cea200234f1c5 to your computer and use it in GitHub Desktop.
Swift iOS SSL public key pinning
func connection(connection: NSURLConnection, didReceiveAuthenticationChallenge challenge: NSURLAuthenticationChallenge) {
if(challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust) {
var localTrust: Unmanaged<SecTrust>?
let serverTrust = challenge.protectionSpace.serverTrust!
let serverPublicKey = SecTrustCopyPublicKey(serverTrust).takeRetainedValue();
let certificateData = NSData(contentsOfFile: NSBundle.mainBundle().pathForResource("pinning-certificate", ofType: "der")!)
let localCertificate = SecCertificateCreateWithData(kCFAllocatorDefault, certificateData).takeRetainedValue();
let policy = SecPolicyCreateBasicX509().takeRetainedValue()
if SecTrustCreateWithCertificates(localCertificate, policy, &localTrust) == errSecSuccess {
let localTrustRef = localTrust!.takeRetainedValue()
let localPublicKey = SecTrustCopyPublicKey(localTrustRef)!.takeRetainedValue();
if (localPublicKey as AnyObject).isEqual(serverPublicKey as AnyObject) {
println("trusted")
return challenge.sender.performDefaultHandlingForAuthenticationChallenge!(challenge)
}
}
}
println("not trusted")
return challenge.sender.cancelAuthenticationChallenge(challenge)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment