Daily using/supporting

Get Firefox browser!
Get Thunderbird!
Get Opera browser!
Get The Gimp!
Get Inkscape!
Get LibreOffice!
Get Videolan!
Get Linux!
Get Mandriva!
Get Joomla!
Hacker Emblem

Archives

Which topics would you like us to cover more?

Latest comments

Latest tweets

about 1 day ago Using REDIPS.drag to add drag and drop to your .Net webapplication #li #dib0 http://t.co/n8zY3s7d
about 7 days ago http://t.co/cknQcDbo #Kindle
about 15 days ago Freedom isn't the ability to choose what to do or say, but the ability to choose what not to do or say #freedom
about 29 days ago http://t.co/61KTQknI #Kindle
12 Apr 2012 Force the use of a networking adapter using C# #li #dib0 http://t.co/ZTJOPzOz
9 Apr 2012 Mandriva 2010.2 and USB devices in Virtualbox http://t.co/fwq9gbHB
9 Apr 2012 Execute a http request to you own site with PHP http://t.co/DIvWPrpd
Home Architecture, security and coding Using a client certificate with an SSL stream in C#
Using a client certificate with an SSL stream in C#
Written by Division by Zero   
Tuesday, 09 August 2011 09:34

On 21 June I wrote an article on how to build up an SSL connection using C#. I realised this example wasn't complete. Of course this was an example on how to create an SSL connection, but what if you needed authentication using a client certificate?

Actually, using a client certificate isn't that different. Here's the original example changed to use a client certificate. Download the complete solution here.

Server side code:

static void Main(string[] args)
{
    // Start TCP server
    TcpListener listener = new TcpListener(IPAddress.Any, 1300);
    listener.Start();
    Console.WriteLine("Server started listening on port 1300.");
    // Wait for a client to connect on TCP port 1300
    TcpClient clientSocket = listener.AcceptTcpClient();
    if (clientSocket != null)
    {
        // We have a client application
        // Let's read some data. Note: since we don't start a new
        // thread to do this and call listener.AcceptTcpClient() again
        // no other client is able to connect. To do this, we have to create
        // multiple threads and call AcceptTcpClient over and over again for every
        // client.
        HandleClient(clientSocket);
    }
    // Stop listening
    listener.Stop();
    Console.WriteLine("\nServer stopped.");
}
static void HandleClient(TcpClient client)
{
    // Create an object from the (server) certificate file
    // To create this, you will need the appropriate password
    // Note: To make this demo work, you'll need to import this certificate
    // by right clicking the file and choose 'Install PFX', use the password as shown
    // below.
    X509Certificate certificate = new X509Certificate("..\\path\\tp\\Certificate.pfx", "ThisPasswordIsTheSameForInstallingTheCertificate");
    // Create a stream to decrypt the data
    using (SslStream sslStream = new SslStream(client.GetStream(), false,
        new RemoteCertificateValidationCallback(ValidateClientCertificate), null))
    {
        // Set a client certificate as mandatory
        sslStream.AuthenticateAsServer(certificate, true, System.Security.Authentication.SslProtocols.Ssl3, true);
        // Somehow the client.Connected is always true, therefore we
        // check for the '#' character, that will disconnect the client
        int b = 0;
        while ((char) b != '#')
        {
            b = sslStream.ReadByte();
            if (b > -1)
                Console.Write((char)b);
        }
    }
}
// The following method is invoked by the RemoteCertificateValidationDelegate.
// This allows you to check the certificate and accept or reject it
// return true will accept the certificate
public static bool ValidateClientCertificate(object sender, X509Certificate certificate,
    X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
    // Accept all certificates
    return true;
}

And the client side code:

static void Main(string[] args)
{
    // Connect as client to port 1300
    string server = "127.0.0.1";
    TcpClient client = new TcpClient(server, 1300);
   
    // Create a secure stream
    X509CertificateCollection cCollection = new X509CertificateCollection();
    cCollection.Add(new X509Certificate("..\\path\\tp\\Certificate.pfx", "ThisPasswordIsTheSameForInstallingTheCertificate"));
    using (SslStream sslStream = new SslStream(client.GetStream(), false,
        new RemoteCertificateValidationCallback(ValidateServerCertificate), null))
    {
        // Add a client certificate to the ssl connection
        sslStream.AuthenticateAsClient(server, cCollection, System.Security.Authentication.SslProtocols.Default, true);
        Console.WriteLine("Begin to type. All data will be send to the server. Type a '#' to stop.");
        char character = ' ';
        while (character != '#')
        {
            ConsoleKeyInfo info = Console.ReadKey();
            character = info.KeyChar;
            // Send the character over the encrypted stream
            sslStream.WriteByte((byte) character);
        }
    }
    // Disconnect and close the client
    client.Close();
}
// The following method is invoked by the RemoteCertificateValidationDelegate.
// This allows you to check the certificate and accept or reject it
// return true will accept the certificate
public static bool ValidateServerCertificate(object sender, X509Certificate certificate,
    X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
    // Accept all certificates
    return true;
}
 

Add comment


Security code
Refresh

If the human brain was simple enough for us to understand we'd be so simple we couldn't understand. - Unknown


© 2009 - 2012, Division by Zero

Template based on the empire template by joomlashack 

Valid XHTML 1.0 Strict  Valid CSS!  Creative Commons License
This work by Division by Zero is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Netherlands License.