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

Aak*_*ash 5 php java 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();
Run Code Online (Sandbox Code Playgroud)

然而,与PHP的md5()功能不匹配.

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

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

Bal*_*usC 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();
}
Run Code Online (Sandbox Code Playgroud)