Java: Calculate MD5 checksum








package examples;

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

public class MD5CSUM {

 public static final int BUFFER_SIZE = 2048;

 public static byte[] getMD5(InputStream in) throws Throwable {
  MessageDigest md = MessageDigest.getInstance("MD5");
  try {
   DigestInputStream dis = new DigestInputStream(in, md);
   byte[] buffer = new byte[BUFFER_SIZE];
   while (dis.read(buffer)!=-1){
    // 
   }
   dis.close();
  } finally {
   in.close();
  }
  return md.digest();
 }

 public static void main(String[] args) throws Throwable {
  File f = new File("/tmp/1.iso.gz");
  byte[] csum = getMD5(new FileInputStream(f));
  StringBuilder sb = new StringBuilder();
  for (int i = 0; i < csum.length; i++) {
   sb.append(String.format("%x", csum[i]));
  }
  System.out.println(sb.toString());
 }

}

See also




No comments:

Post a Comment