Encrypting and Decrypting Text with the Caesar Cipher in Python
- Cryptography
- Python
The Caesar cipher is a simple way of encrypting and decrypting messages by shifting the letters of the alphabet by a certain number of positions. It was named after Julius Caesar, who used it to communicate with his generals and allies during his military campaigns.
How Caesar cipher works
The Caesar cipher works by shifting the letters of the alphabet by a certain number of positions. For example, if you shift the alphabet by 3 positions to the right, then A becomes D, B becomes E, C becomes F, and so on.
The complete substitution table is shown below:
Original alphabet | A | B | C | D | E | F | G | H | I | J | K | L | M |
Shifted alphabet | D | E | F | G | H | I | J | K | L | M | N | O | P |
Original alphabet | N | O | P | Q | R | S | T | U | V | W | X | Y | Z |
Shifted alphabet | Q | R | S | T | U | V | W | X | Y | Z | A | B | C |
To encrypt a message, you replace each letter in the message with the corresponding letter in the shifted alphabet. For example, the text “HELLO” would be encrypted as “KHOOR”.
To decrypt a message, you do the opposite: you replace each letter in the message with the corresponding letter in the original alphabet.
Write the Python code
Given the Caesar cipher algorithm above, we can write the Python code to encrypt text like shown below.
The function caesar_cipher
takes two inputs: text
(the message to be encrypted) and shift
(how much to shift each letter by).
For each letter in the input text, the code does the following:
- If the character is a letter, it calculates the substitution letter by shifting it with the given
shift
value. It also ensures that the shifting wraps around the alphabet. - If the character is not a letter, it is added to the encrypted message as is.
- The substitution letter is added to the encrypted message.
Once it done processing each letter, the function will return the encrypted text.
If you call the function to encrypt “Hello, World!” with shift
equal to 3, it will return “Khoor, Zruog!”.
How to decrypt the encrypted text
The decryption of the Caesar cipher is similar with the encryption, only we do it in reverse. This means we can reuse the caesar_cipher
function above but with negative shift instead.
If you call the function to decrypt “Khoor, Zruog!” with shift
equal to -3, it will return “Hello, World!”.
Key takeaways
The Caesar cipher is a simple example of a substitution cipher, where each letter in the plaintext is replaced with a different letter. It is easy to implement and understand, but it is also relatively easy to break. This is because the shift amount is typically small, which makes it easy to guess.
Although the algorithm is relatively weak, it is still a good way to learn about encryption and cryptography. It is also a good way to encrypt short messages that you do not want others to read.