假设我们有一条使用 HMAC 签名的消息,然后该消息和 HMAC 被加密,然后通过 TCP 套接字发送:
// endpoint info excluded
TcpClient client = new TcpClient();
var stream = client.GetStream();
// assume pre-shared keys are used and set at this point
AesManaged aes = new AesManaged();
var aesEncryptor = aes.CreateEncryptor();
CryptoStream aesStream = new CryptoStream(
stream, aesEncryptor, CryptoStreamMode.Write);
// assume pre-shared keys here too
HMACSHA256 mac = new HMACSHA256();
CryptoStream macStream = new CryptoStream(
aesStream, mac, CryptoStreamMode.Write);
// assume a message with actual data is written to the macStream
// which updates the hash of the HMAC and also pipes the message
// to the aesStream which encrypts the data and writes it to the
// TCP socket stream
byte[] message = new byte[1024];
macStream.Write(message, 0, message.Length);
macStream.FlushFinalBlock();
// flushing the final block of the macStream actually flushes the
// final block of the aesStream, so I get an error when trying to
// write the HMAC hash to the aesStream
aesStream.Write(mac.Hash, 0, mac.Hash.Length);
aesStream.FlushFinalBlock();
我抽象了很多代码,所以这不是一个工作示例。我可能可以解决这个问题,我将数据写入两次,一次是 HMAC.TransformBlock,另一次是 aesStream,但我想避免这种情况。有任何想法吗?