I am looking to use java to get the md5 checksum of a file.
I was really surprised but I haven't been able to find anything that shows how (and the best way) to get the md5 checksum of a file.
Any ideas on how to go forward?
Thanks.
I am looking to use java to get the md5 checksum of a file.
I was really surprised but I haven't been able to find anything that shows how (and the best way) to get the md5 checksum of a file.
Any ideas on how to go forward?
Thanks.
There's an example at Real's Java-How-to using the MessageDigest class.
I'd post the code here, but it's a bit longish, and I don't think Real's going anywhere.
Maybe this will help. You could also look up the spec but that would take more doing as it's complicated.
There's an input stream decorator, java.security.DigestInputStream
, so that you can compute the digest while using the input stream as you normally would, instead of having to make an extra pass over the data.
MessageDigest md = MessageDigest.getInstance("MD5");
InputStream is = new FileInputStream("file.txt");
try {
is = new DigestInputStream(is, md);
// read stream to EOF as normal...
}
finally {
is.close();
}
byte[] digest = md.digest();
I recently had to do this for just a dynamic string, MessageDigest can represent the hash in numerous way's. To get the signature of the file like you would get with the md5sum command I had to do something like the this:
try {
String s = "TEST STRING";
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(s.getBytes(),0,s.length());
String signature = new BigInteger(1,md5.digest()).toString(16);
System.out.println("Signature: "+signature);
} catch (final NoSuchAlgorithmException e) {
e.printStackTrace();
}
This obviously doesn't answer your question about how to do it specifically for a file, the above answer deals with that quiet nicely. I just spent a lot of time getting the sum to look like most application's display it, and thought you might run into the same trouble.
Good Luck, Brian G
Write a program that creates an MD5 message digest, read a massage from a file (MD.txt) and displays the that massage digest it in another file (MDout.txt)
Use the Apache Commons Codec lib:
http://commons.apache.org/codec/
FileInputStream fis = new FileInputStream( new File("foo" ) );
String md5 = org.apache.commons.codec.digest.DigestUtils.md5Hex( fis );
If you're using ANT to build, this is dead-simple. Add the following to your build.xml:
<checksum file="${jarFile}" todir="${toDir}"/>
Where jarFile is the JAR you want to generate the MD5 against, and toDir is the directory you want to place the MD5 file.
public static String MD5Hash(String toHash) throws RuntimeException {
try{
return String.format("%032x", // produces lower case 32 char wide hexa left-padded with 0
new BigInteger(1, // handles large POSITIVE numbers
MessageDigest.getInstance("MD5").digest(toHash.getBytes())));
}
catch (NoSuchAlgorithmException e) {
// do whatever seems relevant
}
}