0% found this document useful (0 votes)
96 views19 pages

Cryptography Lab DA-1

The document describes code implementing three classical ciphers: Caesar cipher, Playfair cipher, and Hill cipher. For the Caesar cipher, it defines encryption and decryption functions that shift each letter by a key. For the Playfair cipher, it generates a key matrix from the keyword and encrypts plaintext by mapping letter pairs to other pairs based on their positions in the matrix. For the Hill cipher, it defines encryption and decryption functions that multiply plaintext and ciphertext matrices by an encryption matrix determined by a keyword.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
96 views19 pages

Cryptography Lab DA-1

The document describes code implementing three classical ciphers: Caesar cipher, Playfair cipher, and Hill cipher. For the Caesar cipher, it defines encryption and decryption functions that shift each letter by a key. For the Playfair cipher, it generates a key matrix from the keyword and encrypts plaintext by mapping letter pairs to other pairs based on their positions in the matrix. For the Hill cipher, it defines encryption and decryption functions that multiply plaintext and ciphertext matrices by an encryption matrix determined by a keyword.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Assessment 1

Applied Cryptography and Network Security


Name:Gautam.T
Regno:19MIC0092
1. Caesar cipher
Code-
def encryption():
print("Encryption")

print("Message can only be Lower or Uppercase alphabet")


msg = input("Enter message: ")
key = int(input("Enter key(0-25): ")) # based on 26 letters of alphabet

encrypted_text = "Cryptography"

for i in range(len(msg)):
if ord(msg[i]) == 32: # ord() will give us the ASCII of space char,
which is 32
encrypted_text += chr(ord(msg[i])) # chr() will convert ASCII
back to character

elif ord(msg[i]) + key > 122:


# after 'z' move back to 'a', 'a' = 97, 'z' = 122
temp = (ord(msg[i]) + key) - 122 # subtracting 122 to get a lower
int and adding it in 96
encrypted_text += chr(96+temp)

elif (ord(msg[i]) + key > 90) and (ord(msg[i]) <= 96):


# moving back to 'A' after 'Z'
temp = (ord(msg[i]) + key) - 90
encrypted_text += chr(64+temp)

else:
# in case of letters being between a-z and A-Z
encrypted_text += chr(ord(msg[i]) + key)

print("Encrypted: " + encrypted_text)

def decryption():
print("Decryption")

print("Message can only be Lower or Uppercase alphabet")


encrp_msg = input("Enter encrypted Text: ")
decrp_key = int(input("Enter key(0-25): "))

decrypted_text = ""

for i in range(len(encrp_msg)):
if ord(encrp_msg[i]) == 32:
decrypted_text += chr(ord(encrp_msg[i]))

elif ((ord(encrp_msg[i]) - decrp_key) < 97) and ((ord(encrp_msg[i]) -


decrp_key) > 90):
# subtract key from letter ASCII and add 26 to current number
temp = (ord(encrp_msg[i]) - decrp_key) + 26
decrypted_text += chr(temp)

elif (ord(encrp_msg[i]) - decrp_key) < 65:


temp = (ord(encrp_msg[i]) - decrp_key) + 26
decrypted_text += chr(temp)

else:
decrypted_text += chr(ord(encrp_msg[i]) - decrp_key)

print("Decrypted Text: " + decrypted_text)


def main():
choice = int(input("1. Encryption\n2. Decryption\nChoose(1,2): "))
if choice == 1:
encryption()
elif choice == 2:
decryption()
else:
print("Wrong Choice")

if __name__ == "__main__":
main()

Output-

Encryption:
Decryption:

2.Playfair cipher:
Code-
plainText=[]
keyMatrix = []
cipherTextList =[]
def index_2d(keyMatrix, v):
for i, x in enumerate(keyMatrix):
if v in x:
return [i, x.index(v)]
def keyMatrixGeneration(keyMatrix,reducedAlphabet):
alphacounter = 0
alpha = len(reducedAlphabet)
#print(alpha,'[alpha]')
while alphacounter < alpha and
len(reducedAlphabet[alphacounter:alphacounter+5]) :
tempReducedAlphabet = []
#print(reducedAlphabet[0:5],'[reducedAlphabet temp]')

tempReducedAlphabet.append(reducedAlphabet[alphacounter:alphaco
unter+5])
alphacounter+=5
keyMatrix.extend(tempReducedAlphabet)
if alphacounter > alpha and len(reducedAlphabet[alphacounter-5:]):
tempReducedAlphabet = []
tempReducedAlphabet.append(reducedAlphabet[alphacounter-
5:])
keyMatrix.append(tempReducedAlphabet)
return keyMatrix
def playFairCipher(plainText,key):
# create key matrix
#print(key,'[key]')
#print('[playFairCipher def]')
cipherText = ''
keyList = list(key.strip(' '))
keyListSet = set(keyList) # use this to find difference in alphabet and
key
reducedKeyList = []
for ch in keyList:
if ch not in reducedKeyList:
reducedKeyList.append(ch)
tempKey = []
#print(keyListSet,reducedKeyList)

k = len(reducedKeyList)
counter = 0
alphabet = list('abcdefghijklmnopqrstuvwxyz')
alphabetSet = set(alphabet)
keycount = 5
#print(k)
if k==5:
#print('k==5')
keyMatrix.append(reducedKeyList[0:5])
elif k>5:
while keycount<=k:

keyMatrix.append(reducedKeyList[keycount-5:keycount])
keycount+=5
if keycount > k:
keyMatrix.append(reducedKeyList[keycount-5:])

else:
keyMatrix.append(reducedKeyList)

print(keyMatrix,'[before keyMatrix]')
reducedAlphabetSet = alphabetSet-keyListSet
#print(reducedAlphabetSet,'[reducedAlphabetSet]')
reducedAlphabet = list(reducedAlphabetSet)
reducedAlphabet.sort()
#print(reducedAlphabet,'[reducedAlphabet list]')
if 'i'and 'j' in reducedAlphabet:
reducedAlphabet.remove('j')
if 'i' not in reducedAlphabet and 'j' not in reducedAlphabet:
ind = index_2d(keyMatrix,'j')
print(ind,keyMatrix[ind[0]][ind[1]])
keyMatrix[ind[0]].remove(keyMatrix[ind[0]][ind[1]])
lengthCheck = False
keyN = 0
# generation of key matrix
for i in range(0,len(keyMatrix)):
if len(keyMatrix[i])<5:
lengthCheck=True
keyN = i
if lengthCheck==True:
tempReducedAlphabet = []
tempReducedAlphabet.extend(reducedAlphabet[0:5-
len(keyMatrix[keyN])])
#print(tempReducedAlphabet,'[tempReducedAlphabet]')
keyMatrix[keyN].extend(tempReducedAlphabet)
for i in tempReducedAlphabet:
reducedAlphabet.remove(i)
#print(reducedAlphabet,'[reducedAlphabet]')
keyMatrixGeneration(keyMatrix,reducedAlphabet)
else:
keyMatrixGeneration(keyMatrix,reducedAlphabet)
print(keyMatrix,'[keymatrix]')
# matching plainText with key matrix
for i in range(0,len(plainText)):
first=[]
second=[]
first.extend(index_2d(keyMatrix,plainText[i][0]))
second.extend(index_2d(keyMatrix,plainText[i][1]))
if first[0]!=second[0] and first[1]!=second[1]:
cipherText += keyMatrix[first[0]][second[1]]+
keyMatrix[second[0]][first[1]]
elif first[0]==second[0]:
if first[1]+1<len(keyMatrix[first[0]]):
cipherText+=keyMatrix[first[0]][first[1]+1]
else:
cipherText+=keyMatrix[first[0]][0]
if second[1]+1<len(keyMatrix[second[0]]):
cipherText+=keyMatrix[first[0]][second[1]+1]
else:
cipherText+=keyMatrix[first[0]][0]
else:
if first[0]+1<len(keyMatrix):
cipherText+=keyMatrix[first[0]+1][first[1]]
else:
cipherText+=keyMatrix[0][first[1]]
if second[0]+1<len(keyMatrix):
cipherText+=keyMatrix[second[0]+1][second[1]]
else:
cipherText+=keyMatrix[0][second[1]]
#print(first,'[first]')
print(cipherText,'[cipherText]')
return cipherText
def plainTextConversion(s,key):

i=0

sList = list(s.strip())
n = len(sList)
while(n>0):
temp=[]
checkSame=False
#print(sList,'sList')
for j in range(0,2):
if j<len(sList) and sList[j] not in temp :
temp.append(sList[j])
checkSame = False
elif j<len(sList) and sList[j] in temp :
temp.append('x')
checkSame = True
else:
checkSame = False
continue
#print(temp,'temp')
sList.remove(sList[0])
# print(checkSame)
if len(temp)>1 and checkSame == False:
sList.remove(sList[0])
plainText.append(temp)
n=n-2
elif len(temp)>1 and checkSame == True:
#do noting
plainText.append(temp)
n=n-1
elif len(temp)<1 and checkSame == True:
# do nothing
plainText.append(temp)
else:
temp.append('x')
plainText.append(temp)
n=n-2
#print(n,'n')

#print(plainText,'plainText')

print(plainText,'final')
res = playFairCipher(plainText,key)
return res

if __name__ == '__main__':
s = input('enter plainText : ')
key = input('enter key text : ')
s = ''.join(s.split())
key = ''.join(key.split())
print(s,'[s]')
result = plainTextConversion(s,key)
print (result)

Output:
Encryption-

3.Hill cipher:
Code-
import numpy as np
def encrypt(msg):
# Replace spaces with nothing
msg = msg.replace(" ", "")
# Ask for keyword and get encryption matrix
C = make_key()
# Append zero if the messsage isn't divisble by 2
len_check = len(msg) % 2 == 0
if not len_check:
msg += "0"
# Populate message matrix
P = create_matrix_of_integers_from_string(msg)
# Calculate length of the message
msg_len = int(len(msg) / 2)
# Calculate P * C
encrypted_msg = ""
for i in range(msg_len):
# Dot product
row_0 = P[0][i] * C[0][0] + P[1][i] * C[0][1]
# Modulate and add 65 to get back to the A-Z range in ascii
integer = int(row_0 % 26 + 65)
# Change back to chr type and add to text
encrypted_msg += chr(integer)
# Repeat for the second column
row_1 = P[0][i] * C[1][0] + P[1][i] * C[1][1]
integer = int(row_1 % 26 + 65)
encrypted_msg += chr(integer)
return encrypted_msg

def decrypt(encrypted_msg):
# Ask for keyword and get encryption matrix
C = make_key()
# Inverse matrix
determinant = C[0][0] * C[1][1] - C[0][1] * C[1][0]
determinant = determinant % 26
multiplicative_inverse = find_multiplicative_inverse(determinant)
C_inverse = C
# Swap a <-> d
C_inverse[0][0], C_inverse[1][1] = C_inverse[1, 1], C_inverse[0, 0]
# Replace
C[0][1] *= -1
C[1][0] *= -1
for row in range(2):
for column in range(2):
C_inverse[row][column] *= multiplicative_inverse
C_inverse[row][column] = C_inverse[row][column] % 26

P = create_matrix_of_integers_from_string(encrypted_msg)
msg_len = int(len(encrypted_msg) / 2)
decrypted_msg = ""
for i in range(msg_len):
# Dot product
column_0 = P[0][i] * C_inverse[0][0] + P[1][i] * C_inverse[0][1]
# Modulate and add 65 to get back to the A-Z range in ascii
integer = int(column_0 % 26 + 65)
# Change back to chr type and add to text
decrypted_msg += chr(integer)
# Repeat for the second column
column_1 = P[0][i] * C_inverse[1][0] + P[1][i] * C_inverse[1][1]
integer = int(column_1 % 26 + 65)
decrypted_msg += chr(integer)
if decrypted_msg[-1] == "0":
decrypted_msg = decrypted_msg[:-1]
return decrypted_msg

def find_multiplicative_inverse(determinant):
multiplicative_inverse = -1
for i in range(26):
inverse = determinant * i
if inverse % 26 == 1:
multiplicative_inverse = i
break
return multiplicative_inverse

def make_key():
# Make sure cipher determinant is relatively prime to 26 and only a/A - z/Z are
given
determinant = 0
C = None
while True:
cipher = input("Input 4 letter cipher: ")
C = create_matrix_of_integers_from_string(cipher)
determinant = C[0][0] * C[1][1] - C[0][1] * C[1][0]
determinant = determinant % 26
inverse_element = find_multiplicative_inverse(determinant)
if inverse_element == -1:
print("Determinant is not relatively prime to 26, uninvertible key")
elif np.amax(C) > 26 and np.amin(C) < 0:
print("Only a-z characters are accepted")
print(np.amax(C), np.amin(C))
else:
break
return C

def create_matrix_of_integers_from_string(string):
# Map string to a list of integers a/A <-> 0, b/B <-> 1 ... z/Z <-> 25
integers = [chr_to_int(c) for c in string]
length = len(integers)
M = np.zeros((2, int(length / 2)), dtype=np.int32)
iterator = 0
for column in range(int(length / 2)):
for row in range(2):
M[row][column] = integers[iterator]
iterator += 1
return M

def chr_to_int(char):
# Uppercase the char to get into range 65-90 in ascii table
char = char.upper()
# Cast chr to int and subtract 65 to get 0-25
integer = ord(char) - 65
return integer

if __name__ == "__main__":
msg = input("Message: ")
encrypted_msg = encrypt(msg)
print(encrypted_msg)
decrypted_msg = decrypt(encrypted_msg)
print(decrypted_msg)

Output:
Encryption and Decryption-

You might also like