python playfair加密(如有错误,请留言指正)

 1 import numpy
 2 key_word = str.upper(input('请输入秘钥:'))
 3 key_set = set()
 4 for i in key_word:
 5     if i.isalpha():
 6         key_set.add(i)
 7 key_set = list(key_set)
 8 key_set.sort(key=key_word.index)
 9 for i in range(26):
10     ch = chr(i+0x41)
11     if ch not in key_set:
12         key_set.append(ch)
13 key_set.remove('J')
14 
15 table = numpy.array(key_set)
16 table = numpy.reshape(table,(5,5))
17 model = int(eval(input('请输入填充模式(0:按列,1:按行):')))
18 if model == 0:
19     table = table.T#by column
20 else:
21     pass
22 print(r'''密钥矩阵(i/j同位):
23 {}'''.format(table))
24 
25 mes = str.upper(input('请输入明文:'))
26 M = []
27 for i in mes:
28     if i.isalpha():
29         M.append(i)
30 try:
31     M[M.index('J')] = 'I'
32 except:
33     pass
34 
35 def yjudge(table,ra,ca,rb,cb):
36     if ra == rb:
37         return 1
38     elif ca == cb:
39         return 2
40     else:
41         return 3
42 
43 
44 i = 0
45 C = ''
46 while True:
47     len_m = len(M)
48     left = len_m - i
49     if left == 0:
50         break
51     elif left == 1:
52         M.append('X')
53     elif M[i] == M[i+1]:
54         M.insert(i+1,'X')
55     else:
56         pass
57     ra,ca = numpy.where(table == M[i])
58     ra = ra[0]
59     ca = ca[0]
60     rb,cb = numpy.where(table == M[i+1])
61     rb = rb[0]
62     cb = cb[0]
63     #print(table[ra,ca],table[rb,cb])
64     ytype = yjudge(table,ra,ca,rb,cb)
65     #print(ytype)
66     if ytype == 1:#同行在右侧
67         C = C+table[ra,(ca+1)%5]
68         C = C+table[rb,(cb+1)%5]
69     elif ytype == 2:#同列在下侧
70         C = C+table[(ra+1)%5,ca]
71         C = C+table[(rb+1)%5,cb]
72     else:#不同行不同列,取同行的那个角
73         C = C+table[ra,cb]
74         C = C+table[rb,ca]
75     i += 2
76 print(r'''密文:{}'''.format(C))

测试样例(同wikipedia):

请输入秘钥:playfair example
请输入填充模式(0:按列,1:按行):1
密钥矩阵(i/j同位):
[['P' 'L' 'A' 'Y' 'F']
 ['I' 'R' 'E' 'X' 'M']
 ['B' 'C' 'D' 'G' 'H']
 ['K' 'N' 'O' 'Q' 'S']
 ['T' 'U' 'V' 'W' 'Z']]
请输入明文:Hide the gold in the tree stump
密文:BMODZBXDNABEKUDMUIXMMOUVIF
posted @ 2018-01-25 14:58  ywsswy  阅读(363)  评论(0编辑  收藏  举报