Saturday, February 12, 2011

The Caesar Cipher

I decided to start with the Caesar cipher for my first tutorial. It is relatively simple and contains some important concepts in cryptography. It also has some rich history behind it. I will include a programming algorithm for it at the end, in Java, if the reader is interested.


It is named after Julius Caesar who used it to encrypt messages of military and personal significance. Cryptography was not in wide use, or even known to exist, in this era, so it was very effective despite it's very simple implementation. The majority of his enemies would have also been illiterate.

How It Works

The Caesar cipher works by shifting the letters of the alphabet. For example, A would become D, and B would become E. It is not a safe encryption system and can be broken relatively easily. If you use this to hide value information, it won't be hidden for long. A very popular use of the Caesar cipher is ROT13, which stands for Rotational 13. ROT13 works by shifting each letter of the alphabet by 13 places.


The message "Cryptomathematics is awesome" becomes: "Pelcgbzngurzngvpf vf njrfbzr"

The shift can also be represented mathematically as:

E(x) = (x + n) mod 26

Where x is being shifted and n is the value to shift by. Decryption is performed similarly:

D(x) = (x + n) mod 26

The modular operator keeps it in a discrete structure, so that if you add a shift that takes you out of the range fo the alphabet, you stay inside. It's basically a loop. Since the alphabet is 26 characters long, we use mod 26. I've always found it interesting that modular arithmetic is very important to advanced mathematics, particularly number theory and cryptography, yet people use this all day. We use this system for time! Think of a clock. You don't say it is 13 o'clock (we're not using military time here), you say 1 o'clock. A clock would be represented the same way mathematically if you wanted to see what time it would be in, say, 5 hours, except you would use mod 12.

If you wish to learn more about modular arithmetic, go here.

Anyways, I promised a programming algorithm and I shall deliver.

String encodedMessage = "";
for (int i = 0; i < plainText.length(); i++) {
char c = plainText.charAt(i);
if (c >= 'a' && c <= 'm'){
c += 13;
} else if (c >= 'n' && c <= 'z'){
c -= 13;
} else if (c >= 'A' && c <= 'M'){
c += 13;
} else if (c >= 'N' && c <= 'Z'){
c -= 13;
encodedMessage += c;

I've seen a lot of algorithms for the ROT13 cipher and Java is definitely not the most elegant, but Java is what I'm learning. And since you're rotating by 13 characters (26/2 = 13) you can use the same piece of code to decode the encoded message.

If anyone knows how to embed code on here, I'd be grateful if you told me how!

No comments:

Post a Comment