TLS - TCP 客户端在 SslStream.AuthenticateAsClient(servername) 上进行身份验证,但服务器未连接到任何客户端,所有客户端都在本地计算机上 C#

TLS - TCP Client Authenticates on SslStream.AuthenticateAsClient(servername) but the server is not connecting to any Client, all on local machine C#

我是网络编程的新手,我需要有关通过 TLS 连接 TCP 客户端的帮助。我得到了一个已经编码的项目,它附带了证书和提供的 public 密钥。我已经在我的本地机器上安装了 pfx 证书,并编码了一个新的 TCP Listener/Server 和指向本地主机的 TCP 客户端,如下所示:

客户

static void Main(string[] args)
    {
        string server = "localhost";
        TcpClient client = new TcpClient(server, 5997);
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;

        //client.Connect(server, 5997);//connection without TLS - authenticating properly

        using (SslStream sslStream = new SslStream(client.GetStream(), false,
            new RemoteCertificateValidationCallback(ValidateServerCertificate), null))
        {
            try
            {
                var servername = "myAuthenticatingServerName";//the server name must be the same as the one on the server certificate
                sslStream.AuthenticateAsClient(servername);

                try
                {
                    Console.WriteLine("Client Connected...");

                    // 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.WriteLine("Server says: {0}", serverMessage);
                    // Close the client connection.
                    client.Close();
                    Console.WriteLine("Client closed.");

                }

                catch (Exception e)
                {
                    Console.WriteLine("Error..... " + e.StackTrace);
                }
            }
            catch (AuthenticationException e)
            {
                Console.WriteLine($"Error: { e.Message}");
                if (e.InnerException != null)
                {
                    Console.WriteLine($"Inner exception: {e.InnerException.Message}");
                }
                Console.WriteLine("Authentication failed - closing the connection.");
                client.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
                Console.WriteLine("Authentication failed - closing the connection.");
                client.Close();
            }

        }
        client.Close();
        Console.WriteLine($"Connection closed at {DateTime.Now}.");
        Console.ReadLine();
    }

    static string ReadMessage(SslStream sslStream)
    {
        // Read the  message sent by the server.
        // The end of the message is signaled using the
        // "<EOF>" marker.
        byte[] buffer = new byte[2048];
        StringBuilder messageData = new StringBuilder();
        int bytes = -1;
        do
        {
            try
            {
                bytes = sslStream.Read(buffer, 0, buffer.Length);
            }
            catch (Exception ex)
            {

                throw ex;
            }


            // Use Decoder class to convert from bytes to UTF8
            // in case a character spans two buffers.
            Decoder decoder = Encoding.UTF8.GetDecoder();
            char[] chars = new char[decoder.GetCharCount(buffer, 0, bytes)];
            decoder.GetChars(buffer, 0, bytes, chars, 0);
            messageData.Append(chars);
            // Check for EOF.
            if (messageData.ToString().IndexOf("<EOF>") != -1)
            {
                break;
            }
        } while (bytes != 0);

        return messageData.ToString();
    }
    public static bool ValidateServerCertificate(object sender, X509Certificate certificate,
    X509Chain chain, SslPolicyErrors sslPolicyErrors)
    {
        if (sslPolicyErrors == SslPolicyErrors.None)
            return true;

        Console.WriteLine($"Certificate error: {sslPolicyErrors}");

        // Do not allow this client to communicate with unauthenticated servers.
        return false;
    }

服务器

  public sealed class SslTcpServer
{
    static X509Certificate2 serverCertificate = null;
    // The certificate parameter specifies the name of the file 
    // containing the machine certificate.
    public static void RunServer(X509Certificate2 certificate)
    {
        serverCertificate = certificate;
        // Create a TCP/IP (IPv4) socket and listen for incoming connections.
        TcpListener listener = new TcpListener(IPAddress.Any, 8080);
        listener.Start();
        while (true)
        {
            Console.WriteLine("Waiting for a client to connect...");
            // Application blocks while waiting for an incoming connection.
            // Type CNTL-C to terminate the server.
            TcpClient client = listener.AcceptTcpClient();
            ProcessClient(client);
        }
    }
    static void ProcessClient(TcpClient client)
    {
        // A client has connected. Create the 
        // SslStream using the client's network stream.
        SslStream sslStream = new SslStream(
            client.GetStream(), false);
        // Authenticate the server but don't require the client to authenticate.
        try
        {
            sslStream.AuthenticateAsServer(serverCertificate, clientCertificateRequired: false, enabledSslProtocols: SslProtocols.Tls, checkCertificateRevocation: true);

            // Display the properties and settings for the authenticated stream.
            DisplaySecurityLevel(sslStream);
            DisplaySecurityServices(sslStream);
            DisplayCertificateInformation(sslStream);
            DisplayStreamProperties(sslStream);

            // Set timeouts for the read and write to 5 seconds.
            sslStream.ReadTimeout = 5000;
            sslStream.WriteTimeout = 5000;
            // Read a message from the client.   
            Console.WriteLine("Waiting for client message...");
            string messageData = ReadMessage(sslStream);
            Console.WriteLine("Received: {0}", messageData);

            // Write a message to the client.
            byte[] message = Encoding.UTF8.GetBytes("Hello from the server.");
            Console.WriteLine("Sending hello message.");
            sslStream.Write(message);
        }
        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.");
            sslStream.Close();
            client.Close();
            return;
        }
        finally
        {
            // The client stream will be closed with the sslStream
            // because we specified this behavior when creating
            // the sslStream.
            sslStream.Close();
            client.Close();
        }
    }
    static string ReadMessage(SslStream sslStream)
    {
        // Read the  message sent by the client.
        // The client signals the end of the message using the
        // "<EOF>" marker.
        byte[] buffer = new byte[2048];
        StringBuilder messageData = new StringBuilder();
        int bytes = -1;
        do
        {
            // Read the client's test message.
            bytes = sslStream.Read(buffer, 0, buffer.Length);

            // Use Decoder class to convert from bytes to UTF8
            // in case a character spans two buffers.
            Decoder decoder = Encoding.UTF8.GetDecoder();
            char[] chars = new char[decoder.GetCharCount(buffer, 0, bytes)];
            decoder.GetChars(buffer, 0, bytes, chars, 0);
            messageData.Append(chars);
            // Check for EOF or an empty message.
            if (messageData.ToString().IndexOf("<EOF>") != -1)
            {
                break;
            }
        } while (bytes != 0);

        return messageData.ToString();
    }
    static void DisplaySecurityLevel(SslStream stream)
    {
        Console.WriteLine("Cipher: {0} strength {1}", stream.CipherAlgorithm, stream.CipherStrength);
        Console.WriteLine("Hash: {0} strength {1}", stream.HashAlgorithm, stream.HashStrength);
        Console.WriteLine("Key exchange: {0} strength {1}", stream.KeyExchangeAlgorithm, stream.KeyExchangeStrength);
        Console.WriteLine("Protocol: {0}", stream.SslProtocol);
    }
    static void DisplaySecurityServices(SslStream stream)
    {
        Console.WriteLine("Is authenticated: {0} as server? {1}", stream.IsAuthenticated, stream.IsServer);
        Console.WriteLine("IsSigned: {0}", stream.IsSigned);
        Console.WriteLine("Is Encrypted: {0}", stream.IsEncrypted);
    }
    static void DisplayStreamProperties(SslStream stream)
    {
        Console.WriteLine("Can read: {0}, write {1}", stream.CanRead, stream.CanWrite);
        Console.WriteLine("Can timeout: {0}", stream.CanTimeout);
    }
    static void DisplayCertificateInformation(SslStream stream)
    {
        Console.WriteLine("Certificate revocation list checked: {0}", stream.CheckCertRevocationStatus);

        X509Certificate localCertificate = stream.LocalCertificate;
        if (stream.LocalCertificate != null)
        {
            Console.WriteLine("Local cert was issued to {0} and is valid from {1} until {2}.",
                localCertificate.Subject,
                localCertificate.GetEffectiveDateString(),
                localCertificate.GetExpirationDateString());
        }
        else
        {
            Console.WriteLine("Local certificate is null.");
        }
        // Display the properties of the client's certificate.
        X509Certificate remoteCertificate = stream.RemoteCertificate;
        if (stream.RemoteCertificate != null)
        {
            Console.WriteLine("Remote cert was issued to {0} and is valid from {1} until {2}.",
                remoteCertificate.Subject,
                remoteCertificate.GetEffectiveDateString(),
                remoteCertificate.GetExpirationDateString());
        }
        else
        {
            Console.WriteLine("Remote certificate is null.");
        }
    }

    public static int Main(string[] args)
    {
        RunServer(Certificate.GetCertificate());
        return 0;
    }
}

public class Certificate
{


    public static X509Certificate2 GetCertificate()
    {
        string certificatePath = ConfigurationManager.AppSettings["certificatePath"].ToString();
        var stream = File.OpenRead(certificatePath);
        return new X509Certificate2(ReadStream(stream), "mypassword");
    }

    private static byte[] ReadStream(Stream input)
    {
        byte[] buffer = new byte[16 * 1024];
        using (MemoryStream ms = new MemoryStream())
        {
            int read;
            while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
            {
                ms.Write(buffer, 0, read);
            }
            return ms.ToArray();
        }
    }
}

我的问题是客户端运行正常,甚至在

上进行了身份验证

sslStream.AuthenticateAsClient(servername);

但是服务器在

上没有获得任何连接

TcpClient client = listener.AcceptTcpClient(); ProcessClient(client);

我是漏掉了什么,还是做错了什么?另外,是否值得重新开始,获得新证书等?

On the server-side you are listening to port 8080 and on the client-side your are connecting to port 5997. To be more specific your server is hosting [YourIP]:8080 and your client is trying to connect to [YourIP]:5997


此外 Tls 和 SSL 通常在端口 443 上使用。客户端和服务器端口需要相同,以便它们可以相互连接。


我也 不确定 c# 是否将 'localhost' 识别为 'YourIP' 最好打开你的 cmd(以防你使用 windows) 输入 'ipconfig ' 按回车键并查找并使用您的 IPv4 地址