1、ceasar

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

cipher="zhongguo" #明文
move=3 #移位数
t="" #密文
for i in cipher:
if 'a'<=i<='z':
t+=chr(ord('a')+((ord(i)-ord('a')+move)%26))
elif 'A'<=i<='Z':
t+=chr(ord('A')+((ord(i)-ord('A')+move)%26))
else:
t+=i
print(t)

#如果要解密的话,秘钥变为负数
#如zhongguo加密后得到ckrqjjxr
#现需要解密,则直接将move取-3即可

2、affine

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
#加密
cipher='zhongguo'#明文
t=''#密文
a=3
b=4 #E(x)=ax+b,gcd(a,26)
for i in cipher:
if 'a'<=i<='z':
t+=chr(ord('a')+((a*(ord(i)-ord('a'))+b)%26))
elif 'A'<=i<='Z':
t+=chr(ord('A')+((a*(ord(i)-ord('A'))+b)%26))
else:
t+=i
print(t)


#解密
t = 'bzurwwmu' # 密文
cipher = '' # 明文
a = 3
b = 4
for i in range(1, 26):
if (i*a) % 26 == 1:
a1 = i
break
for i in t:
if 'a' <= i <= 'z':
cipher += chr(ord('a')+((a1*(ord(i)-ord('a')-b)) % 26))
elif 'A' <= i <= 'Z':
cipher += chr(ord('A')+((a1*(ord(i)-ord('A')-b)) % 26))
else:
cipher += i
print(cipher)


3、多表代换密码

先说下这个方法必要的基础知识

因为解密的时候需要矩阵求逆,所以写下方法,这个是最基本的方法

行列式怎么求好像也不太记得了,看个例子应该就能马上想起来了

可逆矩阵另一种比较简单一点的求法