2

After checking this question (How can I generate an MD5 hash?) and reading the MessageDigest documentation, I attempted to hash a simple string. But for some reason every string I pass into the method returns the same value. Below shows the code I wrote.

    byte[] bytesOfMessage = "helloworld".getBytes("UTF-8");
    MessageDigest md = MessageDigest.getInstance("MD5");
    byte[] thedigest = md.digest(bytesOfMessage);
    System.out.println(thedigest);

and is there anyway to limit the number of characters I get from the hash?

aspire29
  • 461
  • 3
  • 16
  • What method? Can you share all code required for reproducing the problem? – Mick Mnemonic Mar 03 '18 at 21:46
  • 1
    Use `System.out.println(Arrays.toString(thedigest))`. Your code doesn't actually print the contents of the array. – Jorn Vernee Mar 03 '18 at 21:46
  • @JornVernee when I change the code to that, the output is an array containing integers. – aspire29 Mar 03 '18 at 21:50
  • @MickMnemonic that's all the code I wrote. The method I was referring to is the digest() one in line 3 – aspire29 Mar 03 '18 at 21:51
  • What result is returned in the given example? – Dorian Gray Mar 03 '18 at 22:00
  • @TobiasWeimer [B@5b1d2887 is the result – aspire29 Mar 03 '18 at 22:02
  • 1
    Thats the address of the Array, as pointed out above. You need to convert the byte array to String, like this: System.out.println(new String(thedigest)); – Dorian Gray Mar 03 '18 at 22:04
  • 3
    @TobiasWeimer+OP: a digest is effectively random bits so `new String(byte[])` using the platform-dependent default charset will often discard or destroy much of the data. Better to use hex or base64, or at least specify `ISO-8859-1` (aka Latin-1) so it reliably preserves all byte values. – dave_thompson_085 Mar 03 '18 at 22:36

1 Answers1

1

System.out.println(thedigest); calling the toString() method of your array.

Java array type does not override the default implementation of Object#toString():

// from Object.java
public String toString() {
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

that's why you see the string [B@5b1d2887

If you want to print an array, use java utility class java.util.Arrays:

System.out.println(Arrays.toString(myArray));

But in your case, you should create a human readable string from your MD5 digest byte array. Use this simple method fo this:

public static String digestToReadableString(byte[] digest){
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < digest.length; i++) {
        String s = Integer.toHexString(digest[i]);
        while (s.length() < 2) {
            s = "0" + s;
        }
        s = s.substring(s.length() - 2); // we need the last 2 chars
        sb.append(s);
    }
    return sb.toString();
}

Or this one: https://stackoverflow.com/a/304275/1614378

alex
  • 8,904
  • 6
  • 49
  • 75