carlspring carlspring - 1 year ago 46
Java Question

Calculate multiple checksums from the same InputStream using DigestInputStream

I am trying to figure out how to read multiple digests (md5, sha1, gpg) based on the same

. From what I've checked in the documentation, it seems to be possible by cloning the digest. Could somebody please illustrate this?

I don't want to be re-reading the stream in order to calculate the checksums.

Answer Source

You could wrap a DigestInputStream around a DigestInputStream and so on recursively:

DigestInputStream shaStream = new DigestInputStream(
    inStream, MessageDigest.getInstance("SHA-1"));
DigestInputStream md5Stream = new DigestInputStream(
    shaStream, MessageDigest.getInstance("MD5"));
// VERY IMPORTANT: read from final stream since it's FilterInputStream
byte[] shaDigest = shaStream.getDigest().digest();
byte[] md5Digest = md5Stream.getDigest().digest();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download