2019-02-21 16:19:28 +00:00
|
|
|
"""
|
|
|
|
|
|
|
|
Hill Cipher:
|
2020-05-18 11:05:51 +00:00
|
|
|
The 'HillCipher' class below implements the Hill Cipher algorithm which uses
|
|
|
|
modern linear algebra techniques to encode and decode text using an encryption
|
|
|
|
key matrix.
|
2019-02-21 16:19:28 +00:00
|
|
|
|
2020-01-18 12:24:33 +00:00
|
|
|
Algorithm:
|
2019-02-21 16:19:28 +00:00
|
|
|
Let the order of the encryption key be N (as it is a square matrix).
|
|
|
|
Your text is divided into batches of length N and converted to numerical vectors
|
|
|
|
by a simple mapping starting with A=0 and so on.
|
|
|
|
|
2020-01-18 12:24:33 +00:00
|
|
|
The key is then multiplied with the newly created batch vector to obtain the
|
2019-02-21 16:19:28 +00:00
|
|
|
encoded vector. After each multiplication modular 36 calculations are performed
|
|
|
|
on the vectors so as to bring the numbers between 0 and 36 and then mapped with
|
|
|
|
their corresponding alphanumerics.
|
|
|
|
|
|
|
|
While decrypting, the decrypting key is found which is the inverse of the
|
|
|
|
encrypting key modular 36. The same process is repeated for decrypting to get
|
|
|
|
the original message back.
|
|
|
|
|
|
|
|
Constraints:
|
|
|
|
The determinant of the encryption key matrix must be relatively prime w.r.t 36.
|
|
|
|
|
|
|
|
Note:
|
2020-05-18 11:05:51 +00:00
|
|
|
This implementation only considers alphanumerics in the text. If the length of
|
|
|
|
the text to be encrypted is not a multiple of the break key(the length of one
|
|
|
|
batch of letters), the last character of the text is added to the text until the
|
|
|
|
length of the text reaches a multiple of the break_key. So the text after
|
|
|
|
decrypting might be a little different than the original text.
|
2019-02-21 16:19:28 +00:00
|
|
|
|
|
|
|
References:
|
|
|
|
https://apprendre-en-ligne.net/crypto/hill/Hillciph.pdf
|
|
|
|
https://www.youtube.com/watch?v=kfmNeskzs2o
|
|
|
|
https://www.youtube.com/watch?v=4RhLNDqcjpA
|
|
|
|
|
|
|
|
"""
|
2020-05-18 11:05:51 +00:00
|
|
|
import string
|
2020-07-06 07:44:19 +00:00
|
|
|
|
2019-02-21 16:19:28 +00:00
|
|
|
import numpy
|
|
|
|
|
|
|
|
|
2020-05-18 11:05:51 +00:00
|
|
|
def greatest_common_divisor(a: int, b: int) -> int:
|
2020-05-18 07:03:20 +00:00
|
|
|
"""
|
2020-05-18 11:05:51 +00:00
|
|
|
>>> greatest_common_divisor(4, 8)
|
2020-05-18 07:03:20 +00:00
|
|
|
4
|
2020-05-18 11:05:51 +00:00
|
|
|
>>> greatest_common_divisor(8, 4)
|
2020-05-18 07:03:20 +00:00
|
|
|
4
|
2020-05-18 11:05:51 +00:00
|
|
|
>>> greatest_common_divisor(4, 7)
|
2020-05-18 07:03:20 +00:00
|
|
|
1
|
2020-05-18 11:05:51 +00:00
|
|
|
>>> greatest_common_divisor(0, 10)
|
2020-05-18 07:03:20 +00:00
|
|
|
10
|
|
|
|
"""
|
2020-05-18 11:05:51 +00:00
|
|
|
return b if a == 0 else greatest_common_divisor(b % a, a)
|
2019-02-21 16:19:28 +00:00
|
|
|
|
|
|
|
|
|
|
|
class HillCipher:
|
2020-05-18 11:05:51 +00:00
|
|
|
key_string = string.ascii_uppercase + string.digits
|
2019-02-21 16:19:28 +00:00
|
|
|
# This cipher takes alphanumerics into account
|
|
|
|
# i.e. a total of 36 characters
|
|
|
|
|
|
|
|
# take x and return x % len(key_string)
|
|
|
|
modulus = numpy.vectorize(lambda x: x % 36)
|
|
|
|
|
2022-05-13 12:51:44 +00:00
|
|
|
to_int = numpy.vectorize(round)
|
2019-10-05 05:14:13 +00:00
|
|
|
|
2021-04-04 05:22:12 +00:00
|
|
|
def __init__(self, encrypt_key: numpy.ndarray) -> None:
|
2019-02-21 16:19:28 +00:00
|
|
|
"""
|
2020-05-18 11:05:51 +00:00
|
|
|
encrypt_key is an NxN numpy array
|
2019-02-21 16:19:28 +00:00
|
|
|
"""
|
2019-10-05 05:14:13 +00:00
|
|
|
self.encrypt_key = self.modulus(encrypt_key) # mod36 calc's on the encrypt key
|
2020-03-04 12:40:28 +00:00
|
|
|
self.check_determinant() # validate the determinant of the encryption key
|
2019-02-21 16:19:28 +00:00
|
|
|
self.break_key = encrypt_key.shape[0]
|
|
|
|
|
2020-05-18 11:05:51 +00:00
|
|
|
def replace_letters(self, letter: str) -> int:
|
2020-05-18 07:03:20 +00:00
|
|
|
"""
|
2020-05-18 11:05:51 +00:00
|
|
|
>>> hill_cipher = HillCipher(numpy.array([[2, 5], [1, 6]]))
|
|
|
|
>>> hill_cipher.replace_letters('T')
|
2020-05-18 07:03:20 +00:00
|
|
|
19
|
2020-05-18 11:05:51 +00:00
|
|
|
>>> hill_cipher.replace_letters('0')
|
2020-05-18 07:03:20 +00:00
|
|
|
26
|
|
|
|
"""
|
|
|
|
return self.key_string.index(letter)
|
|
|
|
|
2020-05-18 11:05:51 +00:00
|
|
|
def replace_digits(self, num: int) -> str:
|
2020-05-18 07:03:20 +00:00
|
|
|
"""
|
2020-05-18 11:05:51 +00:00
|
|
|
>>> hill_cipher = HillCipher(numpy.array([[2, 5], [1, 6]]))
|
|
|
|
>>> hill_cipher.replace_digits(19)
|
2020-05-18 07:03:20 +00:00
|
|
|
'T'
|
2020-05-18 11:05:51 +00:00
|
|
|
>>> hill_cipher.replace_digits(26)
|
2020-05-18 07:03:20 +00:00
|
|
|
'0'
|
|
|
|
"""
|
|
|
|
return self.key_string[round(num)]
|
|
|
|
|
|
|
|
def check_determinant(self) -> None:
|
|
|
|
"""
|
2020-05-18 11:05:51 +00:00
|
|
|
>>> hill_cipher = HillCipher(numpy.array([[2, 5], [1, 6]]))
|
2020-05-18 07:03:20 +00:00
|
|
|
>>> hill_cipher.check_determinant()
|
|
|
|
"""
|
2019-02-21 16:19:28 +00:00
|
|
|
det = round(numpy.linalg.det(self.encrypt_key))
|
2019-10-05 05:14:13 +00:00
|
|
|
|
2019-02-21 16:19:28 +00:00
|
|
|
if det < 0:
|
|
|
|
det = det % len(self.key_string)
|
|
|
|
|
|
|
|
req_l = len(self.key_string)
|
2020-05-18 11:05:51 +00:00
|
|
|
if greatest_common_divisor(det, len(self.key_string)) != 1:
|
2019-10-05 05:14:13 +00:00
|
|
|
raise ValueError(
|
2020-06-16 08:09:19 +00:00
|
|
|
f"determinant modular {req_l} of encryption key({det}) is not co prime "
|
|
|
|
f"w.r.t {req_l}.\nTry another key."
|
2019-10-05 05:14:13 +00:00
|
|
|
)
|
2019-02-21 16:19:28 +00:00
|
|
|
|
2020-05-18 07:03:20 +00:00
|
|
|
def process_text(self, text: str) -> str:
|
|
|
|
"""
|
2020-05-18 11:05:51 +00:00
|
|
|
>>> hill_cipher = HillCipher(numpy.array([[2, 5], [1, 6]]))
|
2020-05-18 07:03:20 +00:00
|
|
|
>>> hill_cipher.process_text('Testing Hill Cipher')
|
|
|
|
'TESTINGHILLCIPHERR'
|
2020-05-18 11:05:51 +00:00
|
|
|
>>> hill_cipher.process_text('hello')
|
|
|
|
'HELLOO'
|
2020-05-18 07:03:20 +00:00
|
|
|
"""
|
2020-05-18 11:05:51 +00:00
|
|
|
chars = [char for char in text.upper() if char in self.key_string]
|
2019-02-21 16:19:28 +00:00
|
|
|
|
2020-05-18 07:03:20 +00:00
|
|
|
last = chars[-1]
|
|
|
|
while len(chars) % self.break_key != 0:
|
|
|
|
chars.append(last)
|
2019-02-21 16:19:28 +00:00
|
|
|
|
2020-05-18 07:03:20 +00:00
|
|
|
return "".join(chars)
|
2019-10-05 05:14:13 +00:00
|
|
|
|
2020-05-18 07:03:20 +00:00
|
|
|
def encrypt(self, text: str) -> str:
|
|
|
|
"""
|
2020-05-18 11:05:51 +00:00
|
|
|
>>> hill_cipher = HillCipher(numpy.array([[2, 5], [1, 6]]))
|
2020-05-18 07:03:20 +00:00
|
|
|
>>> hill_cipher.encrypt('testing hill cipher')
|
|
|
|
'WHXYJOLM9C6XT085LL'
|
2020-05-18 11:05:51 +00:00
|
|
|
>>> hill_cipher.encrypt('hello')
|
|
|
|
'85FF00'
|
2020-05-18 07:03:20 +00:00
|
|
|
"""
|
2020-03-04 12:40:28 +00:00
|
|
|
text = self.process_text(text.upper())
|
2019-10-05 05:14:13 +00:00
|
|
|
encrypted = ""
|
2019-02-21 16:19:28 +00:00
|
|
|
|
|
|
|
for i in range(0, len(text) - self.break_key + 1, self.break_key):
|
2019-10-05 05:14:13 +00:00
|
|
|
batch = text[i : i + self.break_key]
|
2021-04-04 05:22:12 +00:00
|
|
|
vec = [self.replace_letters(char) for char in batch]
|
|
|
|
batch_vec = numpy.array([vec]).T
|
2019-10-05 05:14:13 +00:00
|
|
|
batch_encrypted = self.modulus(self.encrypt_key.dot(batch_vec)).T.tolist()[
|
|
|
|
0
|
|
|
|
]
|
2020-05-18 07:03:20 +00:00
|
|
|
encrypted_batch = "".join(
|
2020-05-18 11:05:51 +00:00
|
|
|
self.replace_digits(num) for num in batch_encrypted
|
2020-05-18 07:03:20 +00:00
|
|
|
)
|
2019-02-21 16:19:28 +00:00
|
|
|
encrypted += encrypted_batch
|
|
|
|
|
|
|
|
return encrypted
|
|
|
|
|
2021-04-04 05:22:12 +00:00
|
|
|
def make_decrypt_key(self) -> numpy.ndarray:
|
2020-05-18 07:03:20 +00:00
|
|
|
"""
|
2020-05-18 11:05:51 +00:00
|
|
|
>>> hill_cipher = HillCipher(numpy.array([[2, 5], [1, 6]]))
|
2020-05-18 07:03:20 +00:00
|
|
|
>>> hill_cipher.make_decrypt_key()
|
2020-11-19 16:31:31 +00:00
|
|
|
array([[ 6, 25],
|
|
|
|
[ 5, 26]])
|
2020-05-18 07:03:20 +00:00
|
|
|
"""
|
2019-02-21 16:19:28 +00:00
|
|
|
det = round(numpy.linalg.det(self.encrypt_key))
|
2019-10-05 05:14:13 +00:00
|
|
|
|
2019-02-21 16:19:28 +00:00
|
|
|
if det < 0:
|
|
|
|
det = det % len(self.key_string)
|
|
|
|
det_inv = None
|
|
|
|
for i in range(len(self.key_string)):
|
|
|
|
if (det * i) % len(self.key_string) == 1:
|
|
|
|
det_inv = i
|
|
|
|
break
|
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
inv_key = (
|
|
|
|
det_inv
|
|
|
|
* numpy.linalg.det(self.encrypt_key)
|
|
|
|
* numpy.linalg.inv(self.encrypt_key)
|
|
|
|
)
|
2019-02-21 16:19:28 +00:00
|
|
|
|
2020-05-18 11:05:51 +00:00
|
|
|
return self.to_int(self.modulus(inv_key))
|
2019-10-05 05:14:13 +00:00
|
|
|
|
2020-05-18 07:03:20 +00:00
|
|
|
def decrypt(self, text: str) -> str:
|
|
|
|
"""
|
2020-05-18 11:05:51 +00:00
|
|
|
>>> hill_cipher = HillCipher(numpy.array([[2, 5], [1, 6]]))
|
2020-05-18 07:03:20 +00:00
|
|
|
>>> hill_cipher.decrypt('WHXYJOLM9C6XT085LL')
|
|
|
|
'TESTINGHILLCIPHERR'
|
2020-05-18 11:05:51 +00:00
|
|
|
>>> hill_cipher.decrypt('85FF00')
|
|
|
|
'HELLOO'
|
2020-05-18 07:03:20 +00:00
|
|
|
"""
|
2021-04-04 05:22:12 +00:00
|
|
|
decrypt_key = self.make_decrypt_key()
|
2020-03-04 12:40:28 +00:00
|
|
|
text = self.process_text(text.upper())
|
2019-10-05 05:14:13 +00:00
|
|
|
decrypted = ""
|
2019-02-21 16:19:28 +00:00
|
|
|
|
|
|
|
for i in range(0, len(text) - self.break_key + 1, self.break_key):
|
2019-10-05 05:14:13 +00:00
|
|
|
batch = text[i : i + self.break_key]
|
2021-04-04 05:22:12 +00:00
|
|
|
vec = [self.replace_letters(char) for char in batch]
|
|
|
|
batch_vec = numpy.array([vec]).T
|
|
|
|
batch_decrypted = self.modulus(decrypt_key.dot(batch_vec)).T.tolist()[0]
|
2020-05-18 07:03:20 +00:00
|
|
|
decrypted_batch = "".join(
|
2020-05-18 11:05:51 +00:00
|
|
|
self.replace_digits(num) for num in batch_decrypted
|
2020-05-18 07:03:20 +00:00
|
|
|
)
|
2019-02-21 16:19:28 +00:00
|
|
|
decrypted += decrypted_batch
|
|
|
|
|
|
|
|
return decrypted
|
|
|
|
|
|
|
|
|
2021-04-04 05:22:12 +00:00
|
|
|
def main() -> None:
|
2022-10-12 22:54:20 +00:00
|
|
|
n = int(input("Enter the order of the encryption key: "))
|
2019-02-21 16:19:28 +00:00
|
|
|
hill_matrix = []
|
|
|
|
|
|
|
|
print("Enter each row of the encryption key with space separated integers")
|
2022-10-12 22:54:20 +00:00
|
|
|
for _ in range(n):
|
2020-05-18 11:05:51 +00:00
|
|
|
row = [int(x) for x in input().split()]
|
2019-02-21 16:19:28 +00:00
|
|
|
hill_matrix.append(row)
|
|
|
|
|
2020-05-18 11:05:51 +00:00
|
|
|
hc = HillCipher(numpy.array(hill_matrix))
|
2019-02-21 16:19:28 +00:00
|
|
|
|
|
|
|
print("Would you like to encrypt or decrypt some text? (1 or 2)")
|
2020-05-18 11:05:51 +00:00
|
|
|
option = input("\n1. Encrypt\n2. Decrypt\n")
|
2019-10-05 05:14:13 +00:00
|
|
|
if option == "1":
|
2019-02-21 16:19:28 +00:00
|
|
|
text_e = input("What text would you like to encrypt?: ")
|
|
|
|
print("Your encrypted text is:")
|
|
|
|
print(hc.encrypt(text_e))
|
2019-10-05 05:14:13 +00:00
|
|
|
elif option == "2":
|
2019-02-21 16:19:28 +00:00
|
|
|
text_d = input("What text would you like to decrypt?: ")
|
|
|
|
print("Your decrypted text is:")
|
|
|
|
print(hc.decrypt(text_d))
|
2019-10-05 05:14:13 +00:00
|
|
|
|
2019-02-21 16:19:28 +00:00
|
|
|
|
|
|
|
if __name__ == "__main__":
|
2020-05-18 07:03:20 +00:00
|
|
|
import doctest
|
2020-05-18 11:05:51 +00:00
|
|
|
|
2020-05-18 07:03:20 +00:00
|
|
|
doctest.testmod()
|
|
|
|
|
2019-02-21 16:19:28 +00:00
|
|
|
main()
|