Calculate MD5 for a Stream

 
import java.io.InputStream;
import java.security.DigestInputStream;
import java.security.MessageDigest;

public class Main {
  public static String computeMD5(InputStream stream) {
    MessageDigest digest;
    try {
      digest = MessageDigest.getInstance("MD5");

      DigestInputStream digestStream = new DigestInputStream(stream, digest);
      while (digestStream.read() != -1) {
        ; // digest is updating
      }
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
    byte[] digestBytes = digest.digest();

    StringBuffer hexString = new StringBuffer();
    for (byte digestByte : digestBytes) {
      hexString.append(Integer.toHexString(0xFF & digestByte));
    }
    return hexString.toString();
  }

}
  
Home 
  Java Book 
    Runnable examples  

Security:
  1. Calculate checksums for a range of bytes.
  2. Calculate MD5 for a String
  3. Calculate MD5 for a Stream