C#を使用してRESTAPIを利用しようとしています。APIクリエーターは、PHP、Ruby、およびJavaでサンプルライブラリを提供しています。を生成する必要がある部分でハングアップしていHMAC
ます。
彼らが提供したサンプルライブラリでそれがどのように行われるかを次に示します。
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;
これが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();