我得到了以下HMAC密钥(十六进制格式):
52320e181a481f5e19507a75b3cae4d74d5cfbc328f7f2b738e9fb06b2e05b55b632c1c3d331dcf3baacae8d3000594f839d770f2080910b52b7b8beb3458c08
我需要在此字符串上签名:
1100002842850CHF91827364
结果应该是这个(十六进制格式):
2ad2f79111afd818c1dc0916d824b0a1
我有以下代码:
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);
但是,我没有得到结果。我做错了什么?
答案 0 :(得分:9)
使用密钥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();
答案 1 :(得分:4)
而不是这样做:
byte[] keyInBytes = Encoding.UTF8.GetBytes(key);
您需要将密钥从十六进制字符串转换为字节数组。在这里你可以找到例子:
How do you convert Byte Array to Hexadecimal String, and vice versa?