我第一次尝试在iOS中实现套接字。我得到了一个.cer文件,该文件需要用于正确连接服务器。最初SecCertificateCreateWithData崩溃了,所以经过研究,我最终将.cer文件转换为der格式(openssl x509 -in cert.cer -outform der -out certder.der
),然后iOS似乎接受了它。
mSocket = GCDAsyncSocket(delegate: self, delegateQueue: DispatchQueue.main)
do {
print("Connecting...")
try mSocket.connect(toHost: host, onPort: port)
} catch let error {
print(error)
}
// ...
public func socket(_ socket: GCDAsyncSocket, didConnectToHost host: String, port p:UInt16){
print("didConnectToHost!\n");
let cerPath = Bundle.main.path(forResource: "certder", ofType: "der")
let data: NSData = try! Data(contentsOf: URL(fileURLWithPath: cerPath!)) as! NSData
let cert: SecCertificate = SecCertificateCreateWithData(nil, data)!
var certs: CFArray = [cert] as CFArray
mSocket.startTLS([
kCFStreamSSLCertificates as String: certs,
kCFStreamSSLValidatesCertificateChain as String: false as NSNumber,
kCFStreamSSLLevel as String:kCFStreamSocketSecurityLevelNegotiatedSSL,
//GCDAsyncSocketSSLCipherSuites: acceptableCipherSuites as NSObject,
GCDAsyncSocketSSLProtocolVersionMin: NSNumber(value: SSLProtocol.tlsProtocol12.rawValue),
GCDAsyncSocketManuallyEvaluateTrust: false as NSNumber,
kCFStreamPropertySSLPeerTrust as String: "X509" as NSString])
}
但是,我的日志是:
Connecting...
didConnectToHost!
didDisconnect! Optional(Error Domain=GCDAsyncSocketErrorDomain Code=8 "Error in SSLSetCertificate" UserInfo={NSLocalizedDescription=Error in SSLSetCertificate})
表示证书的附加方式有问题。缺少什么?
查看文档,我怀疑certs数组中索引为0的项必须为SecIdentity。如何获得SecIdentity?