@SureshPatil/

Hill Cipher

Python

No description

fork
loading
Files
  • main.py
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
def c2i(c, alphabet):
  return alphabet.index(c)
    #"""Returns the index of c in the string alphabet, starting at 0"""
    # Copy your method from subcipher.py here

def i2c(i, alphabet):
  return alphabet[i]
    #"""Returns the character at index i in alphabet"""
    # Copy your method from subcipher.py here

def prepare_string(s, alphabet):
  newS = ""
  for char in s:
    if char in alphabet.upper() or char in alphabet.lower(): 
      newS += char.upper()
  return newS

def mod_inverse(a, m):
  for x in range(1,m):
    if((a*x)%m == 1):
      return x
  #print("No modular inverse found!")
  return -1

def determinant(matrix):
  return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]

def isNotCoprime(a, lenAlpha):
  if lenAlpha % a == 0:
    return True
  for x in range(2, a):
    if lenAlpha % x == 0 and a % x == 0:
      return True
  return False

def inverseOfMatrix(matrix, m):
  det = determinant(matrix)%m
  modInvDet = mod_inverse(det, m)
  if modInvDet == -1:
    return -1
  newMatrix = [[(matrix[1][1]*modInvDet)%m, (-modInvDet*matrix[0][1])%m], [(-modInvDet*matrix[1][0])%m, (matrix[0][0]*modInvDet)%m]]
  return newMatrix

def multiply_2x1(matrix1,matrix2, m):
  newmatrix = [(matrix1[0][0]*matrix2[0] + matrix1[0][1]*matrix2[1])%m, (matrix1[1][0]*matrix2[0] + matrix1[1][1]*matrix2[1])%m]
  return newmatrix

def multiply_2x2(matrix1, matrix2, m):
  newmatrix = [[(matrix1[0][0]*matrix2[0][0] + matrix1[0][1]*matrix2[1][0])%m, (matrix1[0][0]*matrix2[0][1] + matrix1[0][1]*matrix2[1][1])%m], [(matrix1[1][0]*matrix2[0][0] + matrix1[1][1]*matrix2[1][0])%m, (matrix1[1][0]*matrix2[0][1] + matrix1[1][1]*matrix2[1][1])%m]]
  return newmatrix

def hill_encode(encMatrix, plaintext, alphabet):
  if inverseOfMatrix(encMatrix, len(alphabet)) == -1:
    return -1
  elif len(plaintext)%2 != 0:
    plaintext += "X"
  ciphertext = ''
  for index in range(0, len(plaintext), 2):
    ogMatrix = [c2i(char, alphabet) for char in plaintext[index:index + 2]]
    cipherMatrix = multiply_2x1(encMatrix, ogMatrix, len(alphabet))
    # print(cipherMatrix)
    for index in cipherMatrix:
      ciphertext += i2c(index, alphabet) 
  return ciphertext

def hill_decode(encMatrix, ciphertext, alphabet):
  invMatrix = inverseOfMatrix(encMatrix, len(alphabet))
  if invMatrix == -1:
    return 'Error: Matrix not Invertible!'
  else:
    plaintext = ''
    for index in range(0, len(ciphertext), 2):
      cipherMatrix = [c2i(char, alphabet) for char in ciphertext[index: index + 2]]
      ogMatrix = multiply_2x1(invMatrix, cipherMatrix, len(alphabet))
      for index in ogMatrix:
        plaintext += i2c(index, alphabet) 
    return plaintext

def find_encMatrix(crib, ciphertext, alphabet):
  for x in range(0, len(crib), 2):
    for y in range(x+2, len(crib), 2):
      pairs = [[c2i(crib[x],alphabet), c2i(crib[y], alphabet)], [c2i(crib[x+1], alphabet), c2i(crib[y+1], alphabet)]]
      invOfPairs = inverseOfMatrix(pairs, len(alphabet))
      if invOfPairs != -1:
        cipherPairs = [[c2i(ciphertext[x],alphabet), c2i(ciphertext[y], alphabet)], [c2i(ciphertext[x+1], alphabet), c2i(ciphertext[y+1], alphabet)]]
        encMatrix = multiply_2x2(cipherPairs, invOfPairs, len(alphabet))
        return encMatrix
  return -1

def hill_solver(crib, ciphertext, alphabet):
  encMatrix = find_encMatrix(crib, ciphertext, alphabet)
  if encMatrix == -1:
    return 'No solution found'
  print(encMatrix)
  plaintext = hill_decode(encMatrix, ciphertext, alphabet)
  return plaintext

# alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

# print('2.')
# encMatrix = [[4, 3], [5, 6]]
# print('a.', inverseOfMatrix(encMatrix, len(alpha)))
# plaintext_1 = prepare_string('Lester S. Hill had a brilliant idea for a cipher', alpha)
# ciphertext_1 = hill_encode(encMatrix, plaintext_1, alpha)
# print('b.', ciphertext_1)

# ciphertext_2 = prepare_string('MVTHVEQHWAIKZRBIPGQTQBVEODDATWKFSVYR', alpha)
# plaintext_1 = hill_decode(encMatrix, ciphertext_2, alpha)
# print('c.', plaintext_1)

# possibilities = []
# for c1 in alpha:
#   for c2 in alpha:
#     possibilities.append(c1+c2)

# print('3.')
# encMatrix = [[7, 6],[4, 13]]
# for poss in possibilities:
#   if poss == hill_encode(encMatrix, poss, alpha):
#     print(poss)

# print('4.')
# count = 0
# for a in range(len(alpha)):
#   for b in range(len(alpha)):
#     for c in range(len(alpha)):
#       for d in range(len(alpha)):
#         matrix = [[a, b], [c, d]]
#         if inverseOfMatrix(matrix, len(alpha)) != -1:
#           count += 1
# print(count - 1)

# print('5.')
# count = 0
# for a in range(27):
#   for b in range(27):
#     for c in range(27):
#       for d in range(27):
#         matrix = [[a, b], [c, d]]
#         if inverseOfMatrix(matrix, 27) != -1:
#           count += 1
# print(count - 1)

# print('6.')
# alpha2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!"
# encMatrix = [[34, 15], [29, 4]]
# plaintext_3 = prepare_string("C01DB100D3DC0D3R5!", alpha2)
# print(plaintext_3)
# ciphertext_3 = hill_encode(encMatrix, plaintext_3, alpha2)
# print(ciphertext_3)
# plaintext_3 = hill_decode(encMatrix, ciphertext_3, alpha2)
# print(plaintext_3)

# print('8.')
# print('a.', hill_solver('DEAR', 'XBDYMNLMFEMAMCYXIEUGUIWKXEFZODSO', alpha))
# print('b.', hill_solver('FLEWIN', 'GXIGBKYPCIGAKKRAUSFEVBGG', alpha))
# print('c.', hill_solver('ITOLDY', 'DQJIFHSMBMSMTFSTWEPPWHJWOSULQE', alpha))
# print('d.', hill_solver('ILOOKATY', 'RMYAAMRHMYRSDPSAMRRCXCBIFBFNMRBYQAFLJSNUAC', alpha))

newAlpha = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz.!?, ;:'
encMatrix = [[27, 13], [5, 14]]
plaintext = 'I am the action...the deed of our king' 
ciphertext_1 = hill_encode(encMatrix, plaintext, newAlpha)
print(ciphertext_1)

newAlpha = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz.!?, ;:'
encMatrix = [[27, 13], [5, 14]]
ciphertext = 'tT;agAZMXpCQrKMOoytKeATpnp' 
plaintext_1 = hill_decode(encMatrix, ciphertext, newAlpha)
print(plaintext_1)

print(hill_solver('I rallied', 'UmOZMtFtLpY.LpQotffS,vqkzQsUj,:GOHOZkBDSPhfS:jvg;gZDtDEPOLb;TGNFOZEbdSw!!aZ,DafStTz;uTK?tRuWPhgU,eLpTGNFnUVXA:Y.LpTGNFOZEb;JWVTGNFOZEbh.', newAlpha))

alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

plaintext = "FGGF"

# dictionary = {}
# bool = False
# for x in range(0, 26):
#   for y in range(0, 26):
#     for z in range(0, 26):
#       for a in range(0, 26):
#         encMatrix = [[x, y], [z, a]]
#         ciphertext_1 = hill_encode(encMatrix, plaintext, alpha)
#         if ciphertext_1 in dictionary:
#           print(encMatrix)
#           print(dictionary[ciphertext_1])
#           print(ciphertext_1)
#           bool = True
#           break
#         if ciphertext_1 != -1:
#           dictionary[ciphertext_1] = encMatrix
#       if(bool):
#         break
#     if(bool):
#       break
#   if(bool):
#     break

print(inverseOfMatrix([[25, 25], [25, 18]], 26))