2

When I encrypt something in md5 with java, it removes all the 0s from the hash, which isn't ok for me because it doesn't work with php, since php doesn't remove the 0s. Is there any way to fix it(other than making php remove 0s too). Here's my java code:

public String getMd5Hash(String str) {
    try {
        byte[] array = MessageDigest.getInstance("MD5").digest(str.getBytes());
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < array.length; ++i) {
            sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1,3));
        }
        return sb.toString();
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException("Something went really wrong.");
    }
    return null;
}
Edd
  • 3,724
  • 3
  • 26
  • 33
  • http://stackoverflow.com/questions/415953/generate-md5-hash-in-java – juniperi Jun 21 '13 at 13:53
  • Can you give an example where this produces incorrect output? – tom Jun 21 '13 at 13:58
  • Is this just a padding problem (e.g. leading zeroes are removed)? If so, isn't an MD5 hash always the same length in terms of number of digits that it contains? And if so, can't you just pad the result with zeroes on the left-hand side to make it that length? – jefflunt Jun 21 '13 at 14:22

1 Answers1

1

Integer.toHexString will not prepend zeros to the length you implicitly desire. Use the java.util.Formatter class with a "%02x" format string to get the hex digits into the format you want.

The following code demonstrates the problem.

import java.util.Formatter;

public class TestHex {

    public static final void main(String[]  args) {
        StringBuilder sb = new StringBuilder();
        Formatter formatter = new Formatter(sb);
        byte[] testbytes = {-127, 4, 64, -4};

        for (int i=0; i<testbytes.length; i++) {
            byte b = testbytes[i];
            System.out.printf("%s\t%s\n", formatter.format("%02x", b), Integer.toHexString(b & 0xff));
            sb.setLength(0);
        }
    }
}

When run, this produces:

81      81
04      4
40      40
fc      fc

Note the second row, where the Integer.toHexString returns just '4' and the formatter gives you the two digits you require.

schtever
  • 3,210
  • 16
  • 25