2011-03-31 16 views
5

我在的Android/Java的计算MD5如下:在PHP中,什么是Android/Java的MD5函数?

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(); 

但是有一个与PHP的md5()功能不匹配。

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

这是如何引起的,我该如何解决它,以便Android/Java和PHP生成完全相同的MD5哈希?

回答

17

当字节小于0x10时,您需要以0作为前缀十六进制值。这里有一个完整的例子:

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(); 
}