Created
April 16, 2022 19:21
-
-
Save Yousif-FJ/89235b5b9d758b69cac6e12264fb683d to your computer and use it in GitHub Desktop.
Q/Create software that can encrypt and decrypt using a 2 * 2 Hill cipher
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import string | |
import numpy | |
from sympy import Matrix | |
def HillEncrypt(message : string, key: numpy.ndarray): | |
message = message.replace(" ", "") | |
if len(message)%2 != 0: | |
message += 'a' | |
indexMessageArray = GetIndexArrayFromString(message) | |
rowNumber = int(len(message)/2) | |
messageMatrix = numpy.array(indexMessageArray).reshape(rowNumber,2) | |
resultMatrix = messageMatrix.dot(key) | |
resultMatrix = resultMatrix%26 | |
return GetStringFromIndexArray(resultMatrix.flatten()) | |
def HillDecrypt(cipher : string, key : numpy.ndarray): | |
cipher = cipher.replace(" ", "") | |
indexCipherArray = GetIndexArrayFromString(cipher) | |
rowNumber = int(len(cipher)/2) | |
cipherMatrix = numpy.array(indexCipherArray).reshape(rowNumber,2) | |
keyInverse = numpy.array(Matrix(key).inv_mod(26)) | |
resultMatrix = cipherMatrix.dot(keyInverse) | |
resultMatrix = resultMatrix%26 | |
return GetStringFromIndexArray(resultMatrix.flatten()) | |
def GetIndexArrayFromString(input: string): | |
lettersIndexedArray = [] | |
for letter in input: | |
lettersIndexedArray.append(GetIndexFromLetter(letter)) | |
return lettersIndexedArray | |
def GetStringFromIndexArray(leterIndexes : list): | |
result = "" | |
for index in leterIndexes : | |
result += GetLetterFromIndex(int(index)) | |
return result | |
def GetIndexFromLetter(letter): | |
return string.ascii_uppercase.index(letter.upper()) | |
def GetLetterFromIndex(index): | |
return string.ascii_uppercase[index] | |
message = "meet me at eight" | |
key = numpy.array( | |
[[9,4], | |
[5,7]]) | |
cipher = HillEncrypt(message, key) | |
decryptedMessage = HillDecrypt(cipher, key) | |
print(cipher) #print YYBTYYRDYULVPY | |
print(decryptedMessage) #print MEETMEATEIGHTA |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment