project-euler/059_xor_decryption.py

48 lines
1.5 KiB
Python

#!/usr/bin/env python3
def decrypt():
#genereta tri mestni kluc (mozne so samo male crke)
#decrypta podano besedilo enc_text in ga vrze v percentege
#ce je vec kot 50% besed angleskih ga doda na list results
eng=text()
results=[]
with open("data/059_cipher.txt") as f:
r=f.read()
enc_text=list(map(int,r.split(",")))
key=[]
for a in range(97,123):
for b in range(97,123):
for c in range(97,123):
dec_text=""
for char in range(0,len(enc_text)-2,3):
if enc_text[char]^a in range(0, 128):
dec_text+=chr(enc_text[char]^a)
if enc_text[char+1]^b in range(0, 128):
dec_text+=chr(enc_text[char+1]^b)
if enc_text[char+2]^c in range(0, 128):
dec_text+=chr(enc_text[char+2]^c)
if percentege(dec_text.upper().split(" "),eng)>50:
results.append(dec_text)
key.append([a,b,c])
return results[0]
def text():
with open("data/098_words.txt") as f:
r=f.read()
r=r.split('","')
r[0]=r[0][1:]
r[-1]=r[-1][:-1]
return r
def percentege(x,y):
#x je besedilo, y je list vecine ang besed, vrne ujemanje obeh v %
total=0
for i in x:
if i in y:
total+=1
return (float(total)/len(x))*100
if __name__ == '__main__':
text = decrypt()
print(sum(map(ord, text)))