How to encrypt a plaintext message using Caesar cipher in Python
Caesar cipher is an encryption techniques, which involves substituting each letter of the
The shift defines how many positions each letter in the alphabet would move and determines what the encrypted text would look like.
Example
This is what encryption using Caesar cipher would look like:
In the illustration above, we have shifted the entire alphabet by
We can similarly use any number of shift ranging between
Implementation
Let's implement it in Python, as follows:
def encryption(plaintext, shift):result = ""for i in range(len(plaintext)):letter = plaintext[i]if (letter == " "):result = result + " "elif (letter.isupper()):result = result + chr((ord(letter) + shift - 65) % 26 + 65)else:result = result + chr((ord(letter) + shift - 97) % 26 + 97)return resultif __name__ == "__main__":plaintext = "Hello World"shift = 10encryptedtext = encryption(plaintext, shift)print("Plain text: ", plaintext)print("Encryption text: ", encryptedtext)
Explanation
Lines 1–14: We define the function
encrypted(), which takes two parameters theplaintextand theshift, and returns the encrypted text accordingly.Lines 2 and 14: We define
result, which will hold the encrypted text, and return it from the function.Line 4–12: We use a
forloop to loop over theplaintextand encrypt it letter by letter:Lines 7–8: We check whether the letter is a space and add a space to the encrypted text accordingly.
Lines 9–10: We check whether the letter is an uppercase letter and encrypt it accordingly to an uppercase letter.
Lines 11–12: We encrypt the letter to a lowercase letter.
Lines 16–23: We define the
mainfunction, which calls the functionencryptionto encrypt the provided text and prints encrypted text.
Free Resources