Signing a string with HMAC-MD5 with C#

[亡魂溺海] 提交于 2021-02-18 12:35:09

问题


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?


回答1:


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?




回答2:


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();


来源:https://stackoverflow.com/questions/12415438/signing-a-string-with-hmac-md5-with-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!