5

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


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.

3
  • possible duplicate of How to Generate HMAC MD5 In Android? Commented Dec 6, 2011 at 7:14
  • 1
    @Thilo: I checked the link you provided my self, the solution is not working. Commented Dec 6, 2011 at 7:21
  • + the answer that you linked does not use 2 keys (data + key) Commented Dec 6, 2011 at 7:25

2 Answers 2

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 ;
    }
Sign up to request clarification or add additional context in comments.

2 Comments

Don't ignore the exceptions. Log them.
sure but i remove the Exception to reduce the code above.
6

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

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().

2 Comments

I see your point you are correct, please check my solution, thanks for the hint.
Dump (or use the debugger) in both programs the byte[] keyByte, make sure the bytes are the same. Do the same with byte[] messageBytes. If all those match, byte[] hashmessage should too, but check that as well. If those match, the error is in the final hex encoding part.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.