示例代码swift2与tls连接并使用certficate发送

时间:2016-07-19 09:33:30

标签: swift sockets ssl swift2 certificate

我尝试使用TLS连接,但我不知道我的代码中有什么问题(swift 2)应该发送什么样的certyficate格式?我怎么修这个代码?或编写新的示例代码以便将来使用?

 class Sock: NSObject {
       var socket: GCDAsyncSocket

          override init()
          {
             self.socket = GCDAsyncSocket()
             super.init()
          }

        func connect()  {
            do
            {
                 self.socket = GCDAsyncSocket(delegate: self, delegateQueue:dispatch_get_main_queue())
                 print("try connect")
                 try socket.connectToHost("10.1.1.1", onPort: 5678)
                 while !socket.isConnected
                 {
                   print("polaczono dalej " + String(self.socket.isConnected))

                 }
             print("connect is " + String(self.socket.isConnected))

                         }
            catch let err as NSError
            {
             print("Error " + String(err))
            }
        }

       //override
        func socket(sock: GCDAsyncSocket!, didConnectToHost host: String!, port: UInt16)
        {
          do {
            //read from file
            let myFileURL = NSBundle.mainBundle().URLForResource("ca", withExtension: "der")!
            let certificateCa = try! String(contentsOfURL: myFileURL, encoding: NSISOLatin1StringEncoding)

            //decioding certyficate
            print("client: " + functions.getCertificate().fromBase64())
            print("ca: " + certificateCa)
            let certyfikat: CFArray = [certificateCa, functions.getCertificate().fromBase64() ] //cert.stringToNsData(),

            self.socket.synchronouslySetDelegate(self)

//在这个地方我想保持连接但是在startTLS连接之后是折扣                 self.socket.startTLS([                     GCDAsyncSocketSSLProtocolVersionMin:NSNumber(int:SSLProtocol.TLSProtocol12.rawValue),                     GCDAsyncSocketSSLCipherSuites:acceptableCipherSuites,                     GCDAsyncSocketManuallyEvaluateTrust:false,                     kCFStreamPropertySSLPeerTrust:" X509",                     kCFURLNameKey:" Proget Software",                     kCFStreamSSLCertificates:certyfikat,

            ])

            print("Did conect is still run TLS: " + String(socket.isConnected))

            let request:String = "test test test"
            let data:NSData = request.dataUsingEncoding(NSUTF8StringEncoding)!
            print("Message with is sending: ")
            print(data)
            self.socket.writeData(data, withTimeout: -1.0, tag: 0)
          }
          catch let err as NSError
          {
             print("err socket")
             print(String(err))
          }
       }

0 个答案:

没有答案