-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcrackvig.py
executable file
·70 lines (48 loc) · 1.7 KB
/
crackvig.py
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
#!/usr/bin/env python
import string
import sys
def stack(ciphertext,maxkey=10):
#ciphertext is assumed to be a lowercase string with no spaces in it
ic = {}
for keylen in range(1,maxkey+1):
ics = []
for i in range(0,keylen):
column = ciphertext[i:-1:keylen]
ics.append(getIC(column))
ic[keylen] = sum(ics)/len(ics)
return ic
def getIC(column):
N = len(column)
nc = len(string.lowercase)
freqs = dict(zip(string.lowercase,[0 for i in range(0,26)]))
numer = 0
for c in string.lowercase:
freqs[c] = column.count(c)
numer = column.count(c) * (column.count(c)-1)
ic = float(numer)/(N*(N-1)/nc)
return ic
def crack(ciphertext):
ciphertext = ciphertext.lower()
mic = getIC(ciphertext)
n = len(ciphertext)
mguess = (0.027*n)/((n-1)*mic-0.038*n+0.065)
print 'Guessed key length is %.1f' % mguess
# ic_exp = 1.73
# N = len(ciphertext)
# nc = len*string.lowercase
# #count frequencies of each letter
# freqs = dict(zip(string.lowercase,[0 for i in range(0,26)]))
# numer = 0
# for c in string.lowercase:
# freqs[c] = ciphertext.count(c)
# numer = ciphertext.count(c) * (ciphertext.count(c)-1)
# ic = float(numer)/(N*(N-1)/nc)
# keylen = (kp-kr)/(ko-kr)
if __name__ == '__main__':
ciphertext = 'QPWKALVRXCQZIKGRBPFAEOMFLJMSDZVDHXCXJYEBIMTRQWNMEAIZRVKCVKVLXNEICFZPZCZZHKMLVZVZIZRRQWDKECHOSNYXXLSPMYKVQXJTDCIOMEEXDQVSRXLRLKZHOV'
ciphertext = ciphertext.lower()
icdict = stack(ciphertext)
print icdict
sys.exit(0)
#ciphertext = 'HLKOSNTVPDJMWPUYPAGI'.lower()
crack(ciphertext)