Skip to content

Instantly share code, notes, and snippets.

@Yousif-FJ
Created April 16, 2022 19:21
Show Gist options
  • Save Yousif-FJ/89235b5b9d758b69cac6e12264fb683d to your computer and use it in GitHub Desktop.
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
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