Convert MD5 array to String java

Viewed 32988

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!

5 Answers
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()
Related