How to generate a file checksum value in Java

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 :

About the Author

mkyong
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 make a donation to these charities.

Comments

  • Pingback: water ionizers()

  • Pingback: alkaline water benefits()

  • Pingback: laan penge her og nu()

  • Pingback: parking()

  • Pingback: xnxx()

  • Pingback: DIRECTV()

  • Pingback: tv packages()

  • Pingback: DIRECTV packages()

  • Pingback: Direct TV vs Dish TV()

  • Pingback: best online casinos()

  • Pingback: unblock sites in Saudi Arabia()

  • Pingback: alkaline water()

  • Pingback: stream movies()

  • Pingback: watch movies online free()

  • Pingback: Blue Coaster33()

  • KINGSLEY

    i have been asked to produce a software which demands a person to enter either a text,file etc and produces in return hex from a sha 224 and 512 hash.i would love to do it in java but not only don’t i know how to call a file in a java program and i don’t how to go about writing the sha 224 and 512 programs.please help me

  • Shashant

    Nice post,
    Worked well for txt files.
    Can I find SHA-1 checksum for a encrypted pgp file or a zip file?

    Thanks,
    Shashant

  • Christian

    Great work. Thank you!

  • Dawin

    I got java.lang.ArrayIndexOutOfBoundsException when I use this method in my code. I wonder why? It stopped when the current seq.No=977 in int

    byte[] seqNoinbytes=new byte[4];
                    seqNoinbytes=ByteBuffer.allocate(4).putInt(seqNo).array();
                    System.out.println(&quot;Sequence number= &quot;+seqNo);
                    for(int i=0;i&lt;4;i++){        
                        out_data[i]=seqNoinbytes[i];
                        System.out.println(&quot;Error after this, seqNoinbytes= &quot;+(char)seqNoinbytes[i]);
                        md.update(out_data, 0, seqNoinbytes[i]); //problem here
                    }
    • Dawin

      Basically the seqNoinbytes[i] in md.update has value -47. I wonder how I can use this with a 4-bytes seq.No with value 977, and probably the other numbers.

  • anon

    Why are you adding 0x100?
    If you simple use Integer.toString((byte & 0xFF), 16) you would get the same result.

    • mkyong

      hi anon, thanks for the tips ~

    • rushman

      Adding 0x100 to the number and converting it to String will preserve leading zeroes. That’s why substring(1) is needed to truncate the “hundreds”.
      The result looks prettier, nothing else.

      Example:

      b + 0 = b –toString–> “b”
      b + 100 = 10b –toString–> “10b” –substring–> “0b”

  • http://www.google.com/m/url?cd=1&client=safari&ct=res&ei=tGnMSuCmPIKIgAfqtthl&hl=en&oe=UTF-8&oi=blended&q=http%3A%2F%2Fjava.sun.com%2Fj2se%2F1.4.2%2Fdocs%2Fapi%2Fjava%2Futi Interesting

    Interesting approach, how does it compare to using the CheckedInputStream?

    • mkyong

      i never use CheckedInputStream before, would you mind to share your experience ?

      • Interesting

        It works well: javadoc
        Example (identical to readying any stream):

        try
        {
        // Compute Adler-32 checksum
        CheckedInputStream cis = new CheckedInputStream(new FileInputStream("filename"), new Adler32());
        byte[] tempBuf = new byte[128];
        while (cis.read(tempBuf) >= 0){}
        long checksum = cis.getChecksum().getValue();
        } catch (IOException e) {
        }

  • Charlie Hayes

    You might consider using Adler32 instead of SHA1. It’s a whole lot faster. That is of-course unless you are using the checksum as some sort of identifier for the file, in which case the size of SHA1’s hash might be helpful.

    http://java.sun.com/j2se/1.4.2/docs/api/java/util/zip/Adler32.html
    http://www.anomalousanomaly.com/docs/CheckMark%20Results.pdf

    • mkyong

      Thanks for the suggestion and links provided. I always SHA-1 to generate the checksum value for the file, will look into the Adler32~

  • http://www.geeks.ltd.uk/ software development company

    Nice post,

    exclent approch, I used the code and It worked fine

    Thanks for bringing this up