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.

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

[0, 1, 2, 3]

[7, 4, 11, 11, 14]

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])

'ABCD'

'HELLO'

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)

'YJXYRJXXFLJ'

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)

'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
```

encrypt("SUPERSECRETMESSAGE", 13) encrypt("FHCREFRPERGZRFFNTR", 13)

'FHCREFRPERGZRFFNTR'

'SUPERSECRETMESSAGE'

Similarly, using the decrypt function.

decrypt("SUPERSECRETMESSAGE", 13) decrypt("FHCREFRPERGZRFFNTR", 13)

'FHCREFRPERGZRFFNTR'

'SUPERSECRETMESSAGE'