The caesar cipher is one of the most widely-known and simple ciphers in classical cryptography.
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.
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
K is the same as not shifting at all.
Similarly, any key below
0 or above
K has an identical key between
K - 1 This makes the keyspace extremely small and 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): 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])
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)
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)
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.
encrypt("SUPERSECRETMESSAGE", 13) encrypt("FHCREFRPERGZRFFNTR", 13)
We can also use the decryption function to encrypt with ROT13.
decrypt("SUPERSECRETMESSAGE", 13) decrypt("FHCREFRPERGZRFFNTR", 13)