Alex Rivera | Logout

Java md5, the PHP way

Asked 2010-11-15T11:00:32.230
9

I have been working on this for hours, but I can't get it to work.

Basically I am developing a REST client in Java for a REST server in PHP. Both the client and the server have to compute the md5 of a string and the server will compare them for authentication (kinda).

On the server, the PHP code is:

md5("getTokenapi_keybf8ddfs845jhre980543jhsjfro93fd8capi_ver1tokeniud9ER£jdfff");

that generates:

4d7b2e42c3dfd11de3e77b9fe2211b87

Nice!

Here is the code for the client:

import java.security.*;
....
String s = "getTokenapi_keybf8ddfs845jhre980543jhsjfro93fd8capi_ver1tokeniud9ER£jdfff";
byte[] bytesOfMessage = s.getBytes("UTF-8");
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] thedigest = md.digest(bytesOfMessage);    

System.out.println("String2: " + thedigest);        
System.out.println("String3: " + new String(thedigest));

That generates:

String2: [B@42e816
String3: M{.B�����{��!�

How can I get Java to compute the md5 sum the same way PHP does, please?

Thanks, Dan

Edit
Report

1 Answer

24

Give this a try:

public static String md5(String input) throws NoSuchAlgorithmException {
    String result = input;
    if(input != null) {
        MessageDigest md = MessageDigest.getInstance("MD5"); //or "SHA-1"
        md.update(input.getBytes());
        BigInteger hash = new BigInteger(1, md.digest());
        result = hash.toString(16);
        while(result.length() < 32) { //40 for SHA-1
            result = "0" + result;
        }
    }
    return result;
}

code from http://web.archive.org/web/20140209230440/http://www.sergiy.ca/how-to-make-java-md5-and-sha-1-hashes-compatible-with-php-or-mysql/

answered 2010-11-15T11:03:54.243

Your Answer