0

我正在尝试加密通过 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并且永远不会完成。我在这里做错了什么?我觉得它真的很简单..

4

1 回答 1

0

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

于 2018-03-22T05:39:34.517 回答