Message Digest Streams

The interface to the message digest class requires that you supply the data for the digest as a series of single bytes or byte arrays. As we mentioned earlier, this is not always the most convenient way to process data, which may be coming from a file or other input stream. This brings us to the message digest stream classes. These classes implement the standard input and output filter stream semantics of Java streams so that data can be written to a digest stream that will calculate the digest as the data itself is written (or the reverse operation for reading data).

The DigestOutputStream Class

The first of these classes we’ll examine is the DigestOutputStream class (java.security.DigestOutputStream). This class allows us to write data to a particular output stream and calculate the message digest of that data transparently as the data passes through the stream:

public class DigestOutputStream extends FilterOutputStream

Provide a stream that can calculate the message digest of data that is passed through the stream. A digest output stream holds two components internally: the output stream that is the ultimate destination of the data, and a message digest object that computes the data of the stream written to the destination.

The digest output stream is constructed as follows:

public DigestOutputStream(OutputStream os, MessageDigest md)

Construct a digest output stream that associates the given output stream with the given message digest. Data that is written ...

Get Java Security now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.