0

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?

carlspring
  • 31,231
  • 29
  • 115
  • 197

3 Answers3

2

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());
Fortega
  • 19,463
  • 14
  • 75
  • 113
1

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);
    }
Tyco
  • 131
  • 4
1

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"));
Henry
  • 42,982
  • 7
  • 68
  • 84