In []:
 

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 rotation 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 of K elements, as shifting by 0 or K is the same as not shifting at all.

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

Python implementation

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):
    return "".join(chr(n + ord("A")) for n in numbers)

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):
    numbers = text_to_numbers(text)
    for i, n in enumerate(numbers):
        numbers[i] = (n + key) % 26
    return numbers_to_text(numbers)

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

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

ROT13

The well-known ROT13 cipher is a special case of the Caesar cipher. The key is 13, which divides the alphabet in half.

Because of this, the encryption and decryption functions are identical.

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

We can also use the decryption function to encrypt with ROT13.

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