Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Signing a string with HMAC-MD5 with C#

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?

like image 764
thd Avatar asked Sep 13 '12 22:09

thd


People also ask

Can MD5 be used for HMAC?

Remarks. HMACMD5 is a type of keyed hash algorithm that is constructed from the Message Digest Algorithm 5 (MD5) hash function and used as a Hash-based Message Authentication Code (HMAC).

Is MD5 better than Hmac?

HMAC is not susceptible to length extension attacks. md5(T + K) should be fine for most uses unless your adversary is motivated to tamper with your message and has very good computing power. As long as you control T, birthday attacks are not applicable and you only have brute-force attacks.


1 Answers

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();
like image 166
Adi_Pithwa Avatar answered Dec 03 '22 18:12

Adi_Pithwa