5

I got the following HMAC key (in hexadecimal format):

52320e181a481f5e19507a75b3cae4d74d5cfbc328f7f2b738e9fb06b2e05b55b632c1c3d331dcf3baacae8d3000594f839d770f2080910b52b7b8beb3458c08

I need to sign this string:

1100002842850CHF91827364

The result should be this (in hexadecimal format):

2ad2f79111afd818c1dc0916d824b0a1

I have the following code:

string key = "52320e181a481f5e19507a75b3cae4d74d5cfbc328f7f2b738e9fb06b2e05b55b632c1c3d331dcf3baacae8d3000594f839d770f2080910b52b7b8beb3458c08";
string payload = "1100002842850CHF91827364";

byte[] keyInBytes = Encoding.UTF8.GetBytes(key);
byte[] payloadInBytes = Encoding.UTF8.GetBytes(payload);

var md5 = new HMACMD5(keyInBytes);
byte[] hash = md5.ComputeHash(payloadInBytes);

var result = BitConverter.ToString(hash).Replace("-", string.Empty);

However, I am not getting the result. What am I doing wrong?

thd
  • 1,903
  • 6
  • 30
  • 44

2 Answers2

12

when hashing with key HMAC md5

        var data = Encoding.UTF8.GetBytes(plaintext);
        // key
        var key = Encoding.UTF8.GetBytes(transactionKey);

        // Create HMAC-MD5 Algorithm;
        var hmac = new HMACMD5(key);

        // Compute hash.
        var hashBytes = hmac.ComputeHash(data);

        // Convert to HEX string.
        return System.BitConverter.ToString(hashBytes).Replace("-", "").ToLower();
Adi_Pithwa
  • 391
  • 4
  • 7
4

Instead of doing this:

byte[] keyInBytes = Encoding.UTF8.GetBytes(key);

you need to convert key from a hex string to array of bytes. Here you can find example:

How do you convert Byte Array to Hexadecimal String, and vice versa?

Community
  • 1
  • 1
Victor Ronin
  • 21,988
  • 17
  • 90
  • 178