古典密码之仿射密码

仿射密码将字母系统中所有字母都使用一个简单数学方程加密,对应至数值,再把对应数值转回字母。

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
import string

class AffineCipher:
def __init__(self):
self.letter_map = string.ascii_letters

def encryption(self, plaintext, k1, k2):
'''
加密函数
'''
cyphertext = []
for i in plaintext:
if i.isalpha():
if i.isupper():
num = ord(i) - ord('A') + 26
cyphertext.append(self.letter_map[(num*k1 + k2) % 52])
if i.islower():
num = ord(i) - ord('a')
cyphertext.append(self.letter_map[(num*k1 + k2) % 52])
else:
cyphertext.append(i)
return ''.join(cyphertext)

def decryption(self, cyphertext, k1, k2):
'''
解密函数
'''
for i in range(52):
if k1*i % 52==1:
inv = i
break
plaintext = []
for i in cyphertext:
if i.isalpha():
if i.isupper():
num = ord(i) - ord('A') + 26
plaintext.append(self.letter_map[inv*(num - k2) % 52])
if i.islower():
num = ord(i) - ord('a')
plaintext.append(self.letter_map[inv*(num - k2) % 52])
else:
plaintext.append(i)
return ''.join(plaintext)

t_plain = '12.25 HappyBirthday!'
a = 5 # k1的范围0~51之间
b = 29 # k2的范围0~51之间
t = AffineCipher()
print('明文是:', t_plain)
t_cypher = t.encryption(t_plain, a, b)
print('密文是:', t_cypher)
t_result = t.decryption(t_cypher, a, b)
print('解密结果是:', t_result)
0%