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 and copy&paste the following code into it.

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>");

      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 = != -1) {
            md.update(buf, 0, n);

         // 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);
      catch (Exception x) {

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

No comments:

Get This <