Caesar Cipher Algorithm in Python
Caesar Cipher is the most popular encryption technique where each letter in the original text is replaced by a letter according to the shifted alphabet. For example, with a left shift of 3, D would be replaced by A, E would become B, and so on.
Let’s say that we shift the alphabet by 3 positions on the left. Then we get:
Shifted : XYZABCDEFGHIJKLMNOPQRSTUVW
So, the algorithm is simple. We should replace every letter from the original text with the corresponding shifted one by taking into consideration the upper and lower case. We leave as is the characters which are out of the alphabet, like spaces, punctuations etc.
Caesar Cipher Code
The Caesar Cipher will take as input the
original text and the
key and we return the encrypted text.
def caesar_cipher(raw_text, key):
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
shifted_alphabet = alphabet[26-key:]+alphabet[0:(26-key)]
cipher_text = ""
for i in range(len(raw_text)):
char = raw_text[i]
idx = alphabet.find(char.upper())
if idx == -1:
cipher_text = cipher_text + char
cipher_text = cipher_text + shifted_alphabet[idx].lower()
cipher_text = cipher_text + shifted_alphabet[idx]
Let’s see what is the encrypted text of the “ The quick brown fox jumps over the lazy dog!” by taking a key=3
plain_text = "The quick brown fox jumps over the lazy dog!"
'Qeb nrfzh yoltk clu grjmp lsbo qeb ixwv ald!'
Decrypt the Caesar Cipher
In order to decrypt the Caesar Cipher, we need to set as key the 26 minus the encrypted key which was 3 in our case.
'The quick brown fox jumps over the lazy dog!'
Voilà. We showed how we can encrypt and decrypt the Caesar Cipher using Python!
Originally published at https://predictivehacks.com.