Cryptography Lab DA-1
Cryptography Lab DA-1
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
else:
# in case of letters being between a-z and A-Z
encrypted_text += chr(ord(msg[i]) + key)
def decryption():
print("Decryption")
decrypted_text = ""
for i in range(len(encrp_msg)):
if ord(encrp_msg[i]) == 32:
decrypted_text += chr(ord(encrp_msg[i]))
else:
decrypted_text += chr(ord(encrp_msg[i]) - decrp_key)
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-