ου γαρ εστιν κρυπτον ο ου φανερον γενησεται ουδε αποκρυφον ο ου γνωσθησεται και εις φανερον ελθη
Wersja PL ENG Version

Caesar cipher

  • Description
  • Algorithm
  • Implementation
The Caesar cipher is a simple substitution cipher, which replaces each plaintext letter by a different letter of the alphabet. The cipher is named after Gaius Julius Caesar (100 BC – 44 BC), who used it for communication with his friends and allies.
Simple substitution cipher
Julius Caesar encrypted his correspondence in many ways, for example by writing texts in reverse order or writing Latin texts using Greek letters. Some ancient authors (for example, the Roman historian Gaius Suetonius Tranquillus, who lived in the first century of our era) wrote that he was using the cipher with various shifts, of one or three characters.

The Caesar cipher is one of the simplest substitution ciphers.

Each plaintext letter is replaced by another one, which is offset by a certain amount of alphabet positions (always in the same direction). If the algorithm points to the position after the last letter in the alphabet, one should move to the beginning of the alphabet.

The cipher can be presented using mathematical formulas for encrypting and decrypting characters:
    En(x) = (x+n) mod 26
    Dn(x) = (x-n) mod 26
where:
    n is the offset (the secret key) and 26 is the total number of letters in the Latin alphabet (of course, for other languages one should use other a different number).

Security of the Caesar cipher

The Caesar cipher can be easily broken using brute force attacks. To discover the plaintext one should just check all the possible 26 (for the Latin alphabet) offsets.

Like other substitution ciphers, the Caesar cipher can also be attacked using known ciphertext attacks and letter frequency analysis of the ciphertext.

Simple encryption and decryption functions implemented in Python:

KEY = 3

def encrypt(text):
  encrypted = ""
  for ch in text:
    if ord(ch) >= ord('a') and ord(ch) <= ord('z'):
      newCode = ord(ch) + KEY
      if (newCode > ord('z')):
        newCode -= 26
      encrypted += chr(newCode)
    if ord(ch) >= ord('A') and ord(ch) <= ord('Z'):
      newCode = ord(ch) + KEY
      if (newCode > ord('Z')):
        newCode -= 26
      encrypted += chr(newCode)
  return encrypted

def decrypt(text):
  decrypted = ""
  for ch in text:
    if ord(ch) >= ord('a') and ord(ch) <= ord('z'):
      newCode = ord(ch) - KEY
      if (newCode < ord('a')):
        newCode += 26
      decrypted += chr(newCode)
    if ord(ch) >= ord('A') and ord(ch) <= ord('Z'):
      newCode = ord(ch) - KEY
      if (newCode < ord('A')):
        newCode += 26
      decrypted += chr(newCode)
  return decrypted