NEKO

Vigenere加解密and重合指数破解

2017/12/15
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
import string
import re
#维吉尼亚解密
def Decode():
cipher=input("请输入密文:").lower() #密文转换为小写
key=input("请输入密钥:")
letters = string.ascii_lowercase
clear = ''
for i in range(len(cipher)):
j = i % len(key)
k = letters.index(key[j])
c = letters.index(cipher[i])
if c<k:
c+=26
clear += letters[c-k]
print("明文为:",clear)
print()
#维吉尼亚加密
def Encode():

clear = input("请输入明文:").lower().replace(' ','') #明文转换为小写并去除空格
clear = re.sub("[\s+\.\!\/_,$%^*(\"\'-?]+|[+—!,。?、~@#¥%……&*()]+", '', clear) #正则去除标点

key = input("请输入密钥:")
letters = string.ascii_lowercase
cipher=''
for i in range(len(clear)):
j=i%len(key)
k=letters.index(key[j])
c=letters.index(clear[i])
cipher+=letters[(k+c)%26]
print("密文为:",cipher)
print()

#计算重合指数
def Findexp(str):
rate = []
for i in range(ord('A'),ord('Z')+1):
rate.append(str.count(chr(i))) #rate里存放26字母出现的次数
p=0
for i in rate:
p=p+i*(i-1)
result=p/(len(str)*(len(str)-1))
return float('%.4f'%result)

#计算密钥
def Findkey(str):
normalrate = [0.082, 0.015, 0.028, 0.043, 0.127, 0.022, 0.02, 0.061, 0.07, 0.002, 0.008, 0.04, 0.024, 0.067, 0.075,
0.019, 0.001, 0.06, 0.063, 0.091, 0.028, 0.01, 0.023, 0.001, 0.02, 0.001] #正常英文中26个字母出现的频率
#循环用26个字母当做密钥来解密分组,测试重合指数
for j in range(26):
letters = string.ascii_uppercase
newstr = ''
for i in range(len(str)):

c = letters.index(str[i])
if c < j:
c += 26
newstr += letters[c - j]
rate = []
for i in range(ord('A'), ord('Z')+1):
rate.append(newstr.count(chr(i))/len(newstr))#此处的rate存放的是26个字母出现的频率
p = 0#重合指数
for i in range(26):
p=p+rate[i]*normalrate[i]

#大概范围
if p>=0.055 and p<=0.072:
return chr(ord('A')+j) #求出密钥的1位


def VCDecode():
cipher=input('请输入密文:')
cipher = re.sub("[\s+\.\!\/_,$%^*(+\"\']+|[+——!,。?、~@#¥%……&*()]+", '', cipher).upper()
#寻找分组长度并得到分组
for d in range(1, 100):
sum=0
strgroup=[]
for j in range(d):
strgroup.append(cipher[j::d])
sum+=Findexp(cipher[j::d])
if sum/d>0.06 and sum/d<0.072:
break

key=''
for i in range(d):
key+=Findkey(strgroup[i]) #按位得出秘钥

#解出秘钥后,下面解密密文,没直接调用写好的解密函数,因为那个解密函数里有用户交互环节
letters = string.ascii_uppercase
clear = ''
for i in range(len(cipher)):
j = i % len(key)
k = letters.index(key[j])
c = letters.index(cipher[i])
if c < k:
c += 26
clear += letters[c - k]
print("秘钥为:",key.lower())
print("明文为:", clear.lower())
print()

if __name__=="__main__":
while True:
choice = input("请输入类型:\n1:加密\n2:解密\n3:重合互指数法破解Vigernere\n4:退出\n")
if choice=='1':
Encode()
elif choice=='2':
Decode()
elif choice=='3':
VCDecode()
elif choice=='4':
break
else:
print('请输入1-4')



原文作者: n3k0

发表日期: December 15th 2017, 6:21:43

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

CATALOG