Cipher’s Close Relatives

Cipher Streams

If you are able to encrypt or decrypt all of your data in one shot, then a call to doFinal() is all you need. In some cases, however, you need to encrypt data in pieces. For example, loading a large file into memory to encrypt it would not be practical.

The JCE offers two classes that worry about the details of encrypting or decrypting a stream of data. javax.crypto.CipherInputStream and javax.crypto.CipherOutputStream can be used to encrypt and decrypt data without thinking too hard. They are subclasses of the standard FilterInputStream and FilterOutputStream classes, so they work smoothly with the rest of the stream classes in the java.io package. You can construct one of these streams by specifying an underlying stream (as with all filtered streams) and an initialized Cipher object.[21]

The following example encrypts or decrypts an entire disk file. Like the SecretWriting application (in Chapter 1), it reads a private key from SecretKey.ser. If that file does not exist, Cloak creates a new key and saves it in a newly created file, SecretKey.ser. The input file is read using an ordinary FileInputStream. The file is encrypted or decrypted using a CipherOutputStream.

import java.io.*; import java.security.*; import javax.crypto.*; public class Cloak { public static final int kBufferSize = 8192; public static void main(String[] args) throws Exception { // Check arguments. if (args.length < 3) { System.out.println("Usage: Cloak -e|-d inputfile ...

Get Java Cryptography 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.