What will be the Android/Java equivalent of MD5 function in PHP?

不羁岁月 提交于 2019-12-18 11:59:55

问题


I am calculating the MD5 in Android/Java as follows:

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

However there's a mismatch with PHP's md5() function.

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

How is this caused and how can I solve it so that the both Android/Java and PHP generate exactly the same MD5 hash?


回答1:


You need to prefix hex value with 0 when the byte is less than 0x10. Here's a full example:

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


来源:https://stackoverflow.com/questions/5494447/what-will-be-the-android-java-equivalent-of-md5-function-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!