previous | start | next

File Encryptor.java

1 import java.io.File;
2 import java.io.FileInputStream;
3 import java.io.FileOutputStream;
4 import java.io.InputStream;
5 import java.io.OutputStream;
6 import java.io.IOException;
7
8 /**
9     An encryptor encrypts files using the Caesar cipher.
10     For decryption, use an encryptor whose key is the 
11     negative of the encryption key.
12 */
13 public class Encryptor
14 {
15    /**
16        Constructs an encryptor.
17       @param aKey the encryption key
18     */
19    public Encryptor(int aKey)
20    {
21       key = aKey;
22    }
23
24    /**
25        Encrypts the contents of a file.
26       @param inFile the input file
27       @param outFile the output file
28     */
29    public void encryptFile(File inFile, File outFile)
30       throws IOException
31    {
32       InputStream in = null;
33       OutputStream out = null;
34
35       try
36       {
37          in = new FileInputStream(inFile);
38          out = new FileOutputStream(outFile);
39          encryptStream(in, out);
40       }
41       finally
42       {
43          if (in != null) in.close();
44          if (out != null) out.close();
45       }      
46    }
47
48    /**
49        Encrypts the contents of a stream.
50       @param in the input stream
51       @param out the output stream
52     */      
53    public void encryptStream(InputStream in, OutputStream out)
54       throws IOException
55    {
56       boolean done = false;
57       while (!done)
58       {
59          int next = in.read();
60          if (next == -1) done = true;
61          else
62          {
63             byte b = (byte)next;
64             byte c = encrypt(b);
65             out.write(c);
66          }
67       }
68    }
69
70    /**
71        Encrypts a byte.
72       @param b the byte to encrypt
73       @return the encrypted byte
74     */
75    public byte encrypt(byte b)
76    {
77       return (byte)(b + key);
78    }
79
80    private int key;
81 }


previous | start | next