Caesar's cipher¶
Caesar's cipher is a very simple method of encrypting a text, the authorship of which is attributed to the Roman commander Julius Caesar. The essence of the method is that each letter of the original text is replaced by another letter shifted by a certain number of positions in the alphabet. This encryption method is very simple and easy to break, so it is not used for serious information security these days. However, it is well suited for demonstrating the basic principles of encryption and can be used for educational purposes, as well as showing how standard character tables can be used to work with indexes.
In this example, we will use an ASCII table to implement this algorithm. Let's define a function to encode and decode a string using the Caesar cipher.
function caesar_cipher_encode_decode(text::String, shift::Int, code::Bool)
encoded_text = Char[]
# Проходим по каждому символу в строке
for char in text
ascii_code = Int(char) # Преобразуем символ к его индексу в ASCII
# Определяем новое значение ASCII-кода в зависимости от типа операции (кодирование или декодирование)
if code
new_ascii_code = ascii_code + shift # Если кодируем, добавляем сдвиг к текущему значению ASCII-кода
else
new_ascii_code = ascii_code - shift # Если декодируем, вычитаем сдвиг из текущего значения ASCII-кода
end
push!(encoded_text, Char(new_ascii_code)) # Преобразуем новое значение ASCII-кода обратно в символ и добавляем его в массив
end
return join(encoded_text) # Соединяем все символы в единую строку и возвращаем результат
end
# Пример использования функций
plaintext = "Engee"
shift_amount = 3
ciphertext = caesar_cipher_encode_decode(plaintext, shift_amount, true)
println("Encoded Text: ", ciphertext)
decrypted_text = caesar_cipher_encode_decode(ciphertext, shift_amount, false)
println("Decoded Text: ", decrypted_text)
Conclusion¶
As you can see, we got the source word as a result of the transformations. It means that our function works correctly.