Home » Php » md5 with Android and PHP

md5 with Android and PHP

Posted by: admin July 12, 2020 Leave a comment

Questions:

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.
How to&Answers:

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

md5(utf8_encode($string));

Answer:

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

Instead, try:

digest.update(s.getBytes("UTF-8");