利用C#實(shí)現(xiàn)SSLSocket加密通訊的方法詳解
前言
SSL Socket通訊是對(duì)socket的擴(kuò)展,增加Socket通訊的數(shù)據(jù)安全性,SSL認(rèn)證分為單向和雙向認(rèn)證。單向認(rèn)證只認(rèn)證服務(wù)器端的合法性而不認(rèn)證客戶端的合法性。雙向認(rèn)證是同時(shí)認(rèn)證服務(wù)端和客戶端。下面我分別說說使用C#實(shí)現(xiàn)單向認(rèn)證和雙向認(rèn)證的過程,并用代碼實(shí)現(xiàn)。
一、 單向認(rèn)證
第1步:準(zhǔn)備一個(gè)數(shù)字證書,可以使用如下腳本生成
先進(jìn)入到vs2005的命令行狀態(tài),即:
開始–>程序–>Microsoft Visual Studio 2005–>Visual Studio Tools–>Visual Studio 2005 命令提示
鍵入: makecert -r -pe -n “CN=TestServer” -ss Root -sky exchange
說明:上面的指令將在創(chuàng)建一個(gè)受信任的根證書,
第2步創(chuàng)建服務(wù)器端程序,代碼如下:
using System; using System.ServiceModel; using System.Net; using System.Net.Sockets; using System.Net.Security; using System.Text; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using System.IdentityModel.Tokens; using System.IdentityModel.Selectors; namespace ConsoleApp { public class Program { static X509Certificate serverCertificate = null; public static void RunServer() { TcpListener listener = new TcpListener(IPAddress.Parse("192.168.1.25"), 901); listener.Start(); while (true) { try { Console.WriteLine("Waiting for a client to connect..."); TcpClient client = listener.AcceptTcpClient(); ProcessClient(client); } catch { } } } static void ProcessClient(TcpClient client) { SslStream sslStream = new SslStream(client.GetStream(), false); try { sslStream.AuthenticateAsServer(serverCertificate, false, SslProtocols.Tls, true); DisplaySecurityLevel(sslStream); DisplaySecurityServices(sslStream); DisplayCertificateInformation(sslStream); DisplayStreamProperties(sslStream); sslStream.ReadTimeout = 5000; sslStream.WriteTimeout = 5000; byte[] message = Encoding.UTF8.GetBytes("Hello from the server."); Console.WriteLine("Sending hello message."); sslStream.Write(message); Console.WriteLine("Waiting for client message..."); while (true) { string messageData = ReadMessage(sslStream); Console.WriteLine("Received: {0}", messageData); if (messageData.ToUpper() == "EXIT") break; } } 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 { sslStream.Close(); client.Close(); } } static string 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("") != -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."); } 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."); } } private static void DisplayUsage() { Console.WriteLine("To start the server specify:"); Console.WriteLine("serverSync certificateFile.cer"); } public static void Main(string[] args) { try { X509Store store = new X509Store(StoreName.Root); store.Open(OpenFlags.ReadWrite); // 檢索證書 X509Certificate2Collection certs = store.Certificates.Find(X509FindType.FindBySubjectName, "TestServer", false); // vaildOnly = true時(shí)搜索無結(jié)果。 if (certs.Count == 0) return; serverCertificate = certs[0]; RunServer(); store.Close(); // 關(guān)閉存儲(chǔ)區(qū)。 } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.ReadLine(); } } }
第3步,創(chuàng)建客戶端代碼
namespace ConsoleAppClient { using System; using System.Collections; using System.Net.Security; using System.Net.Sockets; using System.Security.Authentication; using System.Text; using System.Security.Cryptography.X509Certificates; 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(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null); try { sslStream.AuthenticateAsClient("TestServer"); } 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); messsage = Encoding.UTF8.GetBytes("exit"); sslStream.Write(messsage); sslStream.Flush(); // 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.1.25"; try { RunClient(machineName); } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.ReadLine(); } } } }
運(yùn)行效果如下圖:
導(dǎo)致通訊失敗可能問題如下:
1)證書沒有導(dǎo)入到受信任的根證書列表中;2)證書失效;3)客戶端在使用AuthenticateAsClient注冊(cè)時(shí)沒有正確使用服務(wù)器端證書名稱。
二、 雙向認(rèn)證
第1步:創(chuàng)建所需證書,服務(wù)器端所需證書同單向認(rèn)證中的創(chuàng)建過程
先進(jìn)入到vs2005的命令行狀態(tài),即:
開始–>程序–>Microsoft Visual Studio 2005–>Visual Studio Tools–>Visual Studio 2005 命令提示
鍵入:
makecert -r -pe -n “CN=TestClient” -ss Root -sky exchange
第2步:創(chuàng)建服務(wù)端程序
服務(wù)端的程序同單向認(rèn)證的服務(wù)器端代碼
第3步:創(chuàng)建客戶端程序
namespace ConsoleAppClient { using System; using System.Collections; using System.Net.Security; using System.Net.Sockets; using System.Security.Authentication; using System.Text; using System.Security.Cryptography.X509Certificates; 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(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null); // The server name must match the name on the server certificate. X509Store store = new X509Store(StoreName.Root); store.Open(OpenFlags.ReadWrite); //// 檢索證書 X509Certificate2Collection certs = store.Certificates.Find(X509FindType.FindBySubjectName, "TestClient", false); try { sslStream.AuthenticateAsClient("TestServer", 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); messsage = Encoding.UTF8.GetBytes("exit"); sslStream.Write(messsage); sslStream.Flush(); // 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.1.25"; try { RunClient(machineName); } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.ReadLine(); } } } }
總結(jié)
到此這篇關(guān)于利用C#實(shí)現(xiàn)SSLSocket加密通訊的文章就介紹到這了,更多相關(guān)C#實(shí)現(xiàn)SSLSocket加密通訊內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
基于C#實(shí)現(xiàn)的端口掃描器實(shí)例代碼
這篇文章主要介紹了基于C#實(shí)現(xiàn)的端口掃描器實(shí)例代碼,需要的朋友可以參考下2014-07-07詳解C#如何利用TcpListener和TcpClient實(shí)現(xiàn)Tcp通訊
TcpListener 和 TcpClient 是在 System.Net.Sockets.Socket 類的基礎(chǔ)上做的進(jìn)一步封裝,使用 GetStream 方法返回網(wǎng)絡(luò)流,下面我們就來詳細(xì)一下如何使用TcpListener和TcpClient實(shí)現(xiàn)Tcp通訊吧2023-12-12C#操作DataTable方法實(shí)現(xiàn)過濾、取前N條數(shù)據(jù)及獲取指定列數(shù)據(jù)列表的方法
這篇文章主要介紹了C#操作DataTable方法實(shí)現(xiàn)過濾、取前N條數(shù)據(jù)及獲取指定列數(shù)據(jù)列表的方法,實(shí)例分析了C#操作DataTable的各種常用技巧,非常具有實(shí)用價(jià)值,需要的朋友可以參考下2015-04-04Unity3D實(shí)現(xiàn)列表分頁(yè)效果
這篇文章主要為大家詳細(xì)介紹了Unity3D實(shí)現(xiàn)列表分頁(yè)效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-04-04C# .NET實(shí)現(xiàn)掃描識(shí)別圖片中的文字
本文以C#及VB.NET代碼為例,介紹如何掃描并讀取圖片中的文字。文中的示例代碼介紹詳細(xì),對(duì)我們學(xué)習(xí)C#有一定的幫助,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2021-12-12