38

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();
}
Willi Mentzel
  • 27,862
  • 20
  • 113
  • 121
Tom
  • 765
  • 2
  • 8
  • 8

11 Answers11

79

You can get it writing less:

String hex = (new HexBinaryAdapter()).marshal(md5.digest(YOUR_STRING.getBytes()))
arutaku
  • 5,937
  • 1
  • 24
  • 38
  • 1
    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. – Dan J Dec 18 '12 at 22:09
  • 14
    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. – mpontes Mar 22 '13 at 19:01
  • 5
    HexBinaryAdapter is not in JDK9 – user1133275 Aug 30 '17 at 21:49
29
    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")))
stacker
  • 68,052
  • 28
  • 140
  • 210
23

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]));
    }
}
Willi Mentzel
  • 27,862
  • 20
  • 113
  • 121
ajm
  • 12,863
  • 58
  • 163
  • 234
  • 2
    Note also that StringBuilder can be now used instead of StringBuffer, cons and pros of each are discussed in this question: http://stackoverflow.com/questions/355089/stringbuilder-and-stringbuffer – FanaticD Sep 22 '15 at 17:31
23

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 ;)

mmjmanders
  • 1,533
  • 2
  • 13
  • 32
9

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();
WhiteFang34
  • 70,765
  • 18
  • 106
  • 111
  • 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 Apr 06 '21 at 15:22
  • Found this: https://stackoverflow.com/a/3183880/1364747 – Teddy Apr 06 '21 at 15:24
7

Shortest way:

String toMD5(String input) {
    MessageDigest md = MessageDigest.getInstance("MD5");
    byte[] raw = md.digest(input.getBytes());
    return DatatypeConverter.printHexBinary(raw);
}

Just remember to handle the exception.

4

With the byte array, result from message digest:

...
byte hashgerado[] = md.digest(entrada);
...

for(byte b : hashgerado)
    System.out.printf("%02x", Byte.toUnsignedInt(b));

Result (for example):
89e8a9f68ad3c4bba9b9d3581cf5201d

carlao2005
  • 315
  • 2
  • 8
2
/**
 * hashes:
 * e7cfa2be5969e235138356a54bad7fc4
 * 3c9ec110aa171b57bb41fc761130822c
 *
 * compiled with java 8 - 12 Dec 2015
 */
public static String generateHash() {
    long r = new java.util.Random().nextLong();
    String input = String.valueOf(r);
    String md5 = null;

    try {
        java.security.MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
        //Update input string in message digest
        digest.update(input.getBytes(), 0, input.length());
        //Converts message digest value in base 16 (hex)
        md5 = new java.math.BigInteger(1, digest.digest()).toString(16);
    }
    catch (java.security.NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return md5;
}
blueberry0xff
  • 3,707
  • 30
  • 18
2

FYI...

In certain situations this did not work for me

md5 = new java.math.BigInteger(1, digest.digest()).toString(16);

but this did

StringBuilder sb = new StringBuilder();

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

String result = sb.toString();
  • 1
    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. – mech Feb 27 '16 at 00:44
-1

Call hash.digest() to finish the process. It will return an array of bytes.

You can create a String from a byte[] using a String constructor, however if you want a hex string you'll have to loop through the byte array manually and work out the characters.

Priidu Neemre
  • 2,813
  • 2
  • 39
  • 40
brain
  • 5,496
  • 1
  • 26
  • 29
-2

This is another version of @anything answer:

StringBuilder sb = new StringBuilder();

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

String result = sb.toString();
Ernestas Gruodis
  • 8,567
  • 14
  • 55
  • 117