NEKO

仿射加密

2017/12/15

python3:

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
import time
#欧几里得算法
def gcd(a,b):
if b==0:
return a
else:
return gcd(b,a%b)
#扩展欧几里得算法
def egcd(a,b):
if b==0:
return a,1,0
else:
g,x,y=egcd(b,a%b)
return g,y,x-a//b*y

#加密
def encode():
clear = input('请输入密文:')
key1 = int(input('请输入key1:'))
if gcd(key1,26)!=1:
print("key1必须与26互素!")
return
key2 = int(input('请输入key2:'))
cipher=''
for i in clear:
m=key1*(ord(i)-ord('a'))+key2
cipher = cipher + chr(m % 26 + ord('a'))
key_1=egcd(key1,26)[1] #key1的逆
key_2=(-key_1*key2)%26 #解密秘钥的key2
print("解密秘钥为:(%d,%d)\n密文为%s\n"%(key_1,key_2,cipher))

#解密
def decode():
cipher=input('请输入密文:')
key1 = int(input('请输入key1:'))
if gcd(key1,26)!=1:
print("key1必须与26互素!")
return
key2 = int(input('请输入key2:'))
clear=''
for i in cipher:
m=ord(i)-ord('a')
clear=clear+chr((key1*m+key2)%26+97)
print("明文为:",clear)
print()

#用于爆破里的解密
def fdecode(cipher,key1,key2):
clear = ''
for i in cipher:
m = ord(i) - ord('a')
clear = clear + chr((key1 * m + key2) % 26 + 97)
return clear
#测试爆破时间
def Testtime():
print("此爆破用于测试穷举时间")
clear=input("请输入正确的明文:\n")
cipher=input("请输入对应的密文:\n")
print("爆破开始:\nwait...")
starttime=time.time()
for key1 in range(26):
for key2 in range(26):
if clear==fdecode(cipher,key1,key2):
finishtime = time.time()
print("爆破成功,耗时%d秒,秘钥为:(%d,%d)\n" % (finishtime - starttime, key1, key2))
return
print("爆破失败,请输入与明文对应的密文!\n")
#爆破
def Force():
cipher = input("请输入密文:\n")
print("爆破开始:\n")
for key1 in range(26):
for key2 in range(26):
print(fdecode(cipher,key1,key2))
if __name__=='__main__':
while True:
choice = input("请输入类型:\n1:加密\n2:解密\n3:测试爆破时间\n4.爆破\n5:退出\n")
if choice=='1':
encode()
elif choice=='2':
decode()
elif choice=='3':
Testtime()
elif choice=='4':
Force()
elif choice=='5':
break
else:
print('请输入1-5')





原文作者: n3k0

发表日期: December 15th 2017, 4:36:59

发出嘶吼: 没有魔夜2玩我要死了

CATALOG