Question

I've got a problem with the Java md5 hashing function not returning the correct value. 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...

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).

I'd much appreciate any light that can be shed on this by anyone, Thanks.

Was it helpful?

Solution

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

OTHER TIPS

// 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();
            }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top