假设我们有一条使用 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,但我想避免这种情况。有什么想法吗?
最佳答案
因为我在处理类似的话题atm,所以我会在这里回答:
正如 Maarten Bodewes 所写,我建议您先加密然后再 MAC。
然后您可以在对 aesStream
执行 FlushFinalBlock()
之后写入 HMAC 字节。
不要忘记处理 CryptoStreams 和 Algorithms 对象!
var stream = client.GetStream();
HMACSHA256 mac = new HMACSHA256();
CryptoStream macStream = new CryptoStream(stream, mac, CryptoStreamMode.Write);
AesManaged aes = new AesManaged();
var aesEncryptor = aes.CreateEncryptor();
CryptoStream aesStream = new CryptoStream(macStream, aesEncryptor, CryptoStreamMode.Write);
byte[] message = new byte[1024];
aesStream.Write(message, 0, message.Length);
aesStream.FlushFinalBlock();
//No need to FlushFinalBlock() on macStream, would throw
//Write HMAC here
stream.Write(mac.Hash, 0, mac.Hash.Length);
//Dispose
aesStream.Dispose();
aes.Dispose();
macStream.Dispose();
mac.Dispose();
关于c# - 使用 CryptoStreams 加密和 HMAC 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15125680/