2011-03-31 5 views
5

Estoy calculando el MD5 en Android/Java de la siguiente manera:¿Cuál será el equivalente Android/Java de la función MD5 en PHP?

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

Sin embargo hay una falta de coincidencia con la función de PHP md5().

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

cómo es esto provocó y cómo puedo resolverlo de manera que el tanto en Android/Java y PHP generan exactamente el mismo hash MD5?

Respuesta

17

Tiene que prefijar el valor hexadecimal con 0 cuando el byte es menor que 0x10. Aquí hay un ejemplo completo:

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