简体   繁体   English

Java MD5 散列函数给出不正确的散列

[英]Java MD5 hashing function giving incorrect hash

I've got a problem with the Java md5 hashing function not returning the correct value.我遇到了 Java md5 散列函数没有返回正确值的问题。 For most values it does return the correct value, however I have found one example of an input with incorrect out.对于大多数值,它确实返回正确的值,但是我发现了一个输入不正确的示例。

My code is:我的代码是:

public String hash(String pass) throws Exception
{
    encr = MessageDigest.getInstance("MD5");
    return new BigInteger(1, encr.digest(pass.getBytes())).toString(16);
}

This returns the correct answer for most of the examples I've tried such as hash("beep") -> "1284e53a168a5ad955485a7c83b10de0", hash("hello") -> "5d41402abc4b2a76b9719d911017c592" etc...这将返回我尝试过的大多数示例的正确答案,例如 hash("beep") -> "1284e53a168a5ad955485a7c83b10de0", hash("hello") -> "5d41402abc4b2a76b9719d911017c59

Then comes the problem: hash("dog") -> "6d80eb0c50b49a509b49f2424e8c805" instead of "06d80eb0c50b49a509b49f2424e8c805" that I have got from several online md5 generators as well as the psql md5 generator (which my cod is interacting with).然后是问题:hash("dog") -> "6d80eb0c50b49a509b49f2424e8c805" 而不是我从几个在线 md5 生成器获得的 "06d80eb0c50b49a509b49f2424e8c805"。

I'd much appreciate any light that can be shed on this by anyone, Thanks.我非常感谢任何人都可以对此有所了解,谢谢。

By default it doesn't include leading zeros, but you can easily pad these yourself:默认情况下,它不包含前导零,但您可以轻松地自己填充这些:

String md5 = new BigInteger(1, encr.digest(pass.getBytes())).toString(16);
return String.format("%32s", md5).replace(' ', '0');
// this code will resolve hashcode issue 
// I hope this helps everyone.

 private static String makeHash(String key_to_hash) {
            try {
                MessageDigest md = MessageDigest.getInstance("SHA1");
                md.reset();
                md.update(key_to_hash.getBytes(Charset.forName("UTF-8")));
                return bytesToHex(md.digest());
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            return null;
        }



private static String bytesToHex(byte[] b) {
                char hexDigit[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                        'a', 'b', 'c', 'd', 'e', 'f','A', 'B', 'C', 'D', 'E', 'F' };
                StringBuffer buf = new StringBuffer();
                for (int j = 0; j < b.length; j++) {
                    buf.append(hexDigit[(b[j] >> 4) & 0x0f]);
                    buf.append(hexDigit[b[j] & 0x0f]);
                }
                return buf.toString();
            }

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

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