古典密码之简单替换密码

该密码在加密时,将每个明文字母替换为与之唯一对应且不同的字母,解密时逆向查表即可。它与凯撒密码之间的区别是其密码字母表的字母不是简单的移位,而是完全是混乱的,这也使得其破解难度要高于凯撒密码。

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
class SimpleSubstitutionCipher:
def __init__(self):
self.letter_map = {'A':'S', 'B':'H', 'C':'A', 'D':'N', 'E':'B', 'F':'C', 'G':'D', 'H':'E', 'I':'F', 'J':'G', 'K':'I', 'L':'J', 'M':'K', 'N':'L', 'O':'M', 'P':'O', 'Q':'P', 'R':'Q', 'S':'R', 'T':'T', 'U':'V', 'V':'U', 'W':'Z', 'X':'Y', 'Y':'X', 'Z':'W'}

def encryption(self, plaintext, key):
'''
加密函数
'''
plaintext = plaintext.upper()
cyphertext = []
for i in plaintext:
if i.isalpha():
cyphertext.append(self.letter_map[i.upper()])
else:
cyphertext.append(i)
return ''.join(cyphertext)

def decryption(self, cyphertext, key):
'''
解密函数
'''
letter_map2 = dict(zip(self.letter_map.values(), self.letter_map.keys()))
cyphertext = cyphertext.upper()
plaintext = []
for i in cyphertext:
if i.isalpha():
plaintext.append(letter_map2[i.upper()])
else:
plaintext.append(i)
return ''.join(plaintext)

t_plain = '12.25 HappyBirthday!'
t_key = 3
t = SimpleSubstitutionCipher()
print('明文是:', t_plain)
t_cypher = t.encryption(t_plain, t_key)
print('密文是:', t_cypher)
t_result = t.decryption(t_cypher, t_key)
print('解密结果是:', t_result)