【问题标题】:ComputeHash Calls Inexplicably DifferComputeHash 调用莫名其妙的不同
【发布时间】:2015-11-23 21:32:09
【问题描述】:

为什么以下两种调用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

【问题讨论】:

    标签: c# .net cryptography key message


    【解决方案1】:

    很简单:看一下staticHMAC.Create方法的备注:

    默认情况下,此重载使用 HMAC 的 SHA-1 实现。如果您想指定不同的实现,请使用 Create(String) 重载,它允许您指定算法名称。

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

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

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

    【讨论】:

    • 在 Java 中,在定义它的类之外的任何东西上使用 static 方法都会抛出编译器警告。有谁知道这是否也可用于 C#(和 Visual Studio)?或者这是否需要某种静态代码分析工具?
    • 啊,找到了! ReSharper seems to do this。不过不是免费的。
    【解决方案2】:

    来自 MSDN:System.Security.Cryptography.HMACSHA256.Create()

    默认情况下,此重载使用 HMAC 的 SHA-1 实现。如果要指定不同的实现,请使用 Create(String) 重载,它允许您指定算法名称。

    当前调用 Create 时,实际上是在调用基类的 Create 函数。

    试试:

    System.Security.Cryptography.HMAC hmac2 = System.Security.Cryptography.HMACSHA256.Create("System.Security.Cryptography.HMACSHA256");
    

    是的,我意识到这在代码形式中看起来多么愚蠢......只是试图回答这个问题。

    作为替代方案:

    System.Security.Cryptography.HMAC hmac2 = System.Security.Cryptography.HMAC.Create("System.Security.Cryptography.HMACSHA256");
    

    【讨论】:

      猜你喜欢
      • 2012-05-19
      • 1970-01-01
      • 2012-03-12
      • 2019-02-04
      • 2013-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多