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 :
```def text_to_numbers(text):
return [ord(c) - ord("A") for c in text]

text_to_numbers("ABCD")
text_to_numbers("HELLO")```
Out :
`[0, 1, 2, 3]`
Out :
`[7, 4, 11, 11, 14]`
In :
```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 :
`'ABCD'`
Out :
`'HELLO'`
In :
```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 :
`'YJXYRJXXFLJ'`
In :
```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 :
`'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 :
```encrypt("SUPERSECRETMESSAGE", 13)
encrypt("FHCREFRPERGZRFFNTR", 13)```
Out :
`'FHCREFRPERGZRFFNTR'`
Out :
`'SUPERSECRETMESSAGE'`

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

In :
```decrypt("SUPERSECRETMESSAGE", 13)
decrypt("FHCREFRPERGZRFFNTR", 13)```
Out :
`'FHCREFRPERGZRFFNTR'`
Out :
`'SUPERSECRETMESSAGE'`