1

I'm trying to make a C# integration that produces the same HMAC SHA512 hash that I get using the python integration. Should be straightforward, but I cannot seem to get the expected result. Any idea where I'm going wrong?

Python Version

secretKey = 'F9F9F9F9'
binKey = binascii.a2b_hex(secretKey)

text = 'This string is encrypted!'

hash = hmac.new(binKey, text.encode('utf8'), 'sha512').hexdigest()

Python's hash result is 55f7d11a4ff36e794f616975106e58cff4d009bd8c6c0d5dad5ce129dfc27b28846c13f2593a193d5e87e706ab7f602f99d40539636d493b48aea60d6a8a64cc

C# Version

var secretKey = "F9F9F9F9";
var binKey = Encoding.Default.GetBytes(secretKey);

using (HMACSHA512 hmac = new HMACSHA512(binKey))
{
    var data = UTF8Encoding.UTF8.GetBytes("This string is encrypted!");

    var hashValue = hmac.ComputeHash(data);

    var hexString = BitConverter.ToString(hashValue).Replace("-", String.Empty);
}

C#'s hash result is E198C9675B8B854053D39C87D414B56A5463A8F83C76DB7E22D7EFAE629ABD4FD9AA24D771B4C51FA0328F1A4B77769706E91875506EB7103B26F68E0439D527

So clearly I'm messing up somewhere because I would expect the results to be the same.

Any ideas?

Dillon Drobena
  • 761
  • 1
  • 8
  • 26
  • 2
    In the C# code the hex decoding of the key is missing, s. [here](https://stackoverflow.com/a/311179/9014097). – Topaco May 18 '22 at 20:34
  • @Topaco unless I'm mistaken BitConverter.ToString(hashValue).Replace("-", String.Empty) produces the same results as both Convert.ToHexString and the StringBuilder examples in the answer – Dillon Drobena May 18 '22 at 20:47
  • 1
    I mean Hex *decoding* not *encoding*, i.e. I refer to `var binKey = Encoding.Default.GetBytes(secretKey)`, which is to be replaced by e.g. `var binKey = Convert.FromHexString(secretKey)`. – Topaco May 18 '22 at 20:51
  • 1
    @Topaco Welp....that seemed to do the trick. Thanks. Spend the last 7 hours trying to figure out what I was doing wrong – Dillon Drobena May 18 '22 at 21:00

0 Answers0