## CPSC 120 - Assignment #4

### Encryption and Decryption Due by 4 p.m. Friday, December 8, 2006

Security is a major concern in modern computing systems. Confidential information stored in computer databases and transmitted over computer networks needs to be protected from unauthorized access. The systems themselves must be restricted to authorized users. One of many means of ensuring such security is by encrypting data that is stored and transmitted by computers, and using encrypted passwords to limit access to systems. Encryption is the process of converting data (generally called a message) from its original form, called plaintext, into "scrambled" form, called ciphertext. The process of turning ciphertext back to plaintext is called decryption. A goal in systems security is to find encryption algorithms (called ciphers) that are relatively easy to compute but difficult to "reverse" (to break) without some knowledge of the decryption algorithm (especially the "key" needed to decrypt). Most modern algorithms rely heavily on number theory and use the fact that it is difficult to factor very large numbers (a few hundred digits long) in a reasonable length of time. Early algorithms, however, relied on much simpler ideas. One of the simplest algorithms is called the shift transformation or Caesar cipher (supposedly due to Julius Caesar). In this cipher each letter in the plaintext is replaced by the letter that is a fixed number of positions to the right (modulo 26 - that is, wraparound to the beginning of the alphabet occurs). In the original Caesar cipher, each letter was shifted 3 positions to the right. So an a in plaintext would become a d in ciphtertext, a c in plaintext would become an f, a y in plaintext would become a b, and z would become c.

In this assignment you will write a program with a graphical user interface that simulates sending encrypted messages across a network. Sending messages involves two parties that want to communicate, and a network (or a communications channel). Unfortunately, there is also the ocassional eavesdropper who wants to intercept the messages. Your program will have a GUI that looks something like this:

Notice that there are four distinct panels:one for each of the parties who want to exchange messages, one for the eavesdropper and one across the top that represents the network. Each of these panels will have a place for a message (we will use a text area instead of a textfield so there is more room for the message) and other components to let the user do things with the message. For example, the panels for the parties involved will have a button to let the user send the message in plaintext (unencrypted) and another to let the user send a message encrypted (in this case the user must also enter a shift for the encryption in a textfield). The panel representing the network will have a text area that a sent message is displayed in - if the message is sent encrypted the encrypted message will be displayed; otherwise the plaintext will be displayed. The eavesdropper panel will have components that let the user try to "break" the message using a technique called frequency analysis. For any substitution cipher, such as the Caesar cipher, where a given letter is always replaced by some fixed letter, the frequency of letters is not hidden by the cipher. Hence, the best way to try to break the ciphertext is to do a frequency analysis (count the number of instances of each letter in the ciphertext), then try substituting the most frequent letter in English for the most frequent letter in the cipher text. If that doesn't work, substitute the next most frequent letter in English for the most frequent letter in the ciphertext. Eventually you get a substitution that "breaks" the ciphertext. (Note: you can find the frequncy of letters in English by doing a search on the Web). Of course for a simple cipher you could use "brute force" - try all 26 letters until you find a substitution that works.

### Program Structure

It should be evident from the description above that each of these panels can be modeled using 3 distinct classes. Implement these classes using the following specifications:

The PartyPanel Class: This is the GUI representing a party wishing to send and receive messages. The class should have the following instance data:

• a String instance variable representing the name of the party. (i.e. the party that wants to send messages to someone else)
• a NetworkPanel instance variable representing the network the messages will be transmitted over
• an integer holding the shared key. Note: this variable should be shared across all instances of this class.
• instance variables representing the various components on the panel (note: some components on the panel can be local variables in the constructor rather than instance variables)
The class should provide the following methods:

• A constructor with two parameters - a String with the name of the party and a NetworkPanel object representing the network for communication. The constructor should use the parameters to initialize the corresponding instance variables.

The constructor will also set up the GUI. The GUI should have:

• a label with the user's name,
• a textfield to desginate the recipient of the message.
• a textarea for the user to enter a message.
• a button to send the message in plaintext,
• a button to encrypt the message and send it encrypted,
• a textfield for the shift needed to encrypt,
• appropriate labels letting the user know what to do.
To get a GUI that looks good, components should be organized on different subpanels (like the ATM from lab 10). Remember that any subpanels created should have a preferredSize and background color conisistent with the main panel. The constructor also needs to create a single listener object (for the listener class you add) and add the listener to each of the buttons.
• An encrypt method that takes a text string and returns the encrypted text. (See Programming Notes below for additional details)
• A decrypt method that takes a text string and returns the decrypted text.
• A method public void receiveMessage (String txt, boolean isEncrypted) that simulates receiving a message. If the message arrives encrypted, this method should decrypt it. The message should then be displayed in the textarea on the panel.
• Any appropriate accessors and getters. Take caution to only implement the ones that are compeletely necessary -- You don't want to make everything available, otherwise, it would be even easier for potential eavesdropers.

The class must also contain a nested listener class. The actionPerformed method of the listener should always get the string from the textarea and the intended recipient. If the button that triggered the event was the button to send the message as plaintext then an unencrypted message sould be sent to the network for processing. (Note: there will be a method in the NetworkPanel that handles this). If the "Send Encrypted" button is pushed, you need to encrypt the message and reset the encryption key before sending the message to the network for processing.

The HackerPanel Class: This is the GUI representing a eavesdropper wishing to intercept messages. The class should have the following instance data:

• a String instance variable representing the name of the eavesdropper that the object represents.
• a NetworkPanel instance variable representing the network the messages will be transmitted over
• a character used to store the most common character in the message.
• instance variables representing the various components on the panel (note: some components on the panel can be local variables in the constructor rather than instance variables)
The class should provide the following methods:

• A constructor with two parameters - a String with the name of the party and a NetworkPanel object representing the network for communication. The constructor should use the parameters to initialize the corresponding instance variables.

The constructor will also set up the GUI. The GUI should have:

• a label with the eavesdropper's name,
• a button to perform a frequency analysis,
• a label to show the most frequent letter.
• a textfield for the replacement letter,
• a button to attempt the decrypt the message using the replacement
• a textarea to display the hacked message.
• appropriate labels letting the user know what to do.
As with the PartyPanel, the GUI should be well organized using subpanels. background color of the hackerPanel should be different from the PartyPanel. The constructor also needs to create a single listener object (for the listener class you add) and add the listener to each of the buttons.
• public char getMostFrequentChar(String txt) This method should find and return the letter that occurs most often in txt. It might be helpful to write a private method to count the occurrences of a character in a string. Note: you should check both capital and lower case letters.
• a hack method that takes a string and attempts to decrypt it using the frequency information and the replacement letter suggested by the hacker. This method will be very very similar to the decrypt method in the partyPanel. The glaring difference is that this class does not have access to the key; a hypothetical key has to be calculated.

The class also must contain a nested listener class. The actionPerformed method of the listener should determine which button was pressed and take the appropriate actions.

The NetworkPanel Class:

The only instance variables in the NetworkPanel class are components needed in the GUI.

The class should provide the following methods:

• A constructor with no parameters that sets up the GUI. The GUI should have a label at the top, a textarea to display a message, and a subpanel containing the three members of the network (2 parties and a hacker).

Note: To get these components to "stack" on top of each other, make them all the same width (the width of the panel itself).

Note 2: The members of the network each maintain an instance variable referring to the network. This variable is required by the respective constructors. To pass a reference to the current network, you will need to use the this identifier.

• public void processMessage(String txt, String recipient, boolean isEncrypted) This method inserts the message (txt) into its own textarea, and then asks the recipient to recieve the message.
• an accessor, getMessage . This is how the Hacker is able to see the messages that are passed through the network.

The classes above are the main ones for the program but to fit all of everything together you need one more class (Crypto.java) with a main method that instantiates a frame and adds the network panel to the contentpane of the frame. The frame should also contain the title of the program, including your name.

### Programming Notes

Encryption and Decryption - Working with characters To shift the characters you can use the fact that characters are represented by a number in Unicode (See Appendix C for the Unicode character set). Casting a character to int gives the Unicode value of the character and casting an int to char gives the character with that Unicode value (assuming the int is in the correct range). So the shifting for encryption and decryption can be done with careful casting (and in some cases you don't need to cast - adding an int to a char gives a char). To get the wraparound (so that if you shift y by 5 you get d, for example) you need to use the remainder (%) operator. Note: In class, we discussed a how to accomplish this, but our solution involved a conditional. For this assignment, your solution should use a single expression.

Also for this program we will encrypt only letters. So your encrypt and decrypt methods should check to make sure the character is a letter. If it is a letter it should be encrypted (or decrypted) otherwise it shouldn't be. You should encrypt lowercase letters to be lowercase and uppercase letters to be uppercase. In lab 9 we used a method from the Character class to test to see if a character was a letter (and there are also methods to check for lowercase and uppercase). You can use those or use the fact that characters can be compared using the comparison operators <, <=, etc. So, an expression such as

```      ch >= 'a' && ch <= 'z'
```
is legal and would determine if the character is lowercase (see Unicode character set in Appendix C).

Finally, you should verify that that your encryption routines work for any positive key (not just 0-26).

Text Areas in Java: Text areas in Java are similar to textfields except there is a larger area for entering text. They are type JTextArea. To declare a text area you must specify the number of rows and number of columns in the constructor. For example,

```     JTextArea msgArea = new JTextArea (20, 30);
```
creates a text area that is 20 rows by 30 columns. For text areas it is nice to allow lines to wrap. This is accomplished using the setLineWrap method. For example,
```     msgArea.setLineWrap(true);
```
Another option is to put the textarea inside a scrollpane. For the textarea above this would be accomplished as follows:
```     JScrollPane sp = new JScrollPane (msgArea);
```
To put a string in a text area use the setText method that takes the string as a parameter (the same as the setText method for JTextFields). Similarly to get the string out of the text area use getText.

Implementation Suggestions: As usual you should implement this in steps. For example you could start by getting the GUI to look good for the PartyPanel class (without the code for the GUI to actually do anything). Once that is done get the GUI for the HackerPanelPanel class. Next you should implement the NetworkPanel class. Finally implement the listeners so the GUI actually responds to events.

Other Requirements: As usual use good programming practices that include appropriate naming of variables, correct indentation, and documentation that includes documentation at the beginning of every class describing that class, documentation at the beginning of every method that describes what that method does and what it returns (this documentation should be clearly delineated with rows of dashes or stars or something!), and internal documentation where necessary to explain what the code is doing.

Turn in: Printed copy of PartyPanel.java, HackerPanel.java NetworkPanel.java, and Crypto.java. Tar your project directory and send the tar file as an email attachment.

Academic Integrity Reminder: Programming assignments are to be your own work. You may get help on the specifics of the assignment from no one except the instructor. You may not show your program to anyone or look at anyone else's program or share ideas with anyone about how to write the program.

### Bonus

Consider this implementation version 1 of the software design cycle. For bonus credit you can propose and implement enhancements to the interface that would make this program operate better. Here are some ideas:
• Add a second textArea to the PartyPanel. The original textArea is used for typing messages and the new one is used for receiving messages.
• As above except that the new textarea tracks an entire conversation. i.e. messages sent and messages received. The message text should be prepended with the speaker so it is clear who is saying what.
• Add a status field so that the sender can know if his/her message went through. The network can return an update indicating "sent" or "unknown user"
• Add a third party to the network - be able to direct communication to a specific party or "broadcast" a message to each party in the network.
If you have other ideas, you can work on them too. Bonus credit will be awarded for proposing enhancements (other than the ones above) and clearly describing how they would affect the program's interaction. More credit will be awarded if you actually implement your proposed changes.

To get bonus credit, create a subdirectory called Version2, Copy your source files to this new directory and modify them Do not modify your original project files !! . Create a text file called Version2.txt that outlines your proposals and what you successfully implemented. Also include comments in your program that clearly designate any enhancements. Precede these comments with the line "//BONUS" so that I can easily find them.