1

I need to port some python code into c# and I'm having some trouble with this line:

Python

hmac.new(key, message,digestmod=hashlib.sha256).digest()

C#

HMACSHA256 hm = new HMACSHA256(key);
byte[] result = hm.ComputeHash(enc.GetBytes(message));

Why am I getting a different result in C# when key and message are the same (checked byte-by-byte) ?

1 Answer 1

5

You can get different hashes for the same message if you use different encodings when converting the message into a byte array. It is not clear which encoding you are using, but the point is that they should match.

For example:

hmac.new("mykey", "mymessage",digestmod=hashlib.sha256).digest()

gTM3eMvH4WsjwCGzp4gZNV5a62dEcWw/gjTMPngjJpQ=

In C# you get different results depending on your 'enc' variable.

Encoding enc = Encoding.GetEncoding("ASCII");

gTM3eMvH4WsjwCGzp4gZNV5a62dEcWw/gjTMPngjJpQ=

Encoding enc = Encoding.GetEncoding("Unicode");

2wqHPyE5oiI3ukxOaKo9ao6AN8fcwjgdDInBHTXTwGQ=

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I still can't figure out which encoding the python function uses. I have tried chardet and it detects it as windows-1251 but it's not that one. I have tried UTF 7,8,16,32 and Unicode but it doesn't seem to be one of those.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.