Home > DeveloperSection > Forums > How can I generate an MD5 hash?
Nigel Bunyan
Nigel Bunyan

Total Post:20

Posted on    July-03-2015 12:52 AM

 Java Java 

 1 Reply(s)
 709  View(s)
Rate this:
Is there any method to generate MD5 hash of a string in Java?

Mayank Tripathi
Mayank Tripathi

Total Post:397

Posted on    July-03-2015 8:33 AM

There's an input stream decorator, java.security.DigestInputStream, so that you can compute the digest while using the input stream as you normally would, instead of having to make an extra pass over the data.

MessageDigest md = MessageDigest.getInstance("MD5");
try (InputStream is = Files.newInputStream(Paths.get("file.txt"))) {
  DigestInputStream dis = new DigestInputStream(is, md);
  /* Read stream to EOF as normal... */
byte[] digest = md.digest();

Use DigestUtils from Apache Commons Codec library:
FileInputStream fis = new FileInputStream(new File("foo"));
String md5 = org.apache.commons.codec.digest.DigestUtils.md5Hex(fis);

Don't want to miss updates? Please click the below button!

Follow MindStick