【问题标题】:Issue with MD5 hash generationMD5 哈希生成问题
【发布时间】:2012-11-02 05:21:09
【问题描述】:

我正在使用以下代码为我的应用程序生成 MD5 哈希,它编码一些字符串值,然后我通过我的 Web 服务将此生成的哈希发送到一些 .Net 代码,该代码读取我的 MD5 哈希并生成字符串的 MD5他从 DB 获取的字符串,然后比较它们

public static String getMD5Hash(String val) throws Exception {
        byte[] bytes = val.getBytes();

        MessageDigest m = MessageDigest.getInstance("MD5");
        byte[] digest = m.digest(bytes);
        String hash = new BigInteger(1, digest).toString(16);
        System.out.println(hash.length());
        return hash;
    }

    public static void main(String[] asd) throws Exception{
        for(int i=0;i<10;i++){
            System.out.println(getMD5Hash(i+Math.pow(10, i)+""));//for testing
            System.out.println(getMD5Hash(i+""));//for testing
        }
    }

问题是,因为我从 BigInteger 获取转换后的哈希值,有时生成的哈希值以 0 开头,在这种情况下,Biginteger 不考虑 0,而另一方面,当 .Net 生成该哈希值时它使用 0 生成相同的字符串,这样字符串比较返回 false,例如 我生成并发送“102678D1922799CF9122B3F103975F1”的哈希码,其中 .Net 哈希为“0102678D1922799CF9122B3F103975F1

有时它也会生成类似的代码

.Net generates  0012678D1922799CF9122B3F103975F1 and java 12678D1922799CF9122B3F103975F1 

0002678D1922799CF9122B3F103975F1 and 2678D1922799CF9122B3F103975F1

我怎样才能得到这个开头全是 0 的代码。 提前致谢。

【问题讨论】:

标签: java md5


【解决方案1】:

我认为使用MessageDigest 没有比仅填充字符串更好的方法:

// ...
StringBuilder builder = new StringBuilder();
for (int i = hash.length(); i < 64; i++) {
  builder.append('0');
}
builder.append(hash);
return builder.toString();

...但是你可以使用GuavaStrings.padStart()

// ...
return Strings.padStart(hash, 64, '0');

...甚至使用Guava's hashing library,它返回与您的函数完全相同的字符串(我刚刚检查过):

public static String getMD5Hash(String val) throws Exception {
  return Hashing.md5().hashBytes(val.getBytes()).toString();
}

【讨论】:

    【解决方案2】:

    这个问题有一些更好的生成十六进制字符串的方法:

    In Java, how do I convert a byte array to a string of hex digits while keeping leading zeros?

    由于您已经在使用BigInteger,这似乎是最好的解决方案:

    BigInteger bi = new BigInteger(1, digest);
    String hash = String.format("%0" + (digest.length << 1) + "X", bi);
    

    【讨论】:

    • 谢谢你... :)
    猜你喜欢
    • 1970-01-01
    • 2017-05-24
    • 1970-01-01
    • 2011-07-26
    • 2011-08-17
    • 2015-08-14
    • 1970-01-01
    • 2013-09-08
    • 1970-01-01
    相关资源
    最近更新 更多