How to generate a file checksum value in Java
Written on October 5, 2009 at 5:17 am by
mkyong
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
- http://www.itl.nist.gov/fipspubs/fip180-1.htm
- http://java.sun.com/j2se/1.4.2/docs/api/java/security/MessageDigest.html
- http://java.sun.com/j2se/1.4.2/docs/guide/security/CryptoSpec.html
This article was posted in Java category.
All Java Tutorials
- Java Core Technology - Java RegEx, Java XML, Java I/O, Java Misc
- J2EE Frameworks - Hibernate, Spring 2.5, Spring MVC, Struts 1.x, Struts 2.x
- Build Tools - Maven, Archiva
- Unit Test - jUnit, TestNG
- Client Scripts - jQuery
Why are you adding 0×100?
If you simple use Integer.toString((byte & 0xFF), 16) you would get the same result.
hi anon, thanks for the tips ~
Interesting approach, how does it compare to using the CheckedInputStream?
i never use CheckedInputStream before, would you mind to share your experience ?
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) {
}
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
Thanks for the suggestion and links provided. I always SHA-1 to generate the checksum value for the file, will look into the Adler32~
Nice post,
exclent approch, I used the code and It worked fine
Thanks for bringing this up