Wednesday, May 30, 2012

Generate MD5 hash in Java


Is there any method to generate MD5 hash of a string in Java?



Source: Tips4all

15 comments:

  1. MessageDigest is your friend. Call getInstance("MD5") to get an MD5 message digest you can use.

    ReplyDelete
  2. The MessageDigest class can provide you with an instance of the MD5 digest.

    Always when working with strings and the crypto classes be sure to always specify the encoding you want the byte representation in. If you just use string.getBytes() it will use the platform default. (Not all platforms use the same defaults)

    import java.security.*;

    ..

    byte[] bytesOfMessage = yourString.getBytes("UTF-8");

    MessageDigest md = MessageDigest.getInstance("MD5");
    byte[] thedigest = md.digest(bytesOfMessage);


    If you have a lot of data take a look at the .update(byte[]) method which can be called repeatedly. Then call .digest() to obtain the resulting hash.

    ReplyDelete
  3. You might also want to look at the DigestUtils class of the apache commons codec project, which provides very convenient methods to create MD5 or SHA digests.

    ReplyDelete
  4. If you actually want the answer back as a string as opposed to a byte array, you could always do something like this:

    String plaintext = 'your text here';
    MessageDigest m = MessageDigest.getInstance("MD5");
    m.reset();
    m.update(plaintext.getBytes());
    byte[] digest = m.digest();
    BigInteger bigInt = new BigInteger(1,digest);
    String hashtext = bigInt.toString(16);
    // Now we need to zero pad it if you actually want the full 32 chars.
    while(hashtext.length() < 32 ){
    hashtext = "0"+hashtext;
    }

    ReplyDelete
  5. Here is how I use it:

    final MessageDigest messageDigest = MessageDigest.getInstance("MD5");
    messageDigest.reset();
    messageDigest.update(string.getBytes(Charset.forName("UTF8")));
    final byte[] resultByte = messageDigest.digest();
    final String result = new String(Hex.encodeHex(resultByte));


    where Hex is: org.apache.commons.codec.binary.Hex from the Apache Commons project.

    ReplyDelete
  6. Found this:

    public String MD5(String md5) {
    try {
    java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
    byte[] array = md.digest(md5.getBytes());
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < array.length; ++i) {
    sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1,3));
    }
    return sb.toString();
    } catch (java.security.NoSuchAlgorithmException e) {
    }
    return null;
    }


    on the site below, I take no credit for it, but its a solution that works!
    For me lots of other code didnt work properly, I ended up missing 0s in the hash.
    This one seems to be the same as PHP has.
    source: http://m2tec.be/blog/2010/02/03/java-md5-hex-0093

    ReplyDelete
  7. Bombe's answer is correct, however note that unless you absolutely must use MD5 (e.g. forced on you for interoperability), a better choice is SHA1 as MD5 has weaknesses for long term use.

    I should add that SHA1 also has theoretical vulnerabilities, but not as severe. The current state of the art in hashing is that there are a number of candidate replacement hash functions but none have yet emerged as the standard best practice to replace SHA1. So, depending on your needs you would be well advised to make your hash algorithm configurable so it can be replaced in future.

    ReplyDelete
  8. I just downloaded commons-codec.jar and got perfect php like md5. Here is manual http://commons.apache.org/codec/api-release/org/apache/commons/codec/digest/DigestUtils.html

    Just import it to your project and use

    String Url = "your_url";

    System.out.println( DigestUtils.md5Hex( Url ) );


    and there you have it.

    ReplyDelete
  9. MD5 is perfectly fine if you don't need the best security, and if you're doing something like checking file integrity then security is not a consideration. In such as case you might want to consider something simpler and faster, such as Adler32, which is also supported by the Java libraries.

    ReplyDelete
  10. Take a look at the following link, the Example gets an MD5 Hash of a supplied image:
    MD5 Hash of an Image

    ReplyDelete
  11. Another implementation: Fast MD5 Implementation in Java

    String hash = MD5.asHex(MD5.getHash(new File(filename)));

    ReplyDelete
  12. There is an article on JavaBlogging about that. Check out: http://www.javablogging.com/sha1-and-md5-checksums-in-java/

    ReplyDelete
  13. My not very revealing answer:

    private String md5(String s) {
    try {
    MessageDigest m = MessageDigest.getInstance("MD5");
    m.update(s.getBytes(), 0, s.length());
    BigInteger i = new BigInteger(1,m.digest());
    return String.format("%1$032x", i);
    } catch (NoSuchAlgorithmException e) {
    e.printStackTrace();
    }
    return null;
    }

    ReplyDelete
  14. Weakness of hash algorithms:

    Rogue attack of SSL Certificates
    MD5 collisions

    ReplyDelete
  15. Found this solution which is much cleaner in terms of getting a String representation back from an MD5 hash.

    import java.security.*;

    import java.math.*;
    public class MD5 {

    public static void main(String args[]) throws Exception{

    String s="This is a test";

    MessageDigest m=MessageDigest.getInstance("MD5");

    m.update(s.getBytes(),0,s.length());

    System.out.println("MD5: "+new BigInteger(1,m.digest()).toString(16));

    }

    }


    The code was extracted from here.

    ReplyDelete