1 import java.io.InputStream;
2 import java.io.OutputStream;
3 import java.io.IOException;
4
5 /**
6 This class encrypts files using the Caesar cipher.
7 For decryption, use an encryptor whose key is the
8 negative of the encryption key.
9 */
10 public class CaesarCipher
11 {
12 private int key;
13
14 /**
15 Constructs a cipher object with a given key.
16 @param aKey the encryption key
17 */
18 public CaesarCipher(int aKey)
19 {
20 key = aKey;
21 }
22
23 /**
24 Encrypts the contents of a stream.
25 @param in the input stream
26 @param out the output stream
27 */
28 public void encryptStream(InputStream in, OutputStream out)
29 throws IOException
30 {
31 boolean done = false;
32 while (!done)
33 {
34 int next = in.read();
35 if (next == -1) done = true;
36 else
37 {
38 byte b = (byte) next;
39 byte c = encrypt(b);
40 out.write(c);
41 }
42 }
43 }
44
45 /**
46 Encrypts a byte.
47 @param b the byte to encrypt
48 @return the encrypted byte
49 */
50 public byte encrypt(byte b)
51 {
52 return (byte) (b + key);
53 }
54 }