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 ...
Get Java I/O 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.