使用Swift中的SSL

时间:2018-02-19 00:30:44

标签: cocoaasyncsocket

我正在尝试使用CocoaAsyncSocket通过SSL连接到IRC,我似乎在某处出错了。这是我正在使用的代码:

func identity(named name: String, password: String) throws -> SecIdentity {
        let url = Bundle.main.url(forResource: name, withExtension: "p12")!
        let data = try Data(contentsOf: url)
        var importResult: CFArray? = nil
        let err = SecPKCS12Import(
            data as NSData,
            [kSecImportExportPassphrase as String: password] as NSDictionary,
            &importResult
        )
        guard err == errSecSuccess else {
            throw NSError(domain: NSOSStatusErrorDomain, code: Int(err), userInfo: nil)
        }
        let identityDictionaries = importResult as! [[String:Any]]
        return identityDictionaries[0][kSecImportItemIdentity as String] as! SecIdentity
}

public func socket(_ sock: GCDAsyncSocket, didConnectToHost host: String, port: UInt16) {
        let sslSettings = NSMutableDictionary()

        sslSettings[kCFStreamSSLCertificates] = try! identity(named: "ssl", password: "")
        sslSettings.addEntries(from: [kCFStreamSSLLevel: StreamSocketSecurityLevel.negotiatedSSL, kCFStreamSSLPeerName: host, kCFStreamSSLValidatesCertificateChain: false])
        socket?.startTLS(sslSettings as! [String : NSObject])
}

我刚刚收到“远程端口关闭的套接字”错误。我生成的证书可能存在问题吗?似乎无法在任何地方找到有关如何生成适当证书的任何信息。

0 个答案:

没有答案