Java examples for Security:MD5
Compute the md5 hash of a File.
//package com.java2s; import java.io.IOException; import java.io.InputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class Main { /**/*w ww . j a va2s .co m*/ * Compute the md5 hash of a File. In case of errors, returns a zero * length array (file not existent, not readable, ...), also takes care * of closing the InputStream * * @param fis * the input stream to be hashed * @return a 32-character hexadecimal number * @throws IOException * when InputStream can't be read properly */ private static byte[] md5AsBytes(final InputStream fis) throws IOException { MessageDigest complete; try { complete = computeMd5MessageDigest(fis); } catch (NoSuchAlgorithmException ex) { throw new UnsupportedOperationException(ex); } finally { try { if (fis != null) { fis.close(); } } catch (IOException ex) { return new byte[0]; } } return complete.digest(); } /** * Compute the md5 hash of a InputStream. * * @param fis * the InputStream * @throws IOException * when there are problems reading the stream * @throws NoSuchAlgorithmException * should not bother to catch this exception * @return a MessageDigest */ private static MessageDigest computeMd5MessageDigest( final InputStream fis) throws IOException, NoSuchAlgorithmException { int numRead; final int chunk = 1024; MessageDigest complete = MessageDigest.getInstance("MD5"); byte[] buffer = new byte[chunk]; do { numRead = fis.read(buffer, 0, chunk); if (numRead > 0) { complete.update(buffer, 0, numRead); } } while (numRead != -1); return complete; } }