/** * Returns the checksum (also referred to as <i>hash</i> or <i>digest</i>) of the given <code>InputStream</code> * calculated by reading the stream and feeding the bytes to the given <code>MessageDigest</code> until EOF is * reached. * * <p><b>Important:</b> this method does not close the <code>InputStream</code>, and does not reset the * <code>MessageDigest</code> after the checksum has been calculated.</p> * * @param in the InputStream for which to calculate the checksum * @param messageDigest the MessageDigest to use for calculating the checksum * @return the given InputStream's checksum, as an hexadecimal string * @throws IOException if an I/O error occurred while calculating the checksum */ public static String calculateChecksum(InputStream in, MessageDigest messageDigest) throws IOException { ChecksumInputStream cin = new ChecksumInputStream(in, messageDigest); try { StreamUtils.readUntilEOF(cin); return cin.getChecksumString(); } catch(IOException e) { throw new FileTransferException(FileTransferError.READING_SOURCE); } }
origFileStream.close(); } else { sourceChecksum = ((ChecksumInputStream)origFileStream).getChecksumString();
sourceChecksum = ((ChecksumInputStream)in).getChecksumString();
/** * Creates a regular file and fills it with <code>length</code> random bytes, overwriting the file if it exists, * and returns the md5 checksum of the random data that was copied. * <p> * Before returning, this method asserts that the file {@link AbstractFile#exists() exists} and that its * {@link AbstractFile#getSize() size} matches the specified length argument. * </p> * * @param file the file to create or overwrite * @param length the number of random bytes to fill the file with * @return the md5 checksum of the data written to the file * @throws IOException if the file already exists or if an error occurred while writing to it * @throws NoSuchAlgorithmException should not happen */ protected String createFile(AbstractFile file, long length) throws IOException, NoSuchAlgorithmException { ChecksumInputStream md5In = new ChecksumInputStream(new BoundedInputStream(new RandomGeneratorInputStream(), length, false), MessageDigest.getInstance("md5")); file.copyStream(md5In, false, length); assert file.exists(); assert length == file.getSize(); return md5In.getChecksumString(); }