引言 
   有个项目中用到了Socket ssl通信,在此记录一下.

证书

   Socket ssl需要用到证书用来校验身份,而作为调试,我们只需用测试证书即可.

   有个工具可以很方便地制作测试证书,下载地址为http://supersocket.codeplex.com/releases/view/59311

   首先, 输入Common Name,密码和保存路径后,我们可以得到包含私钥的证书server.pfx.

   然后,安装证书到电脑中,在IE选项中导出一份证书作为client.cer.

客户端

   使用客户端的电脑需要安装client.cer到<受信任的根证书颁发机构>,且要把证书放在程序目录中,具体代码如下

 class Program
    {
        private static SslStream _sslStream;

        static void Main(string[] args)
        {

            try
            {
                TcpClient client = new TcpClient("127.0.0.1", 6000);
                Console.WriteLine("Client connected.");
                _sslStream = new SslStream(
                   client.GetStream(),
                   false,
                   new RemoteCertificateValidationCallback(ValidateServerCertificate),
                   null
                   );

             
                X509CertificateCollection certs = new X509CertificateCollection();
                X509Certificate cert = X509Certificate.CreateFromCertFile(System.Environment.CurrentDirectory + @"\" + "client.cer");
                certs.Add(cert);
                //验证证书
                try
                {
                    _sslStream.AuthenticateAsClient("test", certs, SslProtocols.Tls, false);
                }
                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();
                    Console.ReadLine();
                    return;
                }

                //开始读取消息
                Task.Factory.StartNew(() =>
                {
                    ReadMessage(_sslStream);
                });

                Console.WriteLine("按Q退出程序");
                string message = "";
                message = Console.ReadLine() + "<EOF>";
                while (message != "Q")
                {
                    byte[] bytes = Encoding.UTF8.GetBytes(message);
                    _sslStream.Write(bytes);
                    _sslStream.Flush();
                    Console.WriteLine("send:" + message);
                    message = Console.ReadLine() + "<EOF>";
                }

                client.Close();
            }
            catch (Exception ex)
            {
                
                Console.WriteLine(ex);
                Console.ReadLine();
            }
        }

        public static void ReadMessage(SslStream sslStream)
        {
            byte[] buffer = new byte[2048];
            StringBuilder messageData = new StringBuilder();
            int bytes = -1;
            do
            {
                bytes = sslStream.Read(buffer, 0, buffer.Length);
                Decoder decoder = Encoding.UTF8.GetDecoder();
                char[] chars = new char[decoder.GetCharCount(buffer, 0, bytes)];
                decoder.GetChars(buffer, 0, bytes, chars, 0);
                messageData.Append(chars);
                if (messageData.ToString().IndexOf("<EOF>", StringComparison.Ordinal) != -1)
                {
                    break;
                }
            } while (bytes != 0);

            string message = messageData.ToString().Replace("<EOF>", "");
            Console.WriteLine("recevied:" + message);
            ReadMessage(sslStream);
        }

        private static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslpolicyerrors)
        {
            if (sslpolicyerrors == SslPolicyErrors.None)
                return true;
            Console.WriteLine("Certificate error: {0}", sslpolicyerrors);
            return false;
        }
    }
View Code

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-05-18
  • 2021-08-05
  • 2021-06-26
  • 2021-06-11
猜你喜欢
  • 2022-12-23
  • 2022-02-06
  • 2021-11-23
  • 2021-06-16
  • 2021-05-17
相关资源
相似解决方案