Cipher Streams
The Cipher
class is the engine that powers encryption. Chapter 10 and Example 10.7 showed how
this class could be used to encrypt and decrypt data read from a
stream. The javax.crypto package also provides
CipherInputStream and
CipherOutputStream filter streams that use a
Cipher object to encrypt or decrypt data passed
through the stream. Like DigestInputStream and
DigestOutputStream, they aren’t a great deal
of use in themselves. However, you can chain them in the middle of
several other streams. For example, if you chain a
GZIPOutputStream to a
CipherOutputStream that is chained to a
FileOutputStream, you can compress, encrypt and
write to a file, all with a single call to
write(). This is shown in Figure 10.3. Similarly, you might read from a URL with the
input stream returned by openStream(), decrypt the
data read with a CipherInputStream, then check the
decrypted data with a MessageDigestInputStream,
then finally pass it all into an InputStreamReader
for conversion from ISO Latin-1 to Unicode. On the other side of the
connection, a web server could read a file from its hard drive, write
the file onto a socket with an output stream, calculate a digest with
a DigestOutputStream, and encrypt the file with a
CipherOutputStream.

Figure 10-3. The CipherOutputStream in the middle of a chain of filters
CipherInputStream
CipherInputStream is a subclass of
FilterInputStream ...
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