Question

I try to get MD5 string using Java, but the function below return string "MD5 Message Digest from SUN, <in progress>":

public String hash(String value) {
    try {
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(value.getBytes("UTF-8"));
        return md.toString();
    } catch (NoSuchAlgorithmException e) {
        return null;
    } catch (UnsupportedEncodingException e) {
        return null;
    }
}

I'm using OpenJDK on Xubuntu. Why I get this message? Is there a way to get MD5 hash using this setup?

Was it helpful?

Solution

I found the solution that work,

public String byteToHexString(byte[] input) {
    String output = "";
    for (int i=0; i<input.length; ++i) {
        output += String.format("%02X", input[i]);
    }
    return output;
}

public String hash(String value) {
    try {
        MessageDigest md = MessageDigest.getInstance("MD5");
        return byteToHexString(md.digest(value.getBytes("UTF-8")));
    } catch (NoSuchAlgorithmException e) {
        return null;
    } catch (UnsupportedEncodingException e) {
        return null;
    }
}

OTHER TIPS

One option would be to use commons-codec.jar. Check the API.

String value = "YourValue";
System.out.println(DigestUtils.md5Hex( value ));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top