December 2007
Intermediate to advanced
896 pages
19h 57m
English
You want to use the TCP server in Recipe 17.1 to communicate with the TCP client in Recipe 17.2. However, you need to encrypt the communication and verify that it has not been tampered with in transit.
Replace the NetworkStream class with the more secure SslStream class on both the client and the server. The code for the more secure TCP client, TCPClient_SSL, is shown in Example 17-15 (changes are in boldface).
Example 17-15. TCPClient_SSL class
class TCPClient_SSL
{
private TcpClient _client = null;
private IPAddress _address = IPAddress.Parse("127.0.0.1");
private int _port = 5;
private IPEndPoint _endPoint = null;
public TCPClient_SSL(string address, string port)
{
_address = IPAddress.Parse(address);
_port = Convert.ToInt32(port);
_endPoint = new IPEndPoint(_address, _port);
}
public void ConnectToServer(string msg)
{
try
{
using (client = new TcpClient())
{
client.Connect(_endPoint);
using(SslStreamsslStream =newSslStream(_client.GetStream(),
false, new RemoteCertificateValidationCallback(
CertificateValidationCallback)))
{
sslStream.AuthenticateAsClient("MyTestCert2");
// Get the bytes to send for the message.
byte[] bytes = Encoding.ASCII.GetBytes(msg);
// Send message.
Console.WriteLine("Sending message to server: " + msg);
sslStream.Write(bytes, 0, bytes.Length);
// Get the response.
// Buffer to store the response bytes.
bytes = new byte[1024];
// Display the response.
int bytesRead = sslStream.Read(bytes, 0, bytes.Length); string ...Read now
Unlock full access