O'Reilly logo

Core Java® Volume II—Advanced Features, Ninth Edition by Gary Cornell, Cay S. Horstmann

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

9.7.3. Cipher Streams

The JCE library provides a convenient set of stream classes that automatically encrypt or decrypt stream data. For example, here is how you can encrypt data to a file:

Cipher cipher = . . .; cipher.init(Cipher.ENCRYPT_MODE, key); CipherOutputStream out = new CipherOutputStream(new FileOutputStream(outputFileName), cipher); byte[] bytes = new byte[BLOCKSIZE]; int inLength = getData(bytes); // get data from data source while (inLength != -1) {    out.write(bytes, 0, inLength);    inLength = getData(bytes); // get more data from data source } out.flush();

Similarly, you can use a CipherInputStream to read and decrypt data from a file:

Cipher cipher = . . .; cipher.init(Cipher.DECRYPT_MODE, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required