The Caesar cipher is one of the most widely-known and simple ciphers in classical cryptography.

Algorithm

The cipher is a simple monoalphabetic substitution. The substitution alphabet is the normal alphabet, rotated by N positions. For example; the 6-letter alphabet ABCDEF would become CDEFAB with a shift of 2 positions.

Keyspace

As the only parameter to the cipher, the shift amount N serves as the key. There can only be K - 1 different keys for an alphabet with K elements, as shifting by 0 or K positions would do nothing.

Similarly, any key below 0 or above K has an identical key between 1 and K - 1. This makes the keyspace extremely small for most useful alphabets, making it trivial to brute-force.

In [2]:
def text_to_numbers(text):
    return [ord(c) - ord('A') for c in text]

text_to_numbers('ABCD')
text_to_numbers('HELLO')
Out [2]:
[0, 1, 2, 3]
Out [2]:
[7, 4, 11, 11, 14]
In [3]:
def numbers_to_text(numbers):
    letters = [chr(n + ord('A')) for n in numbers]
    return "".join(letters)

numbers_to_text([0, 1, 2, 3])
numbers_to_text([7, 4, 11, 11, 14])
Out [3]:
'ABCD'
Out [3]:
'HELLO'
In [4]:
def encrypt(text, key):
    nums = text_to_numbers(text)
    for i in range(len(text)):
        nums[i] += key
        nums[i] %= 26
    return numbers_to_text(nums)

encrypt("TESTMESSAGE", 5)
Out [4]:
'YJXYRJXXFLJ'
In [5]:
def decrypt(text, key):
    nums = text_to_numbers(text)
    for i in range(len(text)):
        nums[i] -= key
        nums[i] %= 26
    return numbers_to_text(nums)

decrypt("YJXYRJXXFLJ", 5)
Out [5]:
'TESTMESSAGE'

ROT13

The well-known ROT13 cipher is a special case of a Caesar cipher. The key is 13, which divides the alphabet into two. Because of this, the encryption and decryption functions become the same.

ABCDEFGHIJKLMNOPQRSTUVWXYZ
NOPQRSTUVWXYZABCDEFGHIJKLM
In [6]:
encrypt("SUPERSECRETMESSAGE", 13)
encrypt("FHCREFRPERGZRFFNTR", 13)
Out [6]:
'FHCREFRPERGZRFFNTR'
Out [6]:
'SUPERSECRETMESSAGE'

Similarly, using the decrypt function.

In [7]:
decrypt("SUPERSECRETMESSAGE", 13)
decrypt("FHCREFRPERGZRFFNTR", 13)
Out [7]:
'FHCREFRPERGZRFFNTR'
Out [7]:
'SUPERSECRETMESSAGE'