基于SOCKERT证书的信息传输
基于SOCKERT证书的信息传输
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 using System;
2 using System.Net;
3 using System.Net.Sockets;
4 using System.Net.Security;
5 using System.Text;
6 using System.Security.Authentication;
7 using System.Security.Cryptography.X509Certificates;
8
9 namespace Examples.System.Net
10 {
11 public sealed class SslTcpServer
12 {
13 static X509Certificate serverCertificate = null;
14
15 public static int Main(string[] args)
16 {
17 string certificate = "localhost.pfx";//mxd.cer
18 string password = "";
19 SslTcpServer.RunServer(certificate, password);
20 return 0;
21 }
22
23 public static void RunServer(string certificate,string password)
24 {
25 serverCertificate = new X509Certificate2(certificate, password);
26 TcpListener listener = new TcpListener(IPAddress.Any, 8080);
27 listener.Start();
28 while (true)
29 {
30 Console.WriteLine("Waiting for a client to connect...");
31 TcpClient client = listener.AcceptTcpClient();
32 ProcessClient(client);
33 }
34 }
35 static void ProcessClient(TcpClient client)
36 {
37 SslStream sslStream = new SslStream(client.GetStream(), false);
38 try
39 {
40 sslStream.AuthenticateAsServer(serverCertificate, false, SslProtocols.Tls, false);
41 DisplaySecurityLevel(sslStream);
42 DisplaySecurityServices(sslStream);
43 DisplayCertificateInformation(sslStream);
44 DisplayStreamProperties(sslStream);
45
46 sslStream.ReadTimeout = 5000;
47 sslStream.WriteTimeout = 5000;
48 Console.WriteLine("Waiting for client message...");
49 string messageData = ReadMessage(sslStream);
50 Console.WriteLine("Received: {0}", messageData);
51 byte[] message = Encoding.UTF8.GetBytes("Hello from the server. ^-^ mxd...");
52 Console.WriteLine("Sending hello message.");
53 sslStream.Write(message);
54 }
55 catch (AuthenticationException e)
56 {
57 Console.WriteLine("Exception: {0}", e.Message);
58 if (e.InnerException != null)
59 {
60 Console.WriteLine("Inner exception: {0}", e.InnerException.Message);
61 }
62 Console.WriteLine("Authentication failed - closing the connection.");
63 sslStream.Close();
64 client.Close();
65 return;
66 }
67 finally
68 {
69 sslStream.Close();
70 client.Close();
71 }
72 }
73 static string ReadMessage(SslStream sslStream)
74 {
75 byte[] buffer = new byte[2048];
76 StringBuilder messageData = new StringBuilder();
77 int bytes = -1;
78 do
79 {
80 bytes = sslStream.Read(buffer, 0, buffer.Length);
81 Decoder decoder = Encoding.UTF8.GetDecoder();
82 char[] chars = new char[decoder.GetCharCount(buffer, 0, bytes)];
83 decoder.GetChars(buffer, 0, bytes, chars, 0);
84 messageData.Append(chars);
85 if (messageData.ToString().IndexOf("") != -1)
86 {
87 break;
88 }
89 }
90 while (bytes != 0);
91
92 return messageData.ToString();
93 }
94 static void DisplaySecurityLevel(SslStream stream)
95 {
96 Console.WriteLine("Cipher: {0} strength {1}", stream.CipherAlgorithm, stream.CipherStrength);
97 Console.WriteLine("Hash: {0} strength {1}", stream.HashAlgorithm, stream.HashStrength);
98 Console.WriteLine("Key exchange: {0} strength {1}", stream.KeyExchangeAlgorithm, stream.KeyExchangeStrength);
99 Console.WriteLine("Protocol: {0}", stream.SslProtocol);
100 }
101 static void DisplaySecurityServices(SslStream stream)
102 {
103 Console.WriteLine("Is authenticated: {0} as server? {1}", stream.IsAuthenticated, stream.IsServer);
104 Console.WriteLine("IsSigned: {0}", stream.IsSigned);
105 Console.WriteLine("Is Encrypted: {0}", stream.IsEncrypted);
106 }
107 static void DisplayStreamProperties(SslStream stream)
108 {
109 Console.WriteLine("Can read: {0}, write {1}", stream.CanRead, stream.CanWrite);
110 Console.WriteLine("Can timeout: {0}", stream.CanTimeout);
111 }
112 static void DisplayCertificateInformation(SslStream stream)
113 {
114 Console.WriteLine("Certificate revocation list checked: {0}", stream.CheckCertRevocationStatus);
115
116 X509Certificate localCertificate = stream.LocalCertificate;
117 if (stream.LocalCertificate != null)
118 {
119 Console.WriteLine("Local cert was issued to {0} and is valid from {1} until {2}.",
120 localCertificate.Subject,
121 localCertificate.GetEffectiveDateString(),
122 localCertificate.GetExpirationDateString());
123 }
124 else
125 {
126 Console.WriteLine("Local certificate is null.");
127 }
128 X509Certificate remoteCertificate = stream.RemoteCertificate;
129 if (stream.RemoteCertificate != null)
130 {
131 Console.WriteLine("Remote cert was issued to {0} and is valid from {1} until {2}.",
132 remoteCertificate.Subject,
133 remoteCertificate.GetEffectiveDateString(),
134 remoteCertificate.GetExpirationDateString());
135 }
136 else
137 {
138 Console.WriteLine("Remote certificate is null.");
139 }
140 }
141 private static void DisplayUsage()
142 {
143 Console.WriteLine("To start the server specify:");
144 Console.WriteLine("serverSync certificateFile.cer");
145 Console.ReadLine();
146 Environment.Exit(1);
147 }
148 }
149 }
2 using System.Net;
3 using System.Net.Sockets;
4 using System.Net.Security;
5 using System.Text;
6 using System.Security.Authentication;
7 using System.Security.Cryptography.X509Certificates;
8
9 namespace Examples.System.Net
10 {
11 public sealed class SslTcpServer
12 {
13 static X509Certificate serverCertificate = null;
14
15 public static int Main(string[] args)
16 {
17 string certificate = "localhost.pfx";//mxd.cer
18 string password = "";
19 SslTcpServer.RunServer(certificate, password);
20 return 0;
21 }
22
23 public static void RunServer(string certificate,string password)
24 {
25 serverCertificate = new X509Certificate2(certificate, password);
26 TcpListener listener = new TcpListener(IPAddress.Any, 8080);
27 listener.Start();
28 while (true)
29 {
30 Console.WriteLine("Waiting for a client to connect...");
31 TcpClient client = listener.AcceptTcpClient();
32 ProcessClient(client);
33 }
34 }
35 static void ProcessClient(TcpClient client)
36 {
37 SslStream sslStream = new SslStream(client.GetStream(), false);
38 try
39 {
40 sslStream.AuthenticateAsServer(serverCertificate, false, SslProtocols.Tls, false);
41 DisplaySecurityLevel(sslStream);
42 DisplaySecurityServices(sslStream);
43 DisplayCertificateInformation(sslStream);
44 DisplayStreamProperties(sslStream);
45
46 sslStream.ReadTimeout = 5000;
47 sslStream.WriteTimeout = 5000;
48 Console.WriteLine("Waiting for client message...");
49 string messageData = ReadMessage(sslStream);
50 Console.WriteLine("Received: {0}", messageData);
51 byte[] message = Encoding.UTF8.GetBytes("Hello from the server. ^-^ mxd...");
52 Console.WriteLine("Sending hello message.");
53 sslStream.Write(message);
54 }
55 catch (AuthenticationException e)
56 {
57 Console.WriteLine("Exception: {0}", e.Message);
58 if (e.InnerException != null)
59 {
60 Console.WriteLine("Inner exception: {0}", e.InnerException.Message);
61 }
62 Console.WriteLine("Authentication failed - closing the connection.");
63 sslStream.Close();
64 client.Close();
65 return;
66 }
67 finally
68 {
69 sslStream.Close();
70 client.Close();
71 }
72 }
73 static string ReadMessage(SslStream sslStream)
74 {
75 byte[] buffer = new byte[2048];
76 StringBuilder messageData = new StringBuilder();
77 int bytes = -1;
78 do
79 {
80 bytes = sslStream.Read(buffer, 0, buffer.Length);
81 Decoder decoder = Encoding.UTF8.GetDecoder();
82 char[] chars = new char[decoder.GetCharCount(buffer, 0, bytes)];
83 decoder.GetChars(buffer, 0, bytes, chars, 0);
84 messageData.Append(chars);
85 if (messageData.ToString().IndexOf("") != -1)
86 {
87 break;
88 }
89 }
90 while (bytes != 0);
91
92 return messageData.ToString();
93 }
94 static void DisplaySecurityLevel(SslStream stream)
95 {
96 Console.WriteLine("Cipher: {0} strength {1}", stream.CipherAlgorithm, stream.CipherStrength);
97 Console.WriteLine("Hash: {0} strength {1}", stream.HashAlgorithm, stream.HashStrength);
98 Console.WriteLine("Key exchange: {0} strength {1}", stream.KeyExchangeAlgorithm, stream.KeyExchangeStrength);
99 Console.WriteLine("Protocol: {0}", stream.SslProtocol);
100 }
101 static void DisplaySecurityServices(SslStream stream)
102 {
103 Console.WriteLine("Is authenticated: {0} as server? {1}", stream.IsAuthenticated, stream.IsServer);
104 Console.WriteLine("IsSigned: {0}", stream.IsSigned);
105 Console.WriteLine("Is Encrypted: {0}", stream.IsEncrypted);
106 }
107 static void DisplayStreamProperties(SslStream stream)
108 {
109 Console.WriteLine("Can read: {0}, write {1}", stream.CanRead, stream.CanWrite);
110 Console.WriteLine("Can timeout: {0}", stream.CanTimeout);
111 }
112 static void DisplayCertificateInformation(SslStream stream)
113 {
114 Console.WriteLine("Certificate revocation list checked: {0}", stream.CheckCertRevocationStatus);
115
116 X509Certificate localCertificate = stream.LocalCertificate;
117 if (stream.LocalCertificate != null)
118 {
119 Console.WriteLine("Local cert was issued to {0} and is valid from {1} until {2}.",
120 localCertificate.Subject,
121 localCertificate.GetEffectiveDateString(),
122 localCertificate.GetExpirationDateString());
123 }
124 else
125 {
126 Console.WriteLine("Local certificate is null.");
127 }
128 X509Certificate remoteCertificate = stream.RemoteCertificate;
129 if (stream.RemoteCertificate != null)
130 {
131 Console.WriteLine("Remote cert was issued to {0} and is valid from {1} until {2}.",
132 remoteCertificate.Subject,
133 remoteCertificate.GetEffectiveDateString(),
134 remoteCertificate.GetExpirationDateString());
135 }
136 else
137 {
138 Console.WriteLine("Remote certificate is null.");
139 }
140 }
141 private static void DisplayUsage()
142 {
143 Console.WriteLine("To start the server specify:");
144 Console.WriteLine("serverSync certificateFile.cer");
145 Console.ReadLine();
146 Environment.Exit(1);
147 }
148 }
149 }