Digest Streams

The MessageDigest class isn’t particularly hard to use, as I hope Example 10.1 and Example 10.2 demonstrated. It’s flexible and can be used to calculate a digest for anything that can be converted into a byte array, such as a string, an array of floating point numbers, or the contents of a text area. Nonetheless, the input data almost always comes from streams. Therefore, the java.security package contains an input stream and an output stream class that each possess a MessageDigest object to calculate a digest for the stream as it is read or written. These are DigestInputStream and DigestOutputStream .


The DigestInputStream class is a subclass of FilterInputStream :

public class DigestInputStream extends FilterInputStream

DigestInputStream has all the usual methods of any input stream, like read(), skip(), and close(). It overrides two read() methods to do its filtering. Clients use these methods exactly as they use the read() methods of other input streams:

public int read() throws IOException
public int read(byte[] data, int offset, int length) throws IOException

DigestInputStream does not change the data it reads in any way. However, as each byte or group of bytes is read, it is fed as input to a MessageDigest object stored in the class as the protected digest field:

protected MessageDigest digest;

The digest field is normally set in the constructor:

public DigestInputStream(InputStream stream, MessageDigest digest)

For example:

URL u = new URL("http://java.sun.com"); ...

Get Java I/O now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.