The messagedigestforfile class demonstrates the generation of an md5w digest for a file. the MD5 Digest is displayed in hex using the hex class from the apachesw commonssw codec library. the call to messagedigest. getinstance ("MD5") specifies to use the MD5
Algorithm. Other common algorithms are md2 and Sha.
The getdigest () method of messagedigestforfile has three parameters. the first is the inputstream of the file that we're re going to read from. the second parameter is our messagedigest. the third parameter is the size of the byte array that we'll use to read
From the inputstream and update the messagedigest. the getdigest () method first resets the messagedigest to be sure that it is fresh. it reads the bytes of the file to update the messagedigest. we get the resulting Digest from the messagedigest and convert
This to a string that we return from the method.
MessageDigestForFile.javapackage test;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.io.InputStream;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;import org.apache.commons.codec.binary.Hex;public class MessageDigestForFile {public static void main(String[] args) throws NoSuchAlgorithmException, FileNotFoundException, IOException {String file = "httpd-2.2.6-win32-src-r2.zip";MessageDigest md = MessageDigest.getInstance("MD5");String digest = getDigest(new FileInputStream(file), md, 2048);System.out.println("MD5 Digest:" + digest);}public static String getDigest(InputStream is, MessageDigest md, int byteArraySize)throws NoSuchAlgorithmException, IOException {md.reset();byte[] bytes = new byte[byteArraySize];int numBytes;while ((numBytes = is.read(bytes)) != -1) {md.update(bytes, 0, numBytes);}byte[] digest = md.digest();String result = new String(Hex.encodeHex(digest));return result;}}
The execution of messagedigestforfile generates the following console output:
MD5 Digest: 301d61853fc9ce94bbfb55b56c218d06