Caesar Cipher Encryption & Decryption in Python

Caesar Cipher is a type of substitution cipher, in which each letter in the plain text is replaced by another letter at some fixed positions from the current letter in the alphabet. 

A python program to encrypt the plaintext into ciphertext.

def encrypt(plaintext,key):

result = ""


# traverse text

for i in range(len(plaintext)):

char = plaintext[i]


# Encrypt uppercase characters

if (char.isupper()):

result += chr((ord(char) + key-65) % 26 + 65)


# Encrypt lowercase characters

else:

result += chr((ord(char) + key - 97) % 26 + 97)


return result


#check the above function

plaintext = "cybersploit"

key = 2

print ("Text : " + plaintext)

print ("Shift : " + str(key))

print ("Cipher: " + encrypt(plaintext,key))






A python program to decrypt the ciphertext into plaintext.

def decrypt(ciphertext,key):

result = ""


# traverse text

for i in range(len(ciphertext)):

char = ciphertext[i]


# Encrypt uppercase characters

if (char.isupper()):

result += chr((ord(char) - key-65) % 26 + 65)


# Encrypt lowercase characters

else:

result += chr((ord(char) - key - 97) % 26 + 97)


return result


#check the above function

ciphertext= ""

key = 2

print ("Text : " + ciphertext)

print ("Shift : " + str(key))

print ("Cipher: " + decrypt(ciphertext,key))




Post a Comment

0 Comments