65.9K
CodeProject is changing. Read more.
Home

Mentalis Based SecureSocketClient

starIconstarIconstarIconstarIconemptyStarIcon

4.00/5 (1 vote)

Feb 28, 2008

CPOL
viewsIcon

21590

downloadIcon

108

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 
/// <summary>
/// 
/// </summary>
/// <param name=&quot;secureSocket&quot;>true to use a TLS1 otherwise regular socket</param>
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);
            }

        } 
  /// <summary>
  /// Verifies a certificate received from the remote host.
  /// </summary>
  /// <param name=&quot;socket&quot;>The SecureSocket that received the certificate.</param>
  /// <param name=&quot;remote&quot;>The received certificate.</param>
  /// <param name=&quot;e&quot;>The event parameters.</param>
  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();
  }
/// <summary>
/// Verifies a certificate received from the remote host.
/// </summary>
/// <param name=&quot;socket&quot;>The SecureSocket that received the certificate.</param>
/// <param name=&quot;remote&quot;>The received certificate.</param>
/// <param name=&quot;e&quot;>The event parameters.</param>
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