c# - ComputeHash 调用莫名其妙地不同

标签 c# .net cryptography key message

为什么下面两种调用ComputeHash的方法结果长度不同?看起来代码应该产生相同的结果。

byte[] KeyBytes = Convert.FromBase64String("KgMLuq+k1oCUv5bzTlKAJf/mGo0T07jTogbi6apcqLa114CCPH3rlK4c0RktY30xLEQ49MZ+C2bMyFOVQO4PyA==");
byte[] MessageBytes = System.Text.Encoding.UTF8.GetBytes("ae06fcd3-6447-4356-afaa-813aa4f2ba41;70aa7c25-c74f-48be-8ca8-cbf73627c05f1418068667");

// works
byte[] HashBytes1 = new System.Security.Cryptography.HMACSHA256(KeyBytes).ComputeHash(MessageBytes); // correct - 32 bytes

// doesn't work
System.Security.Cryptography.HMAC hmac2 = System.Security.Cryptography.HMACSHA256.Create();
hmac2.Key = KeyBytes;
byte[] HashBytes2 = hmac2.ComputeHash(MessageBytes); // wrong - only 20 bytes

最佳答案

很简单:看static的备注HMAC.Create方法:

By default, this overload uses the SHA-1 implementation of HMAC. If you want to specify a different implementation, use the Create(String) overload, which lets you specify an algorithm name, instead.

现在 HMACSHA256 继承自 HMAC,但它没有定义它自己的静态 Create 方法。所以你仍然需要使用 HMAC.Create("HMACSHA256") .

在这里使用 HMAC.Create(String) 可能比使用 HMACSHA256.Create(String) 类更好,以免混淆。

请注意 SHA-1 输出 160 位或 20 字节,所以这确实解释了奇怪的输出大小......

关于c# - ComputeHash 调用莫名其妙地不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33881095/

相关文章:

c# - 使用方法切换 BorderStyle。 C#

c# - 调用代码隐藏的确认对话框并获取所选选项

c# - 在 C# 中抛出内部 Catch

c# - 如果我在代码中设置一些值,我仍然可以使用 UpdateModel() 吗?

java - 衬垫 RIPEMD 160

ios - ECDSA secp256k1 key 对在 Swift 上签名

c++ - 使用 Crypto++ 将文件的 CRC 计算为数值

c# - 强类型、可本地化的 DisplayNameAttribute

c# - 基于操作系统的不同NuGet软件包

c# - AddWithValue 参数为 NULL 时的异常