Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

samigehi commented Aug 18, 2017

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