Page 1 of 1

Md5 from java to php

Posted: 10 Jan 2011, 07:52
by smilefr
I am trying to generate the same MD5 code as the md5() function in php.

Therefore when i use this code, the result is different:

Code: Select all

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);
            if ((result.length() % 2) != 0) {
                result = "0" + result;
            }
        }
        return result;
    }
Any help would be greatly appreciated.

Posted: 10 Jan 2011, 08:25
by janux
Try something like this:

Code: Select all

	private static String md5(String input) throws NoSuchAlgorithmException {
		String res = "";
		MessageDigest md = MessageDigest.getInstance("MD5");
		try {
			md.reset();
			md.update(input.getBytes());
			byte[] bres = md.digest();
			StringBuffer hexString = new StringBuffer();
			for (int i=0;i<bres.length;i++) {
				hexString.append(Integer.toHexString(0xFF & bres[i]));
			}
			res = hexString.toString();			
		} catch (Exception ex) {
			
		}	
		return res;
	}

Posted: 10 Jan 2011, 08:30
by smilefr
Thank you, i will give it a try.

Posted: 12 Jan 2011, 08:17
by janux
smilefr wrote:Thank you, i will give it a try.
btw found some thing in sfs2x docs

You could use

com.smartfoxserver.v2.util.MD5