Lesson 3

Caesar’s cipher

The Caesar cipher, also known as the shift cipher, Caesar’s code is one of the simplest and most widely known cipher methods.

The Caesar cipher is a type of substitution cipher in which every character in the plaintext is replaced by a character at some fixed number of positions to the left or right of it in the alphabet. For example, in a cipher with a rightward shift of 3, A would be replaced by D, B would become D, and so on.

The cipher is named after the Roman general Gaius Julius Caesar, who used it for secret correspondence with his generals.

Example

Encryption using key k=3. The letter “E” is “moved” three letters forward and becomes a “Z”. A hard sign moved three letters forward becomes an “E”, an “I” moved three letters forward becomes a “B”, and so on:

Исходный алфавит: А Б В Г Д Е Ё Ж З И Й К Л М Н О П Р С Т У Ф Х Ц Ч Ш Щ Ъ Ы Ь Э Ю Я
Шифрованный:      Г Д Е Ё Ж З И Й К Л М Н О П Р С Т У Ф Х Ц Ч Ш Щ Ъ Ы Ь Э Ю Я А Б В 

Original text:

Расшифруйте меня если сможете

Key: 5

The cipher text is obtained by replacing each letter of the original text with the corresponding letter of the cipher alphabet:

Хецэнщхшочй сйты йцрн цсулйчй

History and application

Caesar’s cipher is named after Gaius Julius Caesar, who used it with a left shift of 3

The Caesar cipher is named after Gaius Julius Caesar who, according to Suetonius’ “Life of the Twelve Caesars”, used it with a shift of 3 to protect military communications. Although Caesar was the first recorded person to use this scheme, other substitution ciphers are known to have been used before.

If he had something confidential to pass on, he would write it down in cipher, i.e. change the order of the letters of the alphabet so that not a single word could be made out. If anyone wanted to decipher it and understand its meaning, he had to substitute the fourth letter of the alphabet, namely, D, for A, and so on, with other letters.
Gaius Suetonius Tranquillus Life of the Twelve Caesars, Book One, Ch. 56

His nephew, Augustus, also used this cipher, but with a shift to the right by one, and it was not repeated to the beginning of the alphabet:

Whenever he wrote down the cipher, he wrote down B for A, C for B, and the rest of the letters on the same principle, using AA for X.
Gaius Suetonius Tranquillus Life of the Twelve Caesars, Book Two, Ch. 88

There is evidence that Julius Caesar also used more complex schemes

It is not known how effective Caesar’s cipher was at the time, but it was probably reasonably secure, not least because most of Caesar’s enemies were illiterate and many assumed the messages were written in an unknown foreign language. There is no evidence from the time regarding methods of breaking simple substitution ciphers. The earliest surviving records of frequency analysis are the 9th century writings of Al-Kindi on the discovery of frequency analysis

In the 19th century, the private section of newspaper advertisements was sometimes used to exchange messages encrypted using simple ciphers. Kahn (1967) describes instances where amateurs participated in secret communications encrypted using the Caesar cipher in the Times. Even later, in 1915, Caesar’s cipher had some use: the Russian army used it as a substitute for more complex ciphers, which proved too difficult for the troops; German and Austrian cryptanalysts had only slight difficulty in deciphering the messages.

The Caesar cipher with a shift of thirteen is also used in the ROT13 algorithm, a simple text obfuscation method widely used on the Usenet, and used more as a way to hide spoilers than as an encryption method. The Vigenaire cipher uses a Caesar cipher with a different shift at each position in the text; the shift value is determined by a repeating keyword. If the keyword is as long as the message, generated randomly, kept secret and used only once – such a scheme is called a one-time pad scheme – and it is the only encryption system for which absolute cryptographic strength has been proven.

Keywords shorter than the message (e.g. “Complete Victory”, used by the Confederacy during the US Civil War) introduce a cyclic pattern that could be detected by an improved version of frequency analysis.

In April 2006, fugitive Mafia boss Bernardo Provenzano was caught in Sicily in part because of cryptanalysis of his messages written using a variation of the Caesar cipher. In Provenzano’s cipher, the letters were first replaced by numbers – serial numbers of letters in the alphabet – and Caesar’s cipher was applied to the resulting sequence of numbers, so that a shift of 3 would spell ‘A’ as ‘4’, ‘B’ as ‘5’, and so on.

Often two discs of different diameters placed on a common axis, with alphabets drawn on the edges of the discs, are used to make the Caesar cipher easy to use. Initially the discs are rotated so that opposite each letter of the outer disc alphabet is the same letter of the small disc alphabet. If we now rotate the inner disk by a few characters, we get a correspondence between the characters of the outer disk and the inner disk – the Caesar cipher. The resulting disk can be used for both encryption and decryption.

For example, if we rotate the inner wheel so that symbol A of the outer disk corresponds to symbol D of the inner disk, we get a cipher with a shift of 3 to the left.

Below I have given you the code of the program in python, install python from the official site and open a new file and write this code. Then run

# Текст, который пользователь хочет ввести
text = input("Введите текст, который хотите зашифровавать: ")
# Пользователь вводит ключ
k = int(input("Укажите ключ: "))
# Пользователь вводит язык текста, который будет зашифрован
language = input("На каком языке текст, который вы ввели (русский, английский): ")


# Функция шифрования с тремя параметрами: текст, ключ, язык
def ceaser_cipher(user, key, lang):
    # Переменная результата шифрования; переменная, опредиляющая верхний и нижний регистр
    res, n = [], ""

    # Проверка пользователем выбранного языка

    # Проверка выбран ли русский язык (регистр букв, вводимых пользователем, не важен)
    if lang.lower() in ["русский", "russian"]:
        # Двум переменным присваиваются русская азбука нижнего и верхнего регистра соответственно
        dictionary, dictionary_upper = "абвгдеёжзийклмнопрстуфхцчшщъыьэюя", "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ"
    # Проверка выбран ли английский язык язык (регистр букв, вводимых пользователем, не важен)
    elif lang.lower() in ["английский", "english"]:
        # Двум переменным присваиваются английской азбука нижнего и верхнего регистра соответственно
        dictionary, dictionary_upper = "abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    else:
        return "Такого языка нет в опции"

    # Цикл проверки, где каждую итерацию будет обрабатываться один символ из текста последовательно
    for i in range(len(user)):
        # Проверка символа на верхний или нижний регистр

        # Принадлежит ли символ нижнему регистру
        if user[i] in dictionary:
            n = dictionary
        # Принадлежит ли символ верхнему регистру
        elif user[i] in dictionary_upper:
            n = dictionary_upper
        # Символ не принадлежит ни нижнему ни верхнему регистру (символ не является буквой)
        else:
            res.append(user[i])

        # Если символ есть в списке n (является буквой), то будет происходить его зашифровка
        if user[i] in n:
            # Цикл перебора азбуки
            for j in range(len(n)):
                # Если порядковый номер буквы + ключ находятся  в диапазоне от 0 до конца азбуки
                # и если буква из текста совпадает с буквой из азбуки, то:
                if 0 <= j + key < len(n) and user[i] == n[j]:
                    # В результат добавляется буква со сдвигом key (зашифрованная буква)
                    res.append(n[j + key])
                # Если порядковый номер буквы + ключ выходит из диапазона азбуки, превышая его
                # и если буква из текста совпадает с буквой из азбуки, то:
                elif j + key >= len(n) and user[i] == n[j]:
                    # В результат добавляеться буква со сдвигом key,
                    # при этом преводя порядковый номер буквы к диапазону азбуки (зашифрованая буква)
                    res.append(n[(1 - j - key) % (len(n) - 1)])
                # Если порядковый номер буквы + ключ выходит из диапазона азбуки, недотягивает до него
                # и если буква из текста совпадает с буквой из азбуки, то:
                elif j + key < 0 and user[i] == n[j]:
                    # В результат добавляеться буква со сдвигом key,
                    # при этом преводя порядковый номер буквы к диапазону азбуки (зашифрованая буква)
                    res.append(n[(j + key) % len(n)])

    # Функция возвращает зашифрованный текст
    return ''.join(res)


# Вывод зашифрованного текста
print(ceaser_cipher(text, k, language))