2017-10-17 64 views
0

是否可以通過CFStream與TLS 1.2進行通信?如果是,那麼最好的方法是什麼?設置SSLContext或設置CFReadStreamSetProperty?不幸的是我找不到任何這樣的例子。帶TLS的CFStream

回答

0

這裏是我的代碼,如果有人也尋找這樣的:

var readStream: Unmanaged<CFReadStream>? 
var writeStream: Unmanaged<CFWriteStream>? 
var inputStream: InputStream! 
var outputStream: OutputStream! 

func connectToServer(host: String, port: Int, ssl: Bool=true) throws { 
    self.ssl = ssl 

    // Create StreamPair 
    CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, host as CFString, UInt32(port), &readStream, &writeStream) 

    // CFStreamCreatePairWithSocketToHost creates unmanaged CFReadStreams. So let's take the retained value 
    // we have to release those values! 
    inputStream = readStream!.takeRetainedValue() 
    outputStream = writeStream!.takeRetainedValue() 

    if ssl == true { 
     let dict = [ 
      kCFStreamSSLValidatesCertificateChain: kCFBooleanFalse,  // allow self-signed certificate 
      kCFStreamSSLLevel: "kCFStreamSocketSecurityLevelTLSv1_2" // don't understand, why there isn't a constant for version 1.2 
      ] as CFDictionary 

     let sslSetRead = CFReadStreamSetProperty(inputStream, CFStreamPropertyKey(kCFStreamPropertySSLSettings), dict) 
     let sslSetWrite = CFWriteStreamSetProperty(outputStream, CFStreamPropertyKey(kCFStreamPropertySSLSettings), dict) 

     if sslSetRead == false || sslSetWrite == false { 
      throw ConnectionError.sslConfigurationFailed 
     } 
    } 

    // set the delegate of the streams 
    inputStream.delegate = self 
    outputStream.delegate = self 

    // schedule the streams for the runLoop 
    inputStream.schedule(in: .current, forMode: .commonModes) 
    outputStream.schedule(in: .current, forMode: .commonModes) 

    // open the streams 
    inputStream.open() 
    outputStream.open() 
}