17

I know that there is a lot of similar topics, but still... can someone provide me a working example of method which generates MD5 String.
I'm currently using MessageDigest, and I'm doing the following to get a string

sun.misc.BASE64Encoder().encode(messageDigest.digest())  

I guess there is some better way to do that.
Thanks in advance!

4
  • Which BASE64Encoder class is this? Commented Sep 20, 2010 at 15:37
  • Sorry.... here it is import sun.misc.BASE64Encoder; Commented Sep 20, 2010 at 15:39
  • 7
    I would avoid using sun.* classes in general... See java.sun.com/products/jdk/faq/faq-sun-packages.html Commented Sep 20, 2010 at 15:41
  • Check comments on the accepted answer, there's a bug in the code shown. Commented Oct 28, 2011 at 20:52

5 Answers 5

18
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] arr = md.digest(bytesOfMessage);
return Base64.getEncoder().encodeToString(arr);

note: md5 is not considered as good hash algorithm anymore, consider choosing SHAs

Sign up to request clarification or add additional context in comments.

7 Comments

FYI: MD5 is a hashing algorithm, not a cipher. Therefore, it does not encrypt data. Rather, it hashes data.
You do not really need the overhead of creating a BigInteger in order to print a MD5 string. Printing out 16 bytes as hex is not that difficult. Also you might want to edit the source code, as Adam Paynter pointed out, MD5 is not encrypting, but hashing your data.
WARNING - THIS ALGORITHM HAS A BUG. It will drop the leading 0 of the MD5 hash. To demonstrate: use this algorithm to hash this (no quotes) "wwq123456", and do the same using an online tool like this: miraclesalad.com/webtools/md5.php and note the missing 0. The proper hash is "07e1c0d9533b5168e18a99f4540448af" but this algorithm gives "7e1c0d9533b5168e18a99f4540448af". Oops.
basic problem of above answer is it remove zero in the starting if comes so i dnt think its good for using!!!!
These comments are confusing now that the answer has been edited to a completely different implementation.
|
17

I'd use commons-codec

  • Base64 - Base64.encodeBase64(digestBytes)
  • Hex-string - Hex.encodeHex(digestBytes)

3 Comments

DigestUtils is the best solution on this page. : )
Although it's great to use library code rather than writing your own algorithm, it does come with the disadvantage that the whole library has to be included in the distribution which is a shame for the sake of just one method. Obviously, if many other classes and methods are being used too then this is ideal but this probably won't generally be the case.
Hex.encodeHex is much faster than the accepted answer
6
// Convert to hex string
StringBuffer sb = new StringBuffer();
for (int i = 0; i < messageDigest.length; i++) {
    if ((0xff & messageDigest[i]) < 0x10) {
        sb.append('0');
    }
    sb.append(Integer.toHexString(0xff & messageDigest[i]));
}
String md5 = sb.toString();

This assumes you actually want your MD5 printed as an hex string, not BASE64-encoded. That's the way it is normally represented.

2 Comments

Just a word of warning if people use this solution. It doesn't allow for leading zeroes which may throw off hash checks. So 0x0E will just be printed as E and 0x00 will be stripped down to a single 0. A basic work around is to test the length of each result and prepend a zero when the length is 1.
@MechIntel You are completely right. I just updated the answer. Thank you for the heads up!
2

I've seen next solution:

    byte[] digest = md.digest(someDataByteArray);
    StringBuilder hex = new StringBuilder();
    for (byte b : digest) {
        hex.append(String.format("%02x", b));
    }

1 Comment

This method will get actually the same result as what you get using the md5 program in the *nix terminal, and, clear enough!
0
import javax.xml.bind.DatatypeConverter;
import java.security.MessageDigest;

...
String input = "westerngun";
MessageDigest digest = MessageDigest.getInstance("MD5"); // not thread-safe, create instance for each thread
byte[] result = digest.digest(input.getBytes()); // get MD5 hash array, could contain negative
String hex = DatatypeConverter.printHexBinary(result).toLowerCase(); // convert byte array to hex string

If you want a number:

Integer number = Integer.parseInt(hex, 16); // parse hex number to integer. If overflowed, use Long.parseLong()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.