c# - 使用 CryptoStreams 加密和 HMAC 数据

标签 c# encryption cryptography digital-signature hmac

假设我们有一条使用 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/

相关文章:

使用 <nul 调用时 C# ReadKey 崩溃控制台应用程序

javascript - 在 JavaScript 中重复 php openssl_encrypt

bash - AES128-CBC "bad magic number"和 "error reading input file"

c# - MVVM-我应该在哪里实现我的保存逻辑?

c# - Razor 语法 : Trouble figuring out nested statements and variable scope

PC 客户端上的 C# Crystal Report 总是询问登录提示 SQL Server

java - 带密码的 Zip 字节数组

java - McEliece (Bouncy CaSTLe) 取回公钥

node.js - 使用椭圆曲线 key 创建服务器和客户端时使用 Node JS TLS 密码短语和密码选项(无共享密码套件错误)

cryptography - PIV 智能卡 - 一般验证 - 签署随机数