Maths and Computer Science Tutor Blog

A common question in GCSE Computer Science exams involves encoding or decoding a message using a Caesar Cipher. This is a simple device named after the famous Emperor who used it to encrypt military messages. It involves “shifting” each character in the original message (plaintext) by a fixed amount to create an encoded message (ciphertext).

Take a look at the image below:

Caesar Cipher for online GCSE Computer Science tuition

It represents a shift of 3 character (which is apparently the version Caesar himself used). So “A” becomes “D” and “H” becomes “K”, for example. If the shift puts the new value beyond the 26th position, it is “looped back” to the beginning, so that for example “Z” becomes “C” when shifted by 3 places.

The table below can be very helpful in determining the new position for a particular letter.

GCSE Computer Science online tuition - Caesar Cipher Key

To use it, you add the key (or “shift amount”) to each letter’s value and read off the new letter for the new value. If the new value is greater than 25, you subtract 26 beforehand.

Using this method, a plaintext message of “HELLO” with a shift of 3 becomes “KHOOR”.

Simple eh? The trouble is that because it is so simple, it is very easy to decipher messages encoded with this method. How would you go about deciphering a ciphertext message with an unknown key?

There are more secure ciphers, such as the Vigenère cipher which is based on the Caesar Cipher. Other ciphers you may need to know about for your GCSE Computer Science exam are The Pigpen Cipher and the Rail Fence Cipher.

Below is a very basic implementation of the Caesar Cipher in Python. Type it into your IDLE editor (don’t copy and paste!) and run it to see it work. Try calling the encipher function with different values. Once you’ve done that, have a think about what you could do to extend the program. For example, can you write a “decipher” function? What about handling lowercase letters?

# Ceasar Cipher program

# Function to encode individual characters based on key
def cipher(char, key):
    char = (ord(char) + key - 65) % 26 + 65
    return chr(char)

# Function to encode whole plaintext    
def encipher(plaintext, key):
    ciphertext = ""
    for char in plaintext.upper():
        ciphertext += cipher(char, key)
    return ciphertext
    
# Test the program with specific values
print (encipher("Hello", 3))

Have fun exploring the fascinating world of ciphers.

 Caesar Cipher – GCSE Computer Science