gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 12:24:32 37 4
gpt4 key购买 nike

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

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com