Android:如何创建HMAC MD5字符串?

时间:2011-12-06 06:51:00

标签: java android hash md5 hmac

我正在尝试创建一个Android MD5哈希字符串,以等于下面的C#代码:

private string CalculateHMACMd5(string message, string key)
{
     System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
     byte[] keyByte = encoding.GetBytes(key);
     HMACMD5 hmacmd5 = new HMACMD5(keyByte);
     byte[] messageBytes = encoding.GetBytes(message);
     byte[] hashmessage = hmacmd5.ComputeHash(messageBytes);
     string HMACMd5Value = ByteToString(hashmessage);
     return HMACMd5Value;
}

private static string ByteToString(byte[] buff)
{
    string sbinary = "";
    for (int i = 0; i < buff.Length; i++)
    {
        sbinary += buff[i].ToString("X2"); 
    }
    return (sbinary);
}

<小时/> 我目前使用的Android代码[ 没有生成相同的C#代码 ]:

        public static String sStringToHMACMD5(String sData, String sKey) 
        {
            SecretKeySpec key;
            byte[] bytes;
            String sEncodedString = null;
            try 
            {       
                key = new SecretKeySpec((sKey).getBytes(), "ASCII");
                Mac mac = Mac.getInstance("HMACMD5");
                mac.init(key);
                mac.update(sData.getBytes());

                bytes = mac.doFinal(sData.getBytes());
                StringBuffer hash = new StringBuffer();

                for (int i=0; i<bytes.length; i++) {
                    String hex = Integer.toHexString(0xFF &  bytes[i]);
                    if (hex.length() == 1) {
                        hash.append('0');
                    }
                    hash.append(hex);
                }
            sEncodedString = hash.      
            return sEncodedString;
        }

提前致谢。

2 个答案:

答案 0 :(得分:21)

public static String sStringToHMACMD5(String s, String keyString)
    {
        String sEncodedString = null;
        try
        {
            SecretKeySpec key = new SecretKeySpec((keyString).getBytes("UTF-8"), "HmacMD5");
            Mac mac = Mac.getInstance("HmacMD5");
            mac.init(key);

            byte[] bytes = mac.doFinal(s.getBytes("ASCII"));

            StringBuffer hash = new StringBuffer();

            for (int i=0; i<bytes.length; i++) {
                String hex = Integer.toHexString(0xFF &  bytes[i]);
                if (hex.length() == 1) {
                    hash.append('0');
                }
                hash.append(hex);
            }
            sEncodedString = hash.toString();
        }
        catch (UnsupportedEncodingException e) {}
        catch(InvalidKeyException e){}
        catch (NoSuchAlgorithmException e) {}
        return sEncodedString ;
    }

答案 1 :(得分:6)

定义'不工作'。例外?输出不如预期?等。

一个显而易见的事情是您正在处理两次相同的数据:

mac.update(sData.getBytes());
bytes = mac.doFinal(sData.getBytes());

要一次性处理所有数据,只需使用doFinal()(假设它不是太大)。 另一个可能错误的是密钥的格式:String sKey的格式是什么。理想情况下,您应该使用BASE64编码的字符串,而不是调用getString()