Monday, December 6, 2010

MD5 example in Java


Both Linux and Windows have tools to compute the MD5 (Message Digest algorithm 5) hash value of a file.

In Linux, run
        md5sum <file_name>
       
In Windows, run
        fciv.exe <file_name>
       
If the tools are not installed, it is very easy to build your own one in Java. Just create a new text file named Md5.java and copy&paste the following code into it.

import java.security.MessageDigest;
import java.io.FileInputStream;
import java.math.BigInteger;

public class Md5 {
   public static void main(String[] args) {
      if (args.length < 1)
      {
         System.out.println("Syntax: java Md5 <file_name>");
         return;
      }

      try {
         // Create a message digest with MD5 algorithm.
         MessageDigest md = MessageDigest.getInstance("MD5");

         // Read the file and update the digest.
         FileInputStream fis = new FileInputStream(args[0]);

         byte[] buf = new byte[1024];
         int n = 0;
         while ((n = fis.read(buf)) != -1) {
            md.update(buf, 0, n);
         };

         fis.close();
 
         // Complete the hash computation. And return it as a BigInteger.
         BigInteger i = new BigInteger(1, md.digest());

         // Output the result.
         String s = String.format("%1$032x", i);
         System.out.println(s);
      }
      catch (Exception x) {
         System.out.println("Error:");
         x.printStackTrace();
      }
   }
}

Save the file and compile it
        javac Md5.java
       
Run it like this
        java Md5 <file_name>

No comments:

 
Get This <