What is the Caesar Cipher?
Caesar cipher is a widely known historical cipher. In this cipher, each letter from plaintext is replaced with another letter. And, the key determines how many positions down the alphabet the plaintext letter will be shifted. In other words, in Caesar cipher, each letter of the plaintext is replaced with another letter that is a fixed number of positions down the alphabet and the fixed number is specified with the key.
For example, let’s say the plaintext is “apple” and the key is 3. So, each letter of the plaintext “apple” will be shifted 3 positions down the alphabet. ‘a’ will be replaced by ‘d’, p will be replaced by ‘s’, ‘l’ will be replaced by ‘o’ and ‘e’ will be replaced by ‘h.’ So, the ciphertext will be ‘dssoh’
In other words, if E(x) is the encryption operation and D(x) is the decryption operation, then
E(x) = (x + k) mod 26 D(x) = (x - k) mod 26 where k = key
So, if we decrypt ‘dssoh’ with key 3, then ‘d’ will be replaced by ‘a’ and so on and we would get back the plaintext ‘apple.’
How to implement the Caesar Cipher using Python?
The Caesar cipher can be implemented using Python in the following way:
from curses.ascii import isalpha def encrypt(ptext, k): ptext = list(ptext) ctext = list() for i in range(len(ptext)): if(isalpha(ptext[i])): c = chr(((ord(ptext[i]) - ord('a') + k) % 26) + ord('a')) else: c = ptext[i] ctext.append(c) return "".join(ctext) def decrypt(ctext, k): ctext = list(ctext) dtext = list() for i in range(len(ctext)): if(isalpha(ctext[i])): c = chr(((ord(ctext[i]) - ord('a') - k) % 26) + ord('a')) else: c = ctext[i] dtext.append(c) return "".join(dtext) plaintext = input("Plaintext: ") key = input("Key: ") ciphertext = encrypt(plaintext, int(key)) print("Ciphertext: " + ciphertext) decrypted_text = decrypt(ciphertext, int(key)) print("Decrypted Text: " + decrypted_text)
0 Comments