| 44 | |
| 45 | |
| 46 | class HillCipher: |
| 47 | key_string = string.ascii_uppercase + string.digits |
| 48 | # This cipher takes alphanumerics into account |
| 49 | # i.e. a total of 36 characters |
| 50 | |
| 51 | # take x and return x % len(key_string) |
| 52 | modulus = np.vectorize(lambda x: x % 36) |
| 53 | |
| 54 | to_int = np.vectorize(round) |
| 55 | |
| 56 | def __init__(self, encrypt_key: np.ndarray) -> None: |
| 57 | """ |
| 58 | encrypt_key is an NxN numpy array |
| 59 | """ |
| 60 | self.encrypt_key = self.modulus(encrypt_key) # mod36 calc's on the encrypt key |
| 61 | self.check_determinant() # validate the determinant of the encryption key |
| 62 | self.break_key = encrypt_key.shape[0] |
| 63 | |
| 64 | def replace_letters(self, letter: str) -> int: |
| 65 | """ |
| 66 | >>> hill_cipher = HillCipher(np.array([[2, 5], [1, 6]])) |
| 67 | >>> hill_cipher.replace_letters('T') |
| 68 | 19 |
| 69 | >>> hill_cipher.replace_letters('0') |
| 70 | 26 |
| 71 | """ |
| 72 | return self.key_string.index(letter) |
| 73 | |
| 74 | def replace_digits(self, num: int) -> str: |
| 75 | """ |
| 76 | >>> hill_cipher = HillCipher(np.array([[2, 5], [1, 6]])) |
| 77 | >>> hill_cipher.replace_digits(19) |
| 78 | 'T' |
| 79 | >>> hill_cipher.replace_digits(26) |
| 80 | '0' |
| 81 | >>> hill_cipher.replace_digits(26.1) |
| 82 | '0' |
| 83 | """ |
| 84 | return self.key_string[int(num)] |
| 85 | |
| 86 | def check_determinant(self) -> None: |
| 87 | """ |
| 88 | >>> hill_cipher = HillCipher(np.array([[2, 5], [1, 6]])) |
| 89 | >>> hill_cipher.check_determinant() |
| 90 | """ |
| 91 | det = round(np.linalg.det(self.encrypt_key)) |
| 92 | |
| 93 | if det < 0: |
| 94 | det = det % len(self.key_string) |
| 95 | |
| 96 | req_l = len(self.key_string) |
| 97 | if greatest_common_divisor(det, len(self.key_string)) != 1: |
| 98 | msg = ( |
| 99 | f"determinant modular {req_l} of encryption key({det}) " |
| 100 | f"is not co prime w.r.t {req_l}.\nTry another key." |
| 101 | ) |
| 102 | raise ValueError(msg) |
| 103 | |