繁体   English   中英

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

[英]What will be the Android/Java equivalent of MD5 function in 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哈希?

当字节小于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();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM