我希望在HMACSHA512计算中包含 iv
和salt
,然后添加到加密数据。
目前,有人可能会更改iv
而a则不会注意到这一点。
我链接不同的流以确保加密 - 然后MAC,稍后我想加密大文件,所以这个设计是必要的。
因此,如果我将iv
和salt
添加到流中,例如new MemoryStream(iv).CopyTo(hmacStream);
结果将包含此数据。
到目前为止,这是我的代码:
private static IHmacAndData EncryptInternal(byte[] key, byte[] iv, byte[] plainData, byte[] salt)
{
byte[] hmacHash;
byte[] encryptedBytes;
using (var aesManaged = CreateAesManaged(iv, key))
{
var encryptor = aesManaged.CreateEncryptor(aesManaged.Key, aesManaged.IV);
var hmacsha512 = new HMACSHA512(key);
using (var resultStream = new MemoryStream())
{
using (var hmacStream = new CryptoStream(resultStream, hmacsha512, CryptoStreamMode.Write))
{
using (var aesStream = new CryptoStream(hmacStream, encryptor, CryptoStreamMode.Write))
{
using (var plainStream = new MemoryStream(plainData))
{
plainStream.CopyTo(aesStream);
}
}
}
encryptedBytes = resultStream.ToArray();
}
hmacHash = hmacsha512.Hash;
}
return new Message {HMAC = hmacHash, Data = encryptedBytes};
}
private static AesManaged CreateAesManaged(byte[] iv, byte[] key)
{
var aesManaged = new AesManaged
{
Mode = CipherMode.CBC,
Padding = PaddingMode.PKCS7,
KeySize = KeySize,
IV = iv,
Key = key
};
return aesManaged;
}
我的临时解决方案是在最后进行第二次HMACSHA512计算。 但这似乎不对。
var overallHmac = new HMACSHA512(keyHmac);
hmacHash = overallHmac.ComputeHash(hmacHash.Concat(iv).Concat(saltPassword).Concat(saltHmac).ToArray());
以下是完整示例,搜索CreateOverallHmacKey
以找到该位置。
https://gist.github.com/dhcgn/85b88b516953e8996af8544ee9d7b567