HOW CAN I GENERATE AN MD5 HASH?

Nigel Bunyan

Total Post:20

Points:140
Posted by  Nigel Bunyan
Java 
 778  View(s)
Ratings:
Rate this:
Is there any method to generate MD5 hash of a string in Java?
  1. Mayank Tripathi

    Post:397

    Points:3117
    Re: How can I generate an MD5 hash?

    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);
    fis.close() 

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!