Created
May 23, 2015 20:11
-
-
Save mdelete/d9dbc320d5de347c2a85 to your computer and use it in GitHub Desktop.
Swift iOS SSL public key pinning
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
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
for swift 3