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

2023-09-07 16:17:33 作者:北巷九命猫

我想创建一个Android MD5哈希字符串等于C#code波纹管:

I am trying to create an android MD5 hash string to equal the C# code bellow:

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);
}

安卓code,我目前使用[ 不产生相同的C#code 的]:

Android code that I currently use [not generating the same C# code]:

        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;
        }

在此先感谢。

Thanks in advance.

推荐答案

定义不工作。例外?产量不如预期?等等。

Define 'not working'. Exception? Output not as expected?, etc.

一个明显的一点是,你是处理相同的数据两次:

One obvious thing is that you are processing the same data twice:

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

要处理所有的数据在一通,只需要使用 doFinal()(假设它不是太大)。 另一件事,可能是错是关键的格式:是什么的字符串SKEY 的格式。理想情况下,你应该使用base64连接codeD字符串,而不是调用的getString()

To process all data in one pass, just use doFinal() (assuming it's not too big). Another thing that can be wrong is the format of the key: what is the format of String sKey. Ideally you should be using a BASE64 encoded string, not calls to getString().