【问题标题】:Different between PHP md5 and JAVA md5PHP md5 和 JAVA md5 的区别
【发布时间】:2014-10-28 03:02:37
【问题描述】:

我在JAVA中定义了一个md5函数,使用PHP:md5()函数进行编码,但是输出的结果不同。

我猜我的 JAVA 函数有问题。

代码如下:

public static String MD5Encode(String sourceString) throws Exception {
    MessageDigest md = MessageDigest.getInstance("MD5");
    byte[] bytes = md.digest();
    StringBuffer bf = new StringBuffer(bytes.length * 2);
    for (int i = 0; i < bytes.length; i++) {
        if ((bytes[i] & 0xff) < 0x10) {
            bf.append("0");
        }
        bf.append(Long.toString(bytes[i] & 0xff, 16));
    }
    return bf.toString();
}

【问题讨论】:

    标签: java php md5


    【解决方案1】:
    private static String MD5Encode(String sourceString) {
    try {
    byte[] bytesOfMessage = sourceString.getBytes("UTF-8");
    MessageDigest md = MessageDigest.getInstance("MD5");
    // byte array of md5 hash
    byte[] md5 = md.digest(bytesOfMessage);
    // we convert bytes to hex as php's md5() would do
    StringBuffer stringBuffer = new StringBuffer();
    for (int i = 0; i < md5.length; i++) {
    stringBuffer.append(Integer.toString((md5[i] & 0xff) + 0x100, 
    16).substring(1));
    }
    return stringBuffer.toString();
    } catch (Exception e) {
    }
    return null;
    }
    

    【讨论】:

    • PHP 的 md5() 函数将 md5 哈希作为十六进制返回。如果你想在 java 中获取 md5 哈希作为字符串,你可以这样写
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-02
    • 2014-06-26
    • 1970-01-01
    • 2010-11-05
    • 1970-01-01
    相关资源
    最近更新 更多