Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What will be the Android/Java equivalent of MD5 function in PHP?

Tags:

java

php

md5

I am calculating the MD5 in Android/Java as follows:

byte raw[] = md.digest();   
StringBuffer hexString = new StringBuffer();
for (int i=0; i<raw.length; i++)
    hexString.append(Integer.toHexString(0xFF & raw[i]));
v_password = hexString.toString();

However there's a mismatch with PHP's md5() function.

MD5 - PHP  - Raw Value - catch12 - 214423105677f2375487b4c6880c12ae
MD5 - JAVA - Raw Value - catch12 - 214423105677f2375487b4c688c12ae

How is this caused and how can I solve it so that the both Android/Java and PHP generate exactly the same MD5 hash?

like image 705
Aakash Avatar asked Mar 31 '11 01:03

Aakash


1 Answers

You need to prefix hex value with 0 when the byte is less than 0x10. Here's a full example:

public static String md5(String string) {
    byte[] hash;

    try {
        hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("Huh, MD5 should be supported?", e);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException("Huh, UTF-8 should be supported?", e);
    }

    StringBuilder hex = new StringBuilder(hash.length * 2);

    for (byte b : hash) {
        int i = (b & 0xFF);
        if (i < 0x10) hex.append('0');
        hex.append(Integer.toHexString(i));
    }

    return hex.toString();
}
like image 105
BalusC Avatar answered Oct 05 '22 23:10

BalusC