Thursday, June 27, 2013

How to get the checksum or hash value of a file in JAVA

This is the convenience method that I use in getting the hash value of a file.


The getChecksum() method

 public static String getChecksum(String filename, String algo) throws Exception {  
      byte[] b = createChecksum(filename, algo);  
      String result = "";  
      for (int i=0; i < b.length; i++) {  
           result +=  
                     Integer.toString( ( b[i] & 0xff ) + 0x100, 16).substring( 1 );  
      }  
      return result;  
 }  


The createChecksum() method

 public static byte[] createChecksum(String filename, String algo) throws Exception{  
      InputStream fis = new FileInputStream(filename);  
      byte[] buffer = new byte[1024];  
      MessageDigest complete = MessageDigest.getInstance(algo); //One of the following "SHA-1", "SHA-256", "SHA-384", and "SHA-512"  
      int numRead;  
      do {  
           numRead = fis.read(buffer);  
           if (numRead > 0) {  
                complete.update(buffer, 0, numRead);  
           }  
      } while (numRead != -1);  
      fis.close();  
      return complete.digest();  
 }  

You normally would place these two methods (getChecksum() and createChecksum()) in a separate class (e.g. your own FileUtil.java) and call it whenever you need it as follows:

 Public class MyClass{  
      public static void main(String[] args){  
           String path = "C:\hello.txt";  
           try{  
                String hash = FileUtil.getChecksum(path, "SHA1"); //or "SHA-256", "SHA-384", "SHA-512"  
                System.out.println(hash);  
           }catch(Exception e){  
                System.out.println("An error occured.");  
           }  
      }  
 }  


There you have it! A convenience method for retrieving a file hash value using JAVA. Feel free to post comments below!


Cheers! Happy coding! =)





No comments:

Post a Comment