在PHP中,Android / Java相当于MD5的功能是什么?

时间:2011-03-31 01:43:01

标签: java php md5

我正在计算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哈希?

1 个答案:

答案 0 :(得分:17)

当字节小于0时,您需要将十六进制值加上0x10前缀。这是一个完整的例子:

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