Java MessageDigestCalculatingInputStream-class And Method Code Example


Here is an example of how to use the MessageDigestCalculatingInputStream class from the Apache Commons IO library in Java:

import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.apache.commons.io.input.MessageDigestCalculatingInputStream;

class Example {
    public static void main(String[] args) {
        try (MessageDigestCalculatingInputStream mdInputStream = 
                new MessageDigestCalculatingInputStream(MessageDigest.getInstance("MD5"), new FileInputStream("file.txt"))) {
            byte[] buffer = new byte[1024];
            while (mdInputStream.read(buffer) != -1) {
                // do something with the read data
            }
            byte[] md5 = mdInputStream.getMessageDigest().digest();
            // do something with the digest
        } catch (NoSuchAlgorithmException | IOException e) {
            // handle exception
        }
    }
}

This code creates a MessageDigestCalculatingInputStream which wraps a FileInputStream for the file "file.txt". It then reads data from the file using the read method and the MessageDigestCalculatingInputStream accumulates the digest using the specified algorithm (in this case MD5).

Finally, it retrieve the digest using the getMessageDigest() method, and calls the digest() method to get the computed digest.

The MessageDigestCalculatingInputStream provides a way to calculate a message digest (hash) of the data read from an input stream, it wraps an existing input stream and updates the digest as the data is read.