請幫忙把如下的java簽名算法轉換為c#的,牛人伸手啊!!
具體代碼如下:
public static String genSignature(String sk, String stringToSign) {
String signature = "";
try {
String encodedSign = URLEncoder.encode(stringToSign, ENCODING);
try {
Mac mac = Mac.getInstance(HASH);
mac.init(new SecretKeySpec(sk.getBytes(ENCODING), HASH));
byte[] hashData = mac.doFinal(encodedSign.getBytes(ENCODING));
StringBuilder sb = new StringBuilder(hashData.length * 2);
for (byte data : hashData) {
String hex = Integer.toHexString(data & 0xFF);
if (hex.length() == 1) {
// append leading zero
sb.append("0");
}
sb.append(hex);
}
signature = sb.toString().toLowerCase();
} catch (Exception e) {
logger.warn("sha256 exception for[" + sk + "," + stringToSign + "]. e:", e);
}
} catch (UnsupportedEncodingException e) {
logger.warn("encode error, string[" + stringToSign + "] e:" + e);
}
return signature;
}
已經解決,代碼如下:
public static string genSignature(string sk,string data)
{
UTF8Encoding enc = new UTF8Encoding();
byte[] secretKey = enc.GetBytes(sk);
HMACSHA256 hmac = new HMACSHA256(secretKey);
hmac.Initialize();
byte[] bytes = enc.GetBytes(data);
byte[] hashBytes = hmac.ComputeHash(bytes);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hashBytes.Length; i++)
{
string hex = (hashBytes[i] & 0xFF).ToString("x");
if (hex.Length == 1)
{
sb.Append("0");
}
sb.Append(hex);
}