Reputation: 836
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) ?
Upvotes: 1
Views: 1409
Reputation: 66
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=
Upvotes: 5