ssl - Swift 2 中的公钥固定

标签 ssl swift2 xcode7 pinning tls1.2

我可以使用以下函数与服务器建立 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 中找到一个示例或一段代码。请帮我解决这个问题。

最佳答案

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

}

关于ssl - Swift 2 中的公钥固定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32823571/

相关文章:

linux - 在 ubuntu/linux 上使用 NSJSONSerialization 和 swift

push-notification - 无法注册推送通知(Xcode 7、iOS9)

iOS 9 - 广告资源不可用

tomcat - Spring Boot 重定向到 https

haskell - 如果在 'safe language' 中实现了经过验证的 SSL/TLS,它是否仍然容易受到心脏出血攻击?

.htaccess 使用共享 ssl 证书

ios - 用于 Swift 2.0 的 Alamofire 和 SwiftyJSON

internet-explorer - SSL 不安全项目提示

ios - 如何使计时器在 swift 中与循环一起工作?

swift - 看不到我在 Parse 中发布的消息