我想利用使用C#的REST API。 API創建者已經提供了PHP,Ruby和Java中的示例庫。我正在掛上它的一部分,我需要生成一個HMAC
。如何在C#中生成HMAC-SHA1?
下面是他們提供的示例庫中的工作方式。
PHP
hash_hmac('sha1', $signatureString, $secretKey, false);
紅寶石
digest = OpenSSL::Digest::Digest.new('sha1')
return OpenSSL::HMAC.hexdigest(digest, secretKey, signatureString)
的Java
SecretKeySpec signingKey = new SecretKeySpec(secretKey.getBytes(), HMAC_SHA1_ALGORITHM);
Mac mac = null;
mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
mac.init(signingKey);
byte[] bytes = mac.doFinal(signatureString.getBytes());
String form = "";
for (int i = 0; i < bytes.length; i++)
{
String str = Integer.toHexString(((int)bytes[i]) & 0xff);
if (str.length() == 1)
{
str = "0" + str;
}
form = form + str;
}
return form;
這裏是我的ATT在C#中搶佔。
它不工作。
更新:下面的C#示例工作得很好。我發現真正的問題是由於我的signatureString
中的換行字符存在一些跨平臺差異。
var enc = Encoding.ASCII;
HMACSHA1 hmac = new HMACSHA1(enc.GetBytes(secretKey));
hmac.Initialize();
byte[] buffer = enc.GetBytes(signatureString);
return BitConverter.ToString(hmac.ComputeHash(buffer)).Replace("-", "").ToLower();
原來我的C#代碼工作得很好。真正的問題是由於我的'signatureString'中的換行字符存在一些跨平臺差異。我會將此問題標記爲刪除。 – jessegavin 2011-05-20 17:07:25
不要刪除問題,而是將您的代碼作爲答案發布並接受它。這個問題在尋求做同樣的事情時非常有用。 – 2015-12-04 11:08:26
我在文本「The API responds ...」上添加了更多更新以避免潛在的誤解 – 2016-10-27 09:39:00