How to get .NET CryptoStream to read last block

492 Views Asked by At

I have a client/server setup with CryptoStream around TcpClient's NetWorkStream on both ends. Communication works great biderectionally when I read from the NetworkStream directly but with CryptoStream I can't read a single block of available data. I am closing the CryptoStream to cause FlushLastBlock to be called from the server and indeed the one and only block of 16 bytes (AES encrypted) shows up at the client end. So why does CryptoStream.Read() block waiting for data when there is a full block of data available?

P.S. I've verified that sending an additional block allows the reader to read the first block. Is this just a bug or by design?

1

There are 1 best solutions below

3
On

Have you called FlushFinalBlock() on the CryptoStream on the sending side?

using (var stream = new MemoryStream())
{
    using (var cs = new CryptoStream(stream, your_encryptor, CryptoStreamMode.Write))
    {
        your_formatter.Serialize(cs, your_graph);
        cs.FlushFinalBlock();
        your_socket.Send(stream.GetBuffer(), 0, (int)stream.Length);
    }
}