Encrypt-then-MAC,如何将数据添加到HMAC

时间:2016-09-22 10:51:07

标签: c# .net hmac

我希望在HMACSHA512计算中包含 ivsalt ,然后添加到加密数据。
 目前,有人可能会更改iv而a则不会注意到这一点。

我链接不同的流以确保加密 - 然后MAC,稍后我想加密大文件,所以这个设计是必要的。
因此,如果我将ivsalt添加到流中,例如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

0 个答案:

没有答案