关于C# 的hmacSHA1加密方法的使用
简短的来说:我发送http请求要从人家那获取一些信息,在http的header里面增加一些参数,其中就有特定的的参数需要用hmacSHA1来加密。
对方提供了JAVA的SDK,但没有C#的,java的主要加密实现为:
public static String generateMacSignature( String secret,String data) {
logger.debug("generateDate is:"+data);
logger.debug("secret is:"+secret);
byte[] byteHMAC = null;
try {
Mac mac = Mac.getInstance(HMAC_SHA1);
SecretKey secretKey = new SecretKeySpec(secret.getBytes("utf-8"),
HMAC_SHA1);
mac.init(secretKey);
byteHMAC = mac.doFinal(data.getBytes("utf-8"));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String result = new BASE64Encoder().encode(byteHMAC);
logger.debug("generateMacSignature is:"+result);
return result;
}
我从网上找了些相关资料,换成C#的为:
public static string HMACSHA1Encrypt(string EncryptText,string EncryptKey)
{
HMACSHA1 myHMACSHA1 = new HMACSHA1(Encoding.UTF8.GetBytes(EncryptKey));
byte[] RstRes = myHMACSHA1.ComputeHash(Encoding.UTF8.GetBytes(EncryptText));
//CryptoStream CStream = new CryptoStream(Stream.Null, myHMACSHA1, CryptoStreamMode.Write);
//CStream.Write(RstRes, 0, RstRes.Length);
StringBuilder EnText = new StringBuilder();
foreach (byte Byte in RstRes)
{
EnText.AppendFormat("{0:x2}", Byte);
}
return EnText.ToString();
}
但加密出来的结果始终是不对的,自然回来的信息也是:加密错误。
请问哪位大侠知道C#的hmacSHA1加密正确的方式是怎么样的?我已经在google上搜遍了