temz 2023-03-24 10:21 采纳率: 100%
浏览 80
已结题

求个C# SSL socket的客户端和 服务端代码

求个C# SSL socket的客户端和 服务端代码,得能连的通的

  • 写回答

5条回答 默认 最新

  • 「已注销」 2023-03-24 10:39
    关注

    参考GPT:下面是一个简单的 C# SSL socket 客户端和服务端的示例代码,可以用于测试 SSL socket 的连接。需要注意的是,此示例代码中使用了自签名证书,如果您要在生产环境中使用 SSL socket,请使用受信任的证书。

    服务端代码:

    using System;
    using System.IO;
    using System.Net;
    using System.Net.Security;
    using System.Net.Sockets;
    using System.Security.Authentication;
    using System.Security.Cryptography.X509Certificates;
    using System.Text;
    
    class Server
    {
        static void Main(string[] args)
        {
            TcpListener listener = new TcpListener(IPAddress.Any, 8888);
            listener.Start();
            Console.WriteLine("Server started, waiting for connections...");
    
            while (true)
            {
                TcpClient client = listener.AcceptTcpClient();
                Console.WriteLine("Client connected: " + client.Client.RemoteEndPoint.ToString());
    
                SslStream stream = new SslStream(client.GetStream(), false);
                X509Certificate2 cert = new X509Certificate2("server.pfx", "password");
                stream.AuthenticateAsServer(cert, false, SslProtocols.Tls, true);
    
                StreamReader reader = new StreamReader(stream, Encoding.UTF8);
                StreamWriter writer = new StreamWriter(stream, Encoding.UTF8) { AutoFlush = true };
    
                writer.WriteLine("Welcome to SSL server!");
                string message = reader.ReadLine();
                Console.WriteLine("Received message from client: " + message);
    
                writer.WriteLine("Server received your message: " + message);
                stream.Close();
                client.Close();
                Console.WriteLine("Client disconnected.");
            }
        }
    }
    

    客户端代码:

    using System;
    using System.IO;
    using System.Net.Security;
    using System.Net.Sockets;
    using System.Security.Authentication;
    using System.Security.Cryptography.X509Certificates;
    using System.Text;
    
    class Client
    {
        static void Main(string[] args)
        {
            TcpClient client = new TcpClient("localhost", 8888);
            Console.WriteLine("Connected to server: " + client.Client.RemoteEndPoint.ToString());
    
            SslStream stream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate));
            X509Certificate2 cert = new X509Certificate2("client.pfx", "password");
            stream.AuthenticateAsClient("localhost", new X509Certificate2Collection(cert), SslProtocols.Tls, true);
    
            StreamReader reader = new StreamReader(stream, Encoding.UTF8);
            StreamWriter writer = new StreamWriter(stream, Encoding.UTF8) { AutoFlush = true };
    
            string message = reader.ReadLine();
    Console.WriteLine("Received message from server: " + message);
    
        writer.WriteLine("Hello from SSL client!");
        Console.WriteLine("Sent message to server: Hello from SSL client!");
    
        stream.Close();
        client.Close();
        Console.WriteLine("Disconnected from server.");
    }
    
    private static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
    {
        // In this example, we trust any certificate the server presents.
        // In production code, you should verify that the certificate is issued to the correct server and issued by a trusted certificate authority.
        return true;
    }
    }
    
    

    在此示例中,客户端连接到本地主机的端口 8888,并尝试建立 SSL 连接。客户端使用自签名的证书进行身份验证,并向服务器发送消息。服务器使用相同的自签名证书进行身份验证,并返回接收到的消息。客户端在控制台上输出服务器发送的消息,并发送一条消息作为响应。最后,客户端关闭 SSL 连接和 TcpClient 连接。

    在生产环境中,您应该使用由受信任的证书机构颁发的证书,以确保安全的 SSL 通信。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
  • Leodong. 2023-03-24 10:32
    关注

    该回答引用GPTᴼᴾᴱᴺᴬᴵ,具体如下:

    以下是C# SSL socket的服务端代码:

    using System;
    using System.Net;
    using System.Net.Sockets;
    using System.Security.Cryptography.X509Certificates;
    using System.Net.Security;
    using System.Security.Authentication;
    using System.IO;
    
    class SslTcpServer
    {
        private static X509Certificate serverCertificate = null;
        private static TcpListener listener = null;
    
        public static void RunServer(string certificate)
        {
            serverCertificate = new X509Certificate(certificate);
    
            listener = new TcpListener(IPAddress.Any, 8080);
            listener.Start();
    
            while (true)
            {
                Console.WriteLine("Waiting for a client to connect...");
    
                TcpClient client = listener.AcceptTcpClient();
    
                Console.WriteLine("Client connected. Authenticating...");
    
                SslStream sslStream = new SslStream(client.GetStream(), false);
                sslStream.AuthenticateAsServer(serverCertificate, false, SslProtocols.Tls, true);
    
                Console.WriteLine("Client authenticated. Receiving data...");
    
                byte[] buffer = new byte[2048];
                int bytes = sslStream.Read(buffer, 0, buffer.Length);
    
                Console.WriteLine("Received {0} bytes. Data: {1}", bytes, Encoding.UTF8.GetString(buffer, 0, bytes));
    
                sslStream.Write(Encoding.UTF8.GetBytes("Hello from the server!"));
                sslStream.Flush();
    
                client.Close();
            }
        }
    }
    

    以下是C# SSL socket的客户端代码:

    using System;
    using System.Net.Sockets;
    using System.Security.Authentication;
    using System.Security.Cryptography.X509Certificates;
    using System.Net.Security;
    using System.IO;
    
    class SslTcpClient
    {
        private static X509Certificate clientCertificate = null;
    
        public static void RunClient(string certificate)
        {
            clientCertificate = new X509Certificate(certificate);
    
            TcpClient client = new TcpClient("localhost", 8080);
    
            Console.WriteLine("Client connected. Authenticating...");
    
            SslStream sslStream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate));
            sslStream.AuthenticateAsClient("localhost", new X509CertificateCollection(new X509Certificate[] { clientCertificate }), SslProtocols.Tls, true);
    
            Console.WriteLine("Client authenticated. Sending data...");
    
            sslStream.Write(Encoding.UTF8.GetBytes("Hello from the client!"));
            sslStream.Flush();
    
            byte[] buffer = new byte[2048];
            int bytes = sslStream.Read(buffer, 0, buffer.Length);
    
            Console.WriteLine("Received {0} bytes. Data: {1}", bytes, Encoding.UTF8.GetString(buffer, 0, bytes));
    
            client.Close();
        }
    
        private static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            return true;
        }
    }
    

    如果以上回答对您有所帮助,望采纳~谢谢

    评论 编辑记录
  • 爱吃鱼豆腐 2023-03-24 14:08
    关注

    该回答参考ChatGPT:
    以下是一个C# SSL socket的客户端和服务端代码,它们可以相互通信:
    服务端代码:

    using System;
    using System.Net;
    using System.Net.Sockets;
    using System.Security.Authentication;
    using System.Security.Cryptography.X509Certificates;
    using System.Threading;
    
    namespace SslServer
    {
        class Program
        {
            static void Main(string[] args)
            {
                TcpListener listener = new TcpListener(IPAddress.Any, 1234);
                listener.Start();
                Console.WriteLine("Server started.");
    
                while (true)
                {
                    TcpClient client = listener.AcceptTcpClient();
                    Console.WriteLine("Client connected.");
    
                    Thread thread = new Thread(() => HandleClient(client));
                    thread.Start();
                }
            }
    
            private static void HandleClient(TcpClient client)
            {
                SslStream sslStream = new SslStream(client.GetStream(), false);
                try
                {
                    sslStream.AuthenticateAsServer(GetServerCertificate(), false, SslProtocols.Tls, true);
                    Console.WriteLine("SSL connection established.");
                    byte[] buffer = new byte[1024];
                    int bytesRead = sslStream.Read(buffer, 0, buffer.Length);
                    Console.WriteLine("Received: {0}", Encoding.ASCII.GetString(buffer, 0, bytesRead));
                    sslStream.Write(Encoding.ASCII.GetBytes("Hello from server."));
                }
                catch (Exception e)
                {
                    Console.WriteLine("SSL error: {0}", e.Message);
                }
                finally
                {
                    sslStream.Close();
                    client.Close();
                    Console.WriteLine("Client disconnected.");
                }
            }
    
            private static X509Certificate2 GetServerCertificate()
            {
                X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
                store.Open(OpenFlags.ReadOnly);
    
                X509Certificate2Collection certs = store.Certificates.Find(X509FindType.FindBySubjectName, "localhost", true);
                if (certs.Count == 0)
                {
                    throw new Exception("Server certificate not found.");
                }
    
                return certs[0];
            }
        }
    }
    
    

    客户端代码:

    using System;
    using System.Net.Security;
    using System.Net.Sockets;
    using System.Security.Authentication;
    using System.Security.Cryptography.X509Certificates;
    using System.Text;
    
    namespace SslClient
    {
        class Program
        {
            static void Main(string[] args)
            {
                TcpClient client = new TcpClient();
                client.Connect("localhost", 1234
    
    
    评论
  • 叶秋学长 全栈领域优质创作者 2023-03-24 15:50
    关注

    基于最新版ChatGPT4的回答,望采纳!!!有其他问题也可以询问我哦💕(最新版更智能,功能更加强大):
    以下是一个简单的C# SSL Socket通信的客户端和服务端代码示例:

    服务端代码:

    
    csharp
    Copy code
    using System;
    using System.Net;
    using System.Net.Sockets;
    using System.Security.Authentication;
    using System.Security.Cryptography.X509Certificates;
    using System.Text;
    
    class Program
    {
        static void Main(string[] args)
        {
            TcpListener server = null;
            try
            {
                // 设置本地IP地址和端口号
                IPAddress localAddr = IPAddress.Parse("127.0.0.1");
                int port = 443;
    
                // 创建TCP监听器
                server = new TcpListener(localAddr, port);
    
                // 启动监听
                server.Start();
    
                // 创建SSL证书
                X509Certificate2 serverCertificate = new X509Certificate2("server.pfx", "password");
    
                // 接收连接请求
                TcpClient client = server.AcceptTcpClient();
    
                // 创建SSL流
                SslStream sslStream = new SslStream(client.GetStream(), false);
    
                // 开启SSL握手协议
                sslStream.AuthenticateAsServer(serverCertificate, false, SslProtocols.Tls, true);
    
                // 接收数据
                byte[] buffer = new byte[1024];
                int bytesRead = sslStream.Read(buffer, 0, buffer.Length);
                string message = Encoding.UTF8.GetString(buffer, 0, bytesRead);
                Console.WriteLine("Received: {0}", message);
    
                // 发送响应
                string responseMessage = "Hello, client!";
                byte[] responseBuffer = Encoding.UTF8.GetBytes(responseMessage);
                sslStream.Write(responseBuffer, 0, responseBuffer.Length);
                sslStream.Flush();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            finally
            {
                if (server != null)
                {
                    server.Stop();
                }
            }
        }
    }
    
    

    客户端代码:

    csharp
    Copy code
    using System;
    using System.Net.Security;
    using System.Net.Sockets;
    using System.Security.Authentication;
    using System.Security.Cryptography.X509Certificates;
    using System.Text;
    
    class Program
    {
        static void Main(string[] args)
        {
            TcpClient client = null;
            try
            {
                // 设置远程IP地址和端口号
                string server = "127.0.0.1";
                int port = 443;
    
                // 创建TCP客户端
                client = new TcpClient(server, port);
    
                // 创建SSL流
                SslStream sslStream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
    
                // 创建SSL证书
                X509Certificate2 clientCertificate = new X509Certificate2("client.pfx", "password");
    
                // 开启SSL握手协议
                sslStream.AuthenticateAsClient(server, new X509CertificateCollection(new X509Certificate[] { clientCertificate }), SslProtocols.Tls, false);
    
                // 发送数据
                string message = "Hello, server!";
                byte[] buffer = Encoding.UTF8.GetBytes(message);
                sslStream.Write(buffer, 0, buffer.Length);
                sslStream.Flush();
    
                // 接收响应
                buffer = new byte[1024];
                int bytesRead = sslStream.Read(buffer, 0, buffer.Length);
                string responseMessage = Encoding.UTF8.GetString(buffer, 0, bytesRead);
                Console.WriteLine("Received: {0}", responseMessage);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            finally
            {
                if (client != null)
                {
                    client
    
    
    评论
  • CSDN-Ada助手 CSDN-AI 官方账号 2023-03-27 15:16
    关注
    不知道你这个问题是否已经解决, 如果还没有解决的话:
    • 这有个类似的问题, 你可以参考下: https://ask.csdn.net/questions/721590
    • 我还给你找了一篇非常好的博客,你可以看看是否有帮助,链接:关于SSL握手的错误解决
    • 除此之外, 这篇博客: SSL协议原理中的 Server Key Exchange消息数据包 部分也许能够解决你的问题, 你可以仔细阅读以下内容或者直接跳转源博客中阅读:

      在这里插入图片描述

      在Diffie-Hellman中,客户端无法自行计算预主密钥; 双方都有助于计算它,因此客户端需要从服务器获取Diffie-Hellman公钥。

      由上图可知,此时密钥交换也由签名保护。


    如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^
    评论
查看更多回答(4条)

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 3月27日
  • 已采纳回答 3月24日
  • 创建了问题 3月24日

悬赏问题

  • ¥15 询问MYSQL查询SQLSERVER数据表并比较差异后,更新MYSQL的数据表
  • ¥15 关于#前端#的问题,请各位专家解答!
  • ¥15 最小生成树问题 Prim算法和Kruskal算法
  • ¥25 医院住院病人呼叫器设计
  • ¥15 不想和现在的团队合作了,怎么避免他们对程序动手脚
  • ¥30 c++类和数组实验代码
  • ¥20 C语言字符串不区分大小写字典排序相关问题
  • ¥15 关于#python#的问题:我希望通过逆向技术爬取1688搜索页下滑加载的数据
  • ¥15 关于Linux的终端里,模拟实现一个带口令保护的屏保程序遇到的输入输出的问题!(语言-c语言)
  • ¥30 请问,这个嵌入式Linux系统怎么分析,crc检验区域在哪