Here is a simple example to demonstrate how to generate a file checksum value with “SHA-1” mechanism in Java.

import java.io.FileInputStream;
import java.security.MessageDigest;
 
public class TestCheckSum {
 
  public static void main(String args[]) throws Exception {
 
    String datafile = "c:\\INSTLOG.TXT";
 
    MessageDigest md = MessageDigest.getInstance("SHA1");
    FileInputStream fis = new FileInputStream(datafile);
    byte[] dataBytes = new byte[1024];
 
    int nread = 0; 
 
    while ((nread = fis.read(dataBytes)) != -1) {
      md.update(dataBytes, 0, nread);
    };
 
    byte[] mdbytes = md.digest();
 
    //convert the byte to hex format
    StringBuffer sb = new StringBuffer("");
    for (int i = 0; i < mdbytes.length; i++) {
    	sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
    }
 
    System.out.println("Digest(in hex format):: " + sb.toString());
 
  }
}

Result

Digest(in hex format):: bf35fa420d3e0f669e27b337062bf19f510480d4

The “INSTLOG.TXT” file has a “bf35fa420d3e0f669e27b337062bf19f510480d4″ SHA-1 checksum value.

For checksum value in MD5 format , you need to change the MessageDigest :

MessageDigest md = MessageDigest.getInstance("MD5");

More detail about Message Digest Algorithms

Reference

Tags :
Founder of Mkyong.com and HostingCompass.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider making a donation to this charity, thanks.

Related Posts

Popular Posts