Cipher Streams
In the Cipher
class we just examined, we had to
provide the data to be encrypted or decrypted as multiple blocks of
data. This is not necessarily the best interface for programmers:
what if we want to send and receive arbitrary streams of data over
the network? It would often be inconvenient to get all the data into
buffers before it can be encrypted or decrypted.
The solution to this problem is the ability to associate a cipher object with an input or output stream. When data is written to such an output stream, it is automatically encrypted, and when data is read from such an input stream, it is automatically decrypted. This allows a developer to use Java’s normal semantics of nested filter streams to send and receive encrypted data.
The CipherOutputStream Class
The class that encrypts data on output to a stream is the
CipherOutputStream
class
(javax.crypto.CipherOutputStream
):
- public class CipherOutputStream extends FilterOutputStream
Provide a class that will encrypt data as it is written to the underlying stream.
Like all classes that extend the
FilterOutputStream
class, constructing a cipher
output stream requires that an existing output stream has already
been created. This allows us to use the existing output stream from a
socket or a file as the destination stream for the encrypted data:
- public CipherOutputStream(OutputStream outputStream, Cipher cipher)
Create a cipher output stream, associating the given cipher object with the existing output stream. The ...
Get Java Security 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.