ComputeHash causes an inexplicable difference

Why do the following two methods of calling ComputeHash produce different lengths of results? It seems that the code should give equivalent results.

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
+4
source share
2 answers

It's simple: look at the static method notes HMAC.Create:

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

HMACSHA256 HMAC, Create. HMAC.Create("HMACSHA256").

, HMAC.Create(String), HMACSHA256.Create(String), .

, SHA-1 160 20 , ...

+2

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

SHA-1 HMAC. , Create (String), .

Create , 'Create function.

Try:

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");
0

Source: https://habr.com/ru/post/1617142/


All Articles