使用CryptoStream读取和写入TCP套接字

时间:2016-07-18 14:50:49

标签: c# sockets encryption rijndaelmanaged cryptostream

我尝试加密通过TCP连接发送的数据,但是,我没有通过public class SecureCommunication { public SecureCommunication(TcpClient client, byte[] key, byte[] iv) { _client = client; _netStream = _client.GetStream(); var rijndael = new RijndaelManaged(); _cryptoReader = new CryptoStream(_netStream, rijndael.CreateEncryptor(key, iv), CryptoStreamMode.Read); _cryptoWriter = new CryptoStream(_netStream, rijndael.CreateEncryptor(key, iv), CryptoStreamMode.Write); _reader = new StreamReader(_cryptoReader); _writer = new StreamWriter(_cryptoWriter); } public string Receive() { return _reader.ReadLine(); } public void Send(string buffer) { _writer.WriteLine(buffer); _writer.Flush(); } ... 收到任何数据。

以下是我设置流的类:

byte[] iv = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16 };
byte[] key = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16 };

密钥和初始向量:

var client = new TcpClient("xxx.xxx.xxx.xxx", 12345);
var communication = new SecureTcpCommunication(client, key, iv);
communication.Send("Test message");

在我的测试客户端程序中,我打电话

var serverSocket = new TcpListener(IPAddress.Any, tcpPort);
var client = serverSocket.AcceptTcpClient();
var communication = new SecureTcpCommunication(client, key, iv);
Console.WriteLine($"Received message: {communication.Receive()}");

在我的服务器上,我打电话给:

communication.Receive

然而,应用程序阻止doSomething并且永远不会完成。我在这做错了什么?我觉得它很简单......

1 个答案:

答案 0 :(得分:0)

在发送功能中,最后拨打_cryptoWriter.Flush()_writer.Flush()不会在封装的流上调用flush。