-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmbxor.py
65 lines (51 loc) · 1.62 KB
/
mbxor.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
import binascii
import collections
import operator
def cmp(a, b):
return ((a > b) - (a < b))
def readFile(filename):
with open(filename, "r") as fp:
message = fp.readline().strip()
return message
def readFileHex(filename):
return binascii.unhexlify(readFile(filename))
debug = False
def dprint(string):
if(debug):
print(string)
def singlebyteXOR(sbkey, message):
plaintext = ""
for c in message:
plaintext += chr(c ^ sbkey)
return plaintext
def singleByteFreq(input, englishSample):
matches = {}
englishCounter = collections.Counter(englishSample.lower())
ENGLISH = sorted(englishCounter.items(), key=lambda i: i[1], reverse=True)
ENGLISH7 = []
dprint(ENGLISH)
for i in range(7):
ENGLISH7.append(ENGLISH[i][0])
dprint(ENGLISH7)
for b in range(255):
plaintext = singlebyteXOR(b, input)
dprint(plaintext)
analysistext = collections.Counter(plaintext.lower())
analSort = sorted(analysistext.items(), key=lambda i: i[1], reverse=True)
analSort7 = []
for i in range(7):
analSort7.append(analSort[i][0])
dprint(analSort7)
count = 0
for i in range(7):
if analSort7[i] in ENGLISH7:
count = count + 1
matches[b] = count
dprint(matches)
matchesSorted = sorted(matches.items(), key=lambda x: x[1], reverse=True)
dprint(matchesSorted)
output = singlebyteXOR(matchesSorted[0][0], input)
print(output)
inputtext = readFileHex("file.txt")
englishSample = readFile("english.txt")
singleByteFreq(inputtext, englishSample)