Using C # to implement Sslsocket encrypted communication Https

Source: Internet
Author: User

Original link
http://blog.csdn.net/wuyb_2004/article/details/51393290

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 H        Ashtable ();        The following method is invoked by the remotecertificatevalidationdelegate.              public static bool Validateservercertificate (object sender, X509Certificate certificate, X509chain chain, sslpolicyerrors sslpolicyerrors) {if (sslpolicyerrors = = Sslpolicy            Errors.none) return true;            Console.WriteLine ("Certificate error: {0}", sslpolicyerrors);            Do not allow the 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 would 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); Retrieve certificate 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 and 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 (); }    }}

Using C # to implement Sslsocket encrypted communication Https

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.