Mehdi
Mehdi

Reputation: 77

MD5 in Java different from MD5sum in shell

I'm trying to generate an MD5 hash using Java and Shell but the problem is I get different results using :

    public String generateHash(String name) throws UnsupportedEncodingException, NoSuchAlgorithmException {
    MessageDigest digester = MessageDigest.getInstance("MD5");
    digester.update(name.getBytes());
    byte[] md5Bytes = digester.digest();
    String md5Text = null;

    md5Text = bytesToHex(md5Bytes);

    return md5Text;
}

    public static String bytesToHex(byte[] bytes) {
    char[] hexChars = new char[bytes.length * 2];
    for (int j = 0; j < bytes.length; j++) {
        int v = bytes[j] & 0xFF;
        hexChars[j * 2] = hexArray[v >>> 4];
        hexChars[j * 2 + 1] = hexArray[v & 0x0F];
    }
    return new String(hexChars);
}

and using :

md5sum

How can I get the same result as the "md5sum" command in Java ?

Upvotes: 3

Views: 1578

Answers (1)

Alex R
Alex R

Reputation: 3311

Under the assumption that

private static final char[] hexArray = "0123456789abcdef".toCharArray();

both methods, i.e. you program and md5sum, produce the same result. Be careful to not accidentaly add any newlines.

You can compare the result of both of these example to check that you get the same output:

System.out.println(generateHash("ABCDEF"));
System.out.println(generateHash("ABCDEF\n"));
echo -n  "ABCDEF" | md5sum
echo "ABCDEF" | md5sum

Output:

8827a41122a5028b9808c7bf84b9fcf6
f6674e62795f798fe2b01b08580c3fdc

Upvotes: 5

Related Questions