是否可以CFStream
使用 TLS 1.2 进行通信?如果是,最好的方法是什么?设置 aSSLContext
或设置CFReadStreamSetProperty
? 不幸的是,我找不到任何例子。
问问题
696 次
1 回答
1
这是我的代码,如果有人也在搜索这个:
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()
}
于 2017-10-17T21:09:03.187 回答