I'm learning how to encrypt network streams with the simple example below. Without encryption this example worked fine, but now I've added CryptoStreams the server hangs on "var data = reader.ReadLine()" after the client has written it's message and flushed.
static byte[] Key;
static byte[] IV;
static void Main(string[] args)
{
var svrTask = RunServer();
RunClient();
svrTask.Wait();
}
static async Task RunServer ()
{
var listener = new TcpListener(4567);
var algo = new RijndaelManaged();
listener.Start();
var client = await listener.AcceptTcpClientAsync();
using (var stream = client.GetStream())
using (var inputStream = new CryptoStream(stream, algo.CreateDecryptor(Key, IV), CryptoStreamMode.Read))
using (var outputStream = new CryptoStream(stream, algo.CreateEncryptor(Key, IV), CryptoStreamMode.Write))
{
var reader = new StreamReader(inputStream);
var writer = new StreamWriter(outputStream);
var data = reader.ReadLine(); // Task hangs here
writer.WriteLine("Server Received: " + data);
writer.Flush();
}
client.Close();
listener.Stop();
}
static void RunClient ()
{
var algo = new RijndaelManaged();
Key = algo.Key;
IV = algo.IV;
var client = new TcpClient("localhost", 4567);
using (var stream = client.GetStream())
using (var inputStream = new CryptoStream(stream, algo.CreateDecryptor(Key, IV), CryptoStreamMode.Read))
using (var outputStream = new CryptoStream(stream, algo.CreateEncryptor(Key, IV), CryptoStreamMode.Write))
{
var writer = new StreamWriter(outputStream);
Console.WriteLine("Client will send: ");
var data = Console.ReadLine();
writer.WriteLine(data);
writer.Flush();
var reader = new StreamReader(inputStream);
var response = reader.ReadLine();
Console.WriteLine("Client received: " + response);
}
}
I'm pretty sure I'm missing something very simple. First thought would be that the encryption is messing up the sending of the new line character, causing the server to hang as it waits for the delimiter, but I can't spot the issue.
Any help would be appreciated.