得到错误“身份验证失败,因为远程方已关闭传输流。”

时间:2019-05-26 12:05:27

标签: c#

我正在实现相互认证。

客户端连接已成功建立。

但收到错误消息“由于远程方已关闭传输流,因此身份验证失败。”

这是我的代码:

static void RunClient(string hostName, int port, X509Certificate2Collection certificates)
        {
            // Create a TCP/IP client socket.
            // machineName is the host running the server application.
            TcpClient client = new TcpClient(HostName, port);
            Console.WriteLine("Client connected.");
            // Create an SSL stream that will close the client's stream.
            SslStream sslStream = new SslStream(
                client.GetStream(),
                false, ValidateServerCertificate);
            // The server name must match the name on the server certificate.
            try
            {
                sslStream.AuthenticateAsClient(HostName, certificates, SslProtocols.Tls12, true);

            }
            catch (AuthenticationException e)
            {
                Console.WriteLine("Exception: {0}", e.Message);
                if (e.InnerException != null)
                {
                    Console.WriteLine("Inner exception: {0}", e.InnerException.Message);
                }
                Console.WriteLine("Authentication failed - closing the connection.");
                client.Close();
                return;
            }
            // Encode a test message into a byte array.
            // Signal the end of the message using the "<EOF>".
            byte[] messsage = Encoding.UTF8.GetBytes("Hello from the client.<EOF>");
            // Send hello message to the server. 
            sslStream.Write(messsage);
            sslStream.Flush();
            // Read message from the server.
            string serverMessage = ReadMessage(sslStream);
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine("Server says: {0}", serverMessage);
            Console.ResetColor();
            // Close the client connection.
            client.Close();
            Console.WriteLine("Client closed.");
        }

请帮助我解决此问题。

1 个答案:

答案 0 :(得分:0)

由于接受的SSL协议版本,您可能会收到此错误。

尝试将其更改为以下内容:

try
{
    sslStream.AuthenticateAsClient(_listenerUri, new X509Certificate2Collection(_serverCertificate), SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12, true);
}