C# Socket SSL通讯笔记

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C# Socket SSL通讯笔记相关的知识,希望对你有一定的参考价值。

一、x.509证书

 

1.制作证书

先进入到vs2005的命令行状态,即:
开始-->程序-->Microsoft Visual Studio 2005-->Visual Studio Tools-->Visual Studio 2005 命令提示

键入:

makecert -r -pe -n "CN=MyServer" -ss My -sky exchange

解释一下:makecert.exe是一个专门用来制作证书的小工具,上面一行的意思就是制作一个CN=MyServer的服务器证书,默认存储在CurrentUser"My这个位置,同时这个证书标识为可导出。(详细的

MakeCert参数可参见http://msdn.microsoft.com/zh-cn/bfsktky3(vs.80).aspx)

再输入:

makecert -r -pe -n "CN=MyClient" -ss My -sky exchange

生成客户端证书,证书生成好以后,可以在IE里查看到,IE-->工具-->Internet选项-->内容-->证书

记得要把证书导入到受信任的那栏,不然是访问不到的, 然后在IE-->工具-->Internet选项-->内容-->证书里导出一个CER,面通知过程中选不要是私钥, 这样给客户端使用

socket服务器的建立代码如下,注意所引用的命名空间:

 

技术分享代码

 

 

Sokect客户端代码如下:

 

技术分享代码
using System;
using System.Security;
using System.Net;
using System.Net.Sockets;
using System.Net.Security;
using System.Text;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;

namespace ConsoleAppClient
{
    using System;
    using System.Collections;
    using System.Net;
    using System.Net.Security;
    using System.Net.Sockets;
    using System.Security.Authentication;
    using System.Text;
    using System.Security.Cryptography.X509Certificates;
    using System.IO;

    namespace Examples.System.Net
    {
        public class SslTcpClient
        {
            private static Hashtable certificateErrors = new Hashtable();
            // The following method is invoked by the RemoteCertificateValidationDelegate.
            public static bool ValidateServerCertificate(
                  object sender,
                  X509Certificate certificate,
                  X509Chain chain,
                  SslPolicyErrors sslPolicyErrors)
            {
                if (sslPolicyErrors == SslPolicyErrors.None)
                    return true;

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

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

            public static void RunClient(string machineName)
            {
                // Create a TCP/IP client socket.
                // machineName is the host running the server application.
                TcpClient client = new TcpClient(machineName, 901);
                Console.WriteLine("Client connected.");
                // Create an SSL stream that will close the client‘s stream.
                SslStream sslStream = new SslStream(client.GetStream(), falsenew RemoteCertificateValidationCallback(ValidateServerCertificate), null);
                // The server name must match the name on the server certificate.

                //X509Store store = new X509Store(StoreName.My);
                //store.Open(OpenFlags.ReadWrite);

                //// 检索证书 
                //X509Certificate2Collection certs = store.Certificates.Find(X509FindType.FindBySubjectName, "MyServer", false); // vaildOnly = true时搜索无结果。

                X509CertificateCollection certs = new X509CertificateCollection();
                X509Certificate cert = X509Certificate.CreateFromCertFile(@"D:\\cashcer.cer");
                certs.Add(cert);
                try
                {
                    sslStream.AuthenticateAsClient("MyServer", 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();
                    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.WriteLine("Server says: {0}", serverMessage);
                // Close the client connection.
                client.Close();
                Console.WriteLine("Client closed.");
            }

            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
                {
                    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.
                    if (messageData.ToString().IndexOf("<EOF>"!= -1)
                    {
                        break;
                    }
                } while (bytes != 0);

                return messageData.ToString();
            }

            private static void DisplayUsage()
            {
                Console.WriteLine("To start the client specify:");
                Console.WriteLine("clientSync machineName [serverName]");
                Environment.Exit(1);
            }

            public static void Main(string[] args)
            {
                string machineName = null
                machineName = "192.168.20.139";

                

以上是关于C# Socket SSL通讯笔记的主要内容,如果未能解决你的问题,请参考以下文章

使用C#实现SSLSocket加密通讯

unity C#实现简单socket通讯框架

C# Socket使用ssl连接报错,是证书问题?还是方法问题?

C# socket通讯使用域名的方法

C# HttpWebRequest 如何实现SOCKET5代理

用openssl生成的ssl证书和付费的有啥区别