Skip to content

Instantly share code, notes, and snippets.

@mdelete
Created May 23, 2015 20:11
Show Gist options
  • Save mdelete/d9dbc320d5de347c2a85 to your computer and use it in GitHub Desktop.
Save mdelete/d9dbc320d5de347c2a85 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)
}
@samigehi
Copy link

for swift 3

 func connection(connection: NSURLConnection, didReceiveAuthenticationChallenge challenge: URLAuthenticationChallenge) {
            
    if(challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust) {
        var localTrust: SecTrust?
        let serverTrust = challenge.protectionSpace.serverTrust!
        let serverPublicKey = SecTrustCopyPublicKey(serverTrust)
        let certificateData = NSData(contentsOfFile: Bundle.main.path(forResource: "pinning-certificate", ofType: "der")!)
        let localCertificate = SecCertificateCreateWithData(kCFAllocatorDefault, certificateData!)
        let policy = SecPolicyCreateBasicX509()
        
        if SecTrustCreateWithCertificates(localCertificate!, policy, &localTrust) == errSecSuccess {

            let localPublicKey = SecTrustCopyPublicKey(localTrust!)!
            if (localPublicKey as AnyObject).isEqual(serverPublicKey as AnyObject) {
               print("trusted")
                return challenge.sender!.performDefaultHandling!(for: challenge)
            }
        }
    }
    print("not trusted")
    return challenge.sender!.cancel(challenge)
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment