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
public void InitSocket(bool secureSocket)
{
string serverCN = "ANY COMMON NAME.COM";
SecurityOptions options = null;
if (secureSocket)
{
options = new SecurityOptions(
SecureProtocol.Tls1,
null,
ConnectionEnd.Client,
CredentialVerification.Manual,
new CertVerifyEventHandler(OnVerify),
serverCN,
SecurityFlags.Default,
SslAlgorithms.RSA_AES_128_SHA | SslAlgorithms.NULL_COMPRESSION,
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);
}
}
private void OnVerify(SecureSocket socket, Certificate remote, CertificateChain chain, VerifyEventArgs e)
{
CertificateChain cc = new CertificateChain(remote, new CertificateStore("ROOT"));
Certificate[] cchain = cc.GetCertificates();
CertificateStatus cs = cc.VerifyChain(socket.CommonName, AuthType.Server);
m_Cert = cs;
m_CertVerified.Set();
}
private void OnCertificateRequest(SecureSocket socket, DistinguishedNameList acceptable, RequestEventArgs e)
{
string file = @"..\..\client.pfx";
string pass = "password";
Certificate cert = Certificate.CreateFromPfxFile(file, pass, true);
e.Certificate = cert;
}
public SecureSocketClientTest()
{
SecureSocketClient.Instance.InitSocket(false);
SecureSocketClient.Instance.Connect("15.9.9.99", 12345);
SecureSocketClient.Instance.OnDataReceivedEvent +=
new OnDataReceivedDelegate(OnReceived);
}
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 = "(CMD GetStatus)"
SecureSocketClient.Instance.Post(Encoding.ASCII.GetBytes(cmd));
}
History
- 28th February, 2008: Initial post
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.