Here's another one. This one will be in several parts. The eventual goal is to construct a class that will encrypt plaintext using monoalphabetic substitution. This isn't particularly difficult but it does involve a bit of text manipulation so it's kind of fun and gives us a chance to look at some different ways we can construct some simple algorithms.
First let's get a little bit of background. Monoalphabetic substitution simply means swapping one letter with another. The way we do this is to construct a cipher, using each of the 26 letters of the english alphabet in this case, and line it up against another alphabet (I'll use the regualr one for now) and simply substitute our plaintext to get our ciphertext.
Here's an example given that we already have a cipher "qrskoweipltuyaczmnvdhfgxjb". Let's say we want to encrypt the words "java" and "ranch".
<pre>
P: abcdefghijklmnopqrstuvwxyz
-----------------------------
C: qrskoweipltuyaczmnvdhfgxjb
</pre>
"java ranch" encrypts to
"lqfq nqasi"
Okay pretty simple stuff. I'll get more into the details as we move along. The first thing we need to do is to create a good cipher. There are a few steps we need to accomplish in order to do this. To produce a cipher alphabet you have to 1) apply a key, 2) apply a hat, and 3) apply an offset. We'll talk about applying the hat and offset at a later date. For now let's talk about applying a key.
A key is simply a
word that you apply to your alphabet in order to affect it's order. The key, minus any duplicate letters in the key is inserted at the beginning of the alphabet, and any letter contained in the key is removed from the alphabet. So after applying a key, you are left with an alphabet that contains the 26 unique letters, but in a slightly different order.
To produce a cipher with a key of "java"
1. Truncate the key by removing duplicate letters from it. If our key is "java", our truncated key is
jav
2. Remove the letters in our truncated key from the alphabet. This would leave us with a 23 letter alphabet like this:
bcdefghiklmnopqrstuwxyz
3. Make our cipher by inserting the truncated key at the beginning of the our truncated alphabet. This gives us the cipher:
javbcdefghiklmnopqrstuwxyz
Here is a skeleton of a class that we can build on as we go. All we will do for now is write the applyKey() method, following the steps outlined above. I also added a few get and set methods (not all of them yet) as well as putting in the hooks for time
testing in the main method, although applyKey() will probably run quick enough that your time will be 0 at this stage.
[ September 13, 2002: Message edited by: Jason Menard ]