Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

md5 with Android and PHP

I am using an md5 to secure my posts to a backendserver running PHP. The parameters are send via HTTP Post.

I have one problem, the result of my md5 calculation is different on Android and the PHP server if there is a ü, ä or ö in one of the input parameters.

On Android, the hash is calculated via this function:

public static final String md5(final String s) {
    try {
        // Create MD5 Hash
        MessageDigest digest = java.security.MessageDigest
                .getInstance("MD5");
        digest.update(s.getBytes());
        byte messageDigest[] = digest.digest();

        // Create Hex String
        StringBuffer hexString = new StringBuffer();
        for (int i = 0; i < messageDigest.length; i++) {
            String h = Integer.toHexString(0xFF & messageDigest[i]);
            while (h.length() < 2)
                h = "0" + h;
            hexString.append(h);
        }
        return hexString.toString();

    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return "";
}

on the PHP server I simply use

md5() function.
like image 483
tobias Avatar asked Jan 02 '12 12:01

tobias


2 Answers

Looks like you need to pass utf-8 encoded string to md5 in PHP:

md5(utf8_encode($string));
like image 115
Juicy Scripter Avatar answered Oct 13 '22 06:10

Juicy Scripter


It could be that you are using the platform's default charset.

Instead, try:

digest.update(s.getBytes("UTF-8");
like image 23
zaf Avatar answered Oct 13 '22 07:10

zaf