Java和php5 MD5 Hash之间的区别 [英] Difference between Java and php5 MD5 Hash

查看:897
本文介绍了Java和php5 MD5 Hash之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我面临着一个奇怪的问题,它与Java和php5中的MD5-Hashes有关。
我认为在某些情况下,下面的代码没有
生成正确的MD5哈希:

I'm facing kind of a strange issue which is related MD5-Hashes in Java and php5. I figured that unter certain circumstances the following code does not generate correct MD5 hashes:

public static String getMD5Hash(String string)
{
    try 
    {
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        md5.update(string.getBytes());
        byte[] digest = md5.digest();

        string = byteArrToHexString(digest);
    } 
    catch (NoSuchAlgorithmException e1) 
    {
        e1.printStackTrace();
    }

    return string;
}

private static String byteArrToHexString(byte[] bArr)
{
    StringBuffer sb = new StringBuffer();

    for (int i = 0; i < bArr.length; i++) 
    {
        int unsigned = bArr[i] & 0xff;
        sb.append(Integer.toHexString((unsigned)));
    }

    return sb.toString();
}

我必须迁移现有的用户数据库,其中存储的密码为
在php5 MD5中。现在有些用户(不是全部用户)无法登录,因为我的Java代码
不能生成正确的MD5哈希。

I had to migrate an existing user database where the passwords where stored in php5 MD5. Now some of the users, not all, can't login because my Java code does not produce the correct MD5 hash.

上述任何想法有什么问题?

Any ideas what's wrong with the above?

推荐答案

byteArrToHexString 没有正确转换字节< 0x10,你需要用零填充它们。

byteArrToHexString does not convert bytes <0x10 correctly, you need to pad them with zeros.

示例:

int unsigned = bArr[i] & 0xff;
if (unsigned < 0x10)
  sb.append("0");
sb.append(Integer.toHexString((unsigned)));

这篇关于Java和php5 MD5 Hash之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆