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

本文关键字:TCP 套接字 CryptoStream 读取 使用 | 更新日期: 2023-09-27 17:57:33

我正在尝试加密通过TCP连接发送的数据,但是,我没有通过CryptoStream接收到任何数据。

这是我设置流的类:

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上阻塞,并且永远不会结束。我在这里做错了什么?我觉得这很简单。。

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

在send函数中,最后调用_cryptoWriter.Flush()_writer.Flush()不对封装流调用flush。