The Caesarian Cipher

A Caesarian Cipher is one of the simplest, weakest forms of encryption. Supposedly developed by Julius Caesar, it’s a letter substitution cipher: A becomes C, B becomes D, C becomes E, and so on.

In the kingdom of computers, the Caesarian Cipher was popular in the early days of the Internet using a routine called rot13.

To disguise spoiler information, or the punchline of a joke, text was run through the rot13 filter. So you might have seen a USENET message like this:

Q: Why did the chicken cross the road?

A: Gb trg gb gur bgure fvqr!

Running that text through a rot13 filter yields the result:

D: Jul qvq gur puvpxra pebff gur ebnq?

N: To get to the other side!

The rot13 filter shifted the letters 13 places: A to M became N to Z. That way you could run the filter once to encrypt and again to decrypt.

rot13 was so popular that many email programs and message readers offered it as a command. Here’s the I/O filter version of the rot13 code I wrote for my machine:

#include <stdio.h>
#include <ctype.h>

int main()
{
   int ch;

   while(1)
   {
        ch = fgetc(stdin);
        if(ch == EOF) break;
        if(isalpha(ch))
        {
            if(toupper(ch)>='A' && toupper(ch)<='M')
              ch+=13;
            else
              ch-=13;
        }
        fputc(ch,stdout);
   }
   return(0);
}

Like any filter, the code reads standard input one character at a time, using fgetc() at Line 10. It modifies the input at Lines 11 through 18. And finally sends the character to standard output with fputc() at Line 19.

The modification involves pulling out letters of the alphabet with isalpha() at Line 12. Line 14 checks to see whether the alpha character is in the range A to M, either upper or lower case. If so, it's rotated up at Line 15, otherwise it's rotated down at Line 17. And, as always, this code is merely one way of solving the problem.

But there's another problem!

My rot13 example is hard-coded as a 13 character shift. It's not a true Caesarian Cipher, which can start at any letter. Caesar is said to have used the A-to-C shift. But what about an A-to-G or A-to-R shift? Those are all Caesarian Ciphers.

Your exercise for August is to create a true Caesarian Cipher I/O filter, one that shifts input a given number of letters in the alphabet. In this exercise, set the shift to a constant value; you don't have to code the shift as a variable. Further, you need only code an encryption filter, not one that both encrypts and decrypts, which would probably need to be a separate filter program in any case.

As usual, please attempt to solve the puzzle before you click the link below to view my solution. Also, keep in mind that my solution is one of many.

Exercise Solution

Leave a Reply