简短的来说:我发送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上搜遍了

解决方案 »

  1.   

    生成的串有木有乱码!是不是用到Base64转意了
      

  2.   


    没有乱码,嗯,用到base64了
      

  3.   

    看Java代码的最后是用BASE64转换字节数组的,LZ你是自己转16进制字符串,结果当然会不一样。
    最后return Convert.ToBase64String(RstRes);应该就可以了
      

  4.   


    用到了Base64,出来的结果还是不同,因为在hmacSHA1加密后的值都已经不同了,所以base64出来的也不同。
      

  5.   

    楼主 这个问题我也遇到了 我解决的方法是
    public static string HmacSha1Sign(string text, string key)
            {
                Encoding encode = Encoding.GetEncoding(input_charset);
                byte[] byteData = encode.GetBytes(text);
                byte[] byteKey = encode.GetBytes(key);
                HMACSHA1 hmac = new HMACSHA1(byteKey);
                CryptoStream cs = new CryptoStream(Stream.Null, hmac, CryptoStreamMode.Write);
                cs.Write(byteData, 0, byteData.Length);
                cs.Close();
                return Convert.ToBase64String(hmac.Hash);
            }
    你可以试试