Get MD5 String from Message Digest

78,370

Solution 1

Try this

StringBuffer hexString = new StringBuffer();
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] hash = md.digest();

for (int i = 0; i < hash.length; i++) {
    if ((0xff & hash[i]) < 0x10) {
        hexString.append("0"
                + Integer.toHexString((0xFF & hash[i])));
    } else {
        hexString.append(Integer.toHexString(0xFF & hash[i]));
    }
}

Solution 2

You can get it writing less:

String hex = (new HexBinaryAdapter()).marshal(md5.digest(YOUR_STRING.getBytes()))

Solution 3

    String input = "168";
    MessageDigest md = MessageDigest.getInstance("MD5");
    byte[] md5sum = md.digest(input.getBytes());
    String output = String.format("%032X", new BigInteger(1, md5sum));

or

DatatypeConverter.printHexBinary( MessageDigest.getInstance("MD5").digest("a".getBytes("UTF-8")))

Solution 4

You can also use Apache Commons Codec library. This library includes methods public static String md5Hex(InputStream data) and public static String md5Hex(byte[] data) in the DigestUtils class. No need to invent this yourself ;)

Solution 5

First you need to get the byte[] output of the MessageDigest:

byte[] bytes = hash.digest();

You can't easily print this though (with e.g. new String(bytes)) because it's going to contain binary that won't have good output representations. You can convert it to hex for display like this however:

StringBuilder sb = new StringBuilder(2 * bytes.length);
for (byte b : bytes) {
    sb.append("0123456789ABCDEF".charAt((b & 0xF0) >> 4));
    sb.append("0123456789ABCDEF".charAt((b & 0x0F)));
}
String hex = sb.toString();
Share:
78,370
Tom
Author by

Tom

Updated on December 17, 2020

Comments

  • Tom
    Tom over 3 years

    I understand how it works but if I want to print out the MD5 as String how would I do that?

    public static void getMD5(String fileName) throws Exception{
        InputStream input =  new FileInputStream(fileName);
        byte[] buffer = new byte[1024];
    
        MessageDigest hash = MessageDigest.getInstance("MD5");
        int read;
        do {
            read = input.read(buffer);
            if (read > 0) {
                hash.update(buffer, 0, read);
            }
        } while (read != -1);
        input.close();
    }
    
  • Dan J
    Dan J over 11 years
    Do you know if there are any performance considerations here? Assuming we reused a single HexBinaryAdapter, would this introduce any significant overheads compared to doing the bit operations ourselves? We need to use this code a lot as we use the MD5 for URLs as the key into our image cache.
  • mpontes
    mpontes over 11 years
    Java's source is public. :) HexBinaryAdapter.marshal() only calls DatatypeConverter.printHexBinary() (you can actually use that instead, if you want to avoid instantiating a HexBinaryAdapter), which in turn instantiates a singleton DatatypeConverterImpl the first time it's called. After that, it's just a straight call to DatatypeConverterImpl's printHexBinary. It uses a method pretty similar to WhiteFang34's answer.
  • FanaticD
    FanaticD almost 9 years
    Note also that StringBuilder can be now used instead of StringBuffer, cons and pros of each are discussed in this question: stackoverflow.com/questions/355089/…
  • mech
    mech over 8 years
    Welcome to Stack Overflow, @WillBerger ! While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value.
  • user1133275
    user1133275 almost 7 years
    DatatypeConverter is not in JDK9
  • user1133275
    user1133275 almost 7 years
    HexBinaryAdapter is not in JDK9
  • stacker
    stacker almost 7 years
  • user1133275
    user1133275 almost 7 years
    yah I was just looking at that temporary hack for a lib, but for this question answers that do not depend on deprecated code are better.
  • harley
    harley over 5 years
    BigInteger seems to have an issue when the leading hex digit is 0.
  • Teddy
    Teddy about 3 years
    Thanks for mentioning the actual problem, and what would come as a first thought in byte-string which is to just use the string constructor. Also, I'm surprised no one suggested Base64. How does Base64 compare to these HexToBinary answers.
  • Teddy
    Teddy about 3 years