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"); ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access