O'Reilly logo

Java I/O by Elliotte Rusty Harold

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 .

DigestInputStream

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"); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required