Click here to Skip to main content
Click here to Skip to main content

Mentalis Based SecureSocketClient

, 28 Feb 2008
Rate this:
Please Sign up or sign in to vote.
Mentalis based SecureSocketClient

Introduction

The idea of this article is to show how to use SecureSocketClient - especially for OnVerify and OnCertificateRequest methods.

The SecureSocketClient class is thread safe.

Background

When SSL or TSL connection is established, the server and client have to have valid certificates installed.

When the client validates a server, the OnVerify method is called and when the server validates a client, the OnCertificateRequest is called.

Don't forget to download and add a reference to the Mentalis DLL.

Using the Code

SecureSocketClient code 
/// <span class="code-SummaryComment"><summary></span>
/// 
/// <span class="code-SummaryComment"></summary></span>
/// <span class="code-SummaryComment"><param name=&quot;secureSocket&quot;>true to use a TLS1 otherwise regular socket</param></span>
public void InitSocket(bool secureSocket)
{
    string serverCN = &quot;ANY COMMON NAME.COM&quot;;
    SecurityOptions options = null;
         if (secureSocket)
            {
                // initialize the security options
                // most of the security parameters can be null for 
                // a non secure connection
                options = new SecurityOptions(
                // protocol to use, here TLS1. 
                // For a regular, non secure TCP connection, use SecureProtocol.None
                SecureProtocol.Tls1,
                null,
                    // this is the client side
                ConnectionEnd.Client,
                    //manual certificate verification
                CredentialVerification.Manual,
                    // callback for certificate verification
                new CertVerifyEventHandler(OnVerify),
                    // this is the common name of the web server
                serverCN,
                    // use the default security flags
                SecurityFlags.Default,
                    // only use the RSA_AES_128 cipher
                SslAlgorithms.RSA_AES_128_SHA | SslAlgorithms.NULL_COMPRESSION,
                    // callback to process certificate request
                new CertRequestEventHandler(OnCertificateRequest));
                m_SecureSocket = new SecureSocket(AddressFamily.InterNetwork, 
                                 SocketType.Stream, ProtocolType.Tcp, options);
            }
            else
            {
                m_SecureSocket = new SecureSocket
                     (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            }

        } 
  /// <span class="code-SummaryComment"><summary></span>
  /// Verifies a certificate received from the remote host.
  /// <span class="code-SummaryComment"></summary></span>
  /// <span class="code-SummaryComment"><param name=&quot;socket&quot;>The SecureSocket that received the certificate.</param></span>
  /// <span class="code-SummaryComment"><param name=&quot;remote&quot;>The received certificate.</param></span>
  /// <span class="code-SummaryComment"><param name=&quot;e&quot;>The event parameters.</param></span>
  private void OnVerify(SecureSocket socket, Certificate remote, CertificateChain chain, VerifyEventArgs e)
  {
      CertificateChain cc = new CertificateChain(remote, new CertificateStore(&quot;ROOT&quot;));
      Certificate[] cchain = cc.GetCertificates();
      CertificateStatus cs = cc.VerifyChain(socket.CommonName, AuthType.Server);
      m_Cert = cs;
      m_CertVerified.Set();
  }
/// <span class="code-SummaryComment"><summary></span>
/// Verifies a certificate received from the remote host.
/// <span class="code-SummaryComment"></summary></span>
/// <span class="code-SummaryComment"><param name=&quot;socket&quot;>The SecureSocket that received the certificate.</param></span>
/// <span class="code-SummaryComment"><param name=&quot;remote&quot;>The received certificate.</param></span>
/// <span class="code-SummaryComment"><param name=&quot;e&quot;>The event parameters.</param></span>
private void OnCertificateRequest(SecureSocket socket, DistinguishedNameList acceptable, RequestEventArgs e)
{
    //Load the PFX certificate
    string file = @&quot;..\..\client.pfx&quot;;// client cert file
    string pass = &quot;password&quot;;

    Certificate cert = Certificate.CreateFromPfxFile(file, pass, true);

    //save certificate information
    e.Certificate = cert;
}
 
public SecureSocketClientTest()
{
    //false for open communication,true for TLS1
    SecureSocketClient.Instance.InitSocket(false);
    SecureSocketClient.Instance.Connect(&quot;15.9.9.99&quot;, 12345);
    SecureSocketClient.Instance.OnDataReceivedEvent += 
            new OnDataReceivedDelegate(OnReceived);
}

//This is a delegate that is registered with the SecureSocketClient 
//and is invoked when reply arrived from a remote end
private void OnReceived(byte[] reply,int size)
 {
      if (textBox1.InvokeRequired)
      {
         textBox1.Invoke(new OnDataReceivedDelegate(OnReceived), new object[2] 
                { reply, size });
      }
      else
      {
         string rep = Encoding.ASCII.GetString(reply,0,size);
         textBox1.Text += rep;
      }
}
private void Send_Click(object sender, EventArgs e)
{
    string cmd = &quot;(CMD GetStatus)&quot;
    SecureSocketClient.Instance.Post(Encoding.ASCII.GetBytes(cmd));
}

History

  • 28th February, 2008: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Igor Sokolsky
Software Developer (Senior)
Canada Canada
No Biography provided

Comments and Discussions

 
GeneralMentalis doesn't support .NET 2.0 x64 PinmemberMichael B. Hansen5-Mar-08 0:50 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.140821.2 | Last Updated 28 Feb 2008
Article Copyright 2008 by Igor Sokolsky
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid