Amit Raj
Amit Raj

Reputation: 1388

Public Key Pinning in Swift 2

I am able to establish an HTTP connection with the server using the following function.

func isHostConnected(jsonString:NSDictionary, var retryCounter: Int) -> NSDictionary
{

    let request = NSMutableURLRequest(URL: NSURL(string: "http://***.*.*.**:****/")!)

    do {
        request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(jsonString, options: [])
    } catch {
        //error = error1
        request.HTTPBody = nil
    }
    request.timeoutInterval = 45.0 //(number as! NSTimeInterval)
    request.HTTPMethod = "POST"
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    request.setValue("gzip", forHTTPHeaderField: "Accept-encoding")

    var JSONdata: AnyObject = ["" : ""] as Dictionary<String, String>
    //print(JSONdata)

    if retryCounter == 0 {
        JSONdata = ["0" : "0"] as Dictionary<String, String>
        return (JSONdata) as! NSDictionary
    }
    retryCounter--

    let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
    var responseCode = -1

    let group = dispatch_group_create()
    dispatch_group_enter(group)

    print("session.dataTaskWithRequest")
    delayTimer(1.0){

        session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
            if let httpResponse = response as? NSHTTPURLResponse {
                responseCode = httpResponse.statusCode
                let JSONresdata: AnyObject = (try! NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers))
                JSONdata = JSONresdata as! NSDictionary
            }
            dispatch_group_leave(group)
        }).resume()
    }

    dispatch_group_wait(group, DISPATCH_TIME_FOREVER)
    print("responseCode == 200: \(responseCode)")
    if responseCode != 200 {
        print("retryCounter: \(retryCounter)")
        self.isHostConnected(jsonString,retryCounter: retryCounter)
    }
    return (JSONdata) as! NSDictionary
}

Now in the same function we want to establish HTTPS connection where I have a self signed certificate. I want to know for implementing the public key pinning which steps I need to follow with my self signed certificate with writing the piece of code.

I searched on the internet but I did not find a single example or piece of code for this in NSURLSession and swift 2. Please help me with this.

Upvotes: 0

Views: 1284

Answers (1)

Karlos
Karlos

Reputation: 1661

The following code might be helpful: link

 import UIKit
 import Foundation
 class ViewController: UIViewController, NSURLSessionDelegate {

     override func viewDidLoad() {
          super.viewDidLoad()
         httpGet(NSMutableURLRequest(URL: NSURL(string: "https://example.com")!))
     }

    func httpGet(request: NSMutableURLRequest!) {


        let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
        session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in


       }).resume()
   }


  func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) {
   completionHandler(NSURLSessionAuthChallengeDisposition.UseCredential, NSURLCredential(forTrust: challenge.protectionSpace.serverTrust!))
  }

}

Upvotes: 1

Related Questions