【问题标题】:Public Key Pinning in Swift 2Swift 2 中的公钥固定
【发布时间】:2015-09-28 12:56:50
【问题描述】:

我可以使用以下函数与服务器建立 HTTP 连接。

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
}

现在在同一个函数中,我们要在我有一个自签名证书的地方建立 HTTPS 连接。我想知道为了实现公钥固定,在编写这段代码时我需要使用自签名证书执行哪些步骤。

我在互联网上搜索,但在 NSURLSession 和 swift 2 中没有找到一个示例或一段代码。请帮助我。

【问题讨论】:

标签: ssl swift2 xcode7 pinning tls1.2


【解决方案1】:

以下代码可能会有所帮助: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!))
  }

}

【讨论】:

    猜你喜欢
    • 2019-07-28
    • 1970-01-01
    • 2017-12-17
    • 2019-10-03
    • 2021-09-17
    • 2017-10-20
    • 1970-01-01
    • 1970-01-01
    • 2016-12-16
    相关资源
    最近更新 更多