23.07.2013 Views

Java IO.pdf - Nguyen Dang Binh

Java IO.pdf - Nguyen Dang Binh

Java IO.pdf - Nguyen Dang Binh

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Figure 10.2. Encrypting data<br />

<strong>Java</strong> I/O<br />

Example 10.6 is a simple program that reads a filename and a password from the command<br />

line and encrypts the file with DES. The key is generated from the bytes of the password in a<br />

fairly predictable and insecure fashion. The cipher is initialized for encryption with the DES<br />

algorithm in CBC mode with PKCS5Padding and a random initialization vector. The<br />

initialization vector and its length are written at the start of the encrypted file so they'll be<br />

conveniently available for decryption.<br />

Data is read from the file in 64-byte blocks. This happens to be an integral multiple of the<br />

eight-byte block size used by DES, but that's not necessary. The Cipher object buffers as<br />

necessary to handle nonintegral multiples of the block size. Each block of data is fed into the<br />

update() method to be encrypted. update() returns either encrypted data or null if it<br />

doesn't have enough data to fill out a block. If it returns the encrypted data, that's written into<br />

the output file. When no more input data remains, the cipher's doFinal() method is invoked<br />

to pad and flush any remaining data. Then both input and output files are closed.<br />

Example 10.6. FileEncryptor<br />

import java.io.*;<br />

import java.security.*;<br />

217

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!