0% found this document useful (0 votes)
4 views

Css Exp1

The document contains code for implementing Caesar cipher, Playfair cipher and Rail Fence cipher encryption and decryption algorithms. It includes functions for encrypting and decrypting messages for each cipher along with examples of encrypting sample messages.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Css Exp1

The document contains code for implementing Caesar cipher, Playfair cipher and Rail Fence cipher encryption and decryption algorithms. It includes functions for encrypting and decrypting messages for each cipher along with examples of encrypting sample messages.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

Name: Bruno Pegado Roll No: 21 Batch: TE-B2

Code:
char = {"a":0,"b": 1,"c": 2,"d": 3,"e": 4,"f": 5,"g": 6,"h": 7,"i": 8,"j": 9,"k": 10,"l": 11,"m":
12,"n": 13,"o": 14,"p": 15,"q": 16,"r": 17,"s": 18,"t": 19,"u": 20,"v": 21,"w": 22,"x": 23,"y":
24,"z": 25,}

rev = {0: "A",1: "B",2: "C",3: "D",4: "E",5: "F",6: "G",7: "H",8: "I",9: "J",10: "K",11: "L",12:
"M",13: "N",14: "O",15: "P",16: "Q",17: "R",18: "S",19: "T",20: "U",21: "V",22: "W",23:
"X",24: "Y",25: "Z"}

#! Caesar/Additive cipher

def ceaser_encrypt(msg,key):
enc_msg = ""
for i in range(len(msg)):
if msg[i] != ' ':
enc_word = (char[msg[i]]+key)%26
# print(enc_word)
enc_msg = enc_msg + rev[enc_word]
else:
enc_msg = enc_msg + msg[i]
return enc_msg

def ceaser_decrypt(msg,key):
dec_msg = ""
for i in range(len(msg)):
if msg[i] != ' ':
dec_word = (char[msg[i].lower()] - key) % 26
# print(enc_word)
dec_msg = dec_msg + rev[dec_word]
else:
dec_msg = dec_msg + msg[i]
return dec_msg

#! Playfair Cipher

# Key generation
def prepare_key(key):
# convert 'J' to 'I'
key = key.upper().replace("J","I")
Name: Bruno Pegado Roll No: 21 Batch: TE-B2

key_set = set(key)
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

key_matrix = []

for char in key_set:


if char != 'J':
key_matrix.append(char)

for char in alphabet:


if char not in key_set and char != 'J':
key_matrix.append(char)

key_matrix = [key_matrix[i:i+5] for i in range(0,len(key_matrix),5)]


return key_matrix

# Finding co-ordinates of the letter


def find_coordinates(matrix,char):
# i --> index of the list within the matrix (row number)
# row is the actual list itself wihtin the matrix (col number)
for i,row in enumerate(matrix):
if char in row:
return i,row.index(char)
return None

def preprocess(text):
# Convert to uppercase
text = text.upper().replace(" ","")
# Replace 'J' with 'I'
text = text.replace("J", "I")

i=0
while i < len(text)-1:
if text[i] == text[i+1]:
text = text[:i+1] + "X" + text[i+1:]
i += 2
else:
i += 1

if len(text)%2 != 0:
text += "X"
Name: Bruno Pegado Roll No: 21 Batch: TE-B2

print(text)
processed_text = [text[i:i+2] for i in range(0,len(text),2)]
return processed_text

# function for the encryption using playfair


def playfair_encrypt(plaintext,key):
key_matrix = prepare_key(key)
plaintext = plaintext.upper().replace("J","I")

# print(f"key_matrix : {key_matrix}")
pairs = []
i=0
# iterate through the plainText and perform preprocessing
pairs = preprocess(plaintext)

# print(f"Pairs : {pairs}")
# perform data encryption
ciphertext = ""
for pair in pairs:
row1,col1 = find_coordinates(key_matrix,pair[0])
row2,col2 = find_coordinates(key_matrix,pair[1])

if row1 == row2:
ciphertext += key_matrix[row1][(col1+1)%5] + key_matrix[row1][(col2+1)%5]
print(f"1 : {ciphertext}")
elif col1 == col2:
ciphertext += key_matrix[(row1+1)%5][col1] + key_matrix[(row2+1)%5][col1]
print(f"2 : {ciphertext}")
else:
ciphertext += key_matrix[row1][col2] + key_matrix[row2][col1]
print(f"3 : {ciphertext}")

return ciphertext

def playfair_decrypt(ciphertext,key):
key_matrix = prepare_key(key)
ciphertext = ciphertext.upper().replace("J","I")

# print(f"key_matrix : {key_matrix}")
pairs = []
Name: Bruno Pegado Roll No: 21 Batch: TE-B2

# iterate through the plainText and perform preprocessing


pairs = preprocess(ciphertext)

# print(f"Pairs : {pairs}")
# perform data encryption
plaintext = ""
for pair in pairs:
row1,col1 = find_coordinates(key_matrix,pair[0])
row2,col2 = find_coordinates(key_matrix,pair[1])

if row1 == row2:
plaintext += key_matrix[row1][(col1-1)%5] + key_matrix[row1][(col2-1)%5]
print(f"1 : {plaintext}")
elif col1 == col2:
plaintext += key_matrix[(row1-1)%5][col1] + key_matrix[(row2-1)%5][col1]
print(f"2 : {plaintext}")
else:
plaintext += key_matrix[row1][col2] + key_matrix[row2][col1]
print(f"3 : {plaintext}")

return plaintext

#! Railfence Cipher
def encrypt_railFence(plaintext,rails):
# initialize the rails
cipher_rows = ['' for _ in range(rails)]
# print(cipher_rows)

current_row = 0
direction = 1 # 1 --> down, -1 --> up

for char in plaintext:


# add a character
cipher_rows[current_row] += char
# increament or decreament row number based on direction
current_row += direction

# if at the edge, first or last rails, wsitch the direction


if current_row == 0 or current_row == rails - 1:
direction *= -1
Name: Bruno Pegado Roll No: 21 Batch: TE-B2

print(cipher_rows)
ciphertext = ''.join(cipher_rows)
return ciphertext

def decrypt_railFence(ciphertext,rails):
rail = [['\n' for i in range(len(ciphertext))]
for j in range(rails)]
# to find the direction
direction = 1
row, col = 0, 0

# mark the places with '*'


#! similar to encryption, traversing in zig-zag and placing markers
for i in range(len(ciphertext)):
rail[row][col] = '*'
col += 1
row += direction
if row == 0 or row == rails-1:
direction *= -1

# now we can construct the


# fill the rail matrix
index = 0
for i in range(rails):
for j in range(len(ciphertext)):
if ((rail[i][j] == '*') and
(index < len(ciphertext))):
rail[i][j] = ciphertext[index]
index += 1

# now read the matrix in


# zig-zag manner to construct
# the resultant text
result = []
row, col = 0, 0
direction = 1
for i in range(len(ciphertext)):
if (rail[row][col] != '*'):
result.append(rail[row][col])
col += 1
row += direction
Name: Bruno Pegado Roll No: 21 Batch: TE-B2

if row == 0 or row == rails-1:


direction *= -1

return("".join(result))

def switch(choice):
# print("choice :",choice)
if(choice == "1"): #!Ceaser Cipher
message = input("Enter the message :")
enc_msg = ceaser_encrypt(message.lower(), 3)
print("Encrypted message:", enc_msg)
dec_msg = ceaser_decrypt(enc_msg, 3)
print("Decrypted message:", dec_msg)
return "1"

elif choice == "2": #! Playfair Cipher


plaintext = input("Enter the message :")
key = input("Enter the key :")
ciphertext = playfair_encrypt(plaintext,key)
print(f"Plaintext:{plaintext}")
print(f"key:{key}")
print(f"CipherText:{ciphertext}")
decrypted_pt = playfair_decrypt(ciphertext,key)
# preprocess to remove X from the string
decrypted_pt = decrypted_pt.replace("X","")
print(f"Decrypted Plaintext:{decrypted_pt}")
return "2"

elif choice == "3":


plaintext = input("Enter the text :")
rails = int(input("Enter number of rails :"))
# Encrypt
ciphertext = encrypt_railFence(plaintext, rails)
print(f"Plaintext: {plaintext}")
print(f"Encrypted: {ciphertext}")
# Decrypt
decrypted_text = decrypt_railFence(ciphertext, rails)
print(f"Decrypted Plaintext: {decrypted_text}")
return "3"
elif choice == "4":
# print("choice :",choice)
Name: Bruno Pegado Roll No: 21 Batch: TE-B2

return "4"

if __name__ == "__main__":
choice = 0
# seed = 65
# print(chr(seed+1))
while choice != "4":
print('''\nwelcome to encryptiion Center :
1. Ceaser Cipher
2. Playfair Cipher
3. RailFence Cipher
4. Exit
''')
choice = switch(input("Enter your choice :"))
print("You have exited the program")

Output:
Name: Bruno Pegado Roll No: 21 Batch: TE-B2

You might also like