Question

I am trying to generate an MD5 hex hash using the following code:

String password = "password";

MessageDigest digest = MessageDigest.getInstance("MD5");

ByteArrayInputStream bais = new ByteArrayInputStream(password.getBytes());

int size = 16;
byte[] bytes = new byte[size];
while ((bais.read(bytes, 0, size)) != -1)
{
  digest.update(bytes);
}

byte[] hash = digest.digest();
StringBuilder sb = new StringBuilder(2 * hash.length);
for (byte b : hash)
{
  sb.append(String.format("%02x", b & 0xff));
}

System.out.println("MD5:/ " + sb.toString());

The output should be 5f4dcc3b5aa765d61d8327deb882cf99 (as checked with md5sum), but I fail to see where the error is. What am I doing wrong?

Was it helpful?

Solution 2

You put always a full bytes array (16 bytes) into the digest, even if the password was shorter.

Btw. the whole construction with the stream is not necessary, you can simply do:

byte[] hash = digest.digest(password.getBytes("UTF-8"));

OTHER TIPS

I don't know what is wrong with yours, but this should work:

byte[] array = MessageDigest.getInstance("MD5").digest("password".getBytes("UTF-8"));              
StringBuffer sb = new StringBuffer();
for (int i = 0; i < array.length; ++i) {
    sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1, 3));            
}
System.out.println(sb.toString());

You should update only part of read bytes:

    int len;
    byte[] bytes = new byte[size];
    while ((len = bais.read(bytes, 0, size)) != -1)
    {
        digest.update(bytes, 0, len);
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top