Sunday, December 18, 2011

Shifting decipher (probability based)

A little experiment using probability to find out the shifting applied to encrypt a message.


dicctionary = ['the', "and","by","to", "in", "out"]
message = "Esp qtcde nzyqpcpynp zy esp ezatn zq Lcetqtntlw\
Tyepwwtrpynp hld spwo le Olcexzfes Nzwwprp ty estd jplc."

separation_characters =[' ','.']

score = []

m = [x.lower() for x in message]
m = "".join(m)
for i in range(27):
sh = []
for x in m:
if x in separation_characters:
sh.append(x)
else:
sh.append(chr(((ord(x)+i-97)%26 + 97)))
sh = "".join(sh)
words = sh.split(" ")
print words
found = 0
for w in words:
if w in dicctionary:
found = found + 1
print found/len(words)
score.append(found/float(len(words)))
print score
maxval = 0
maxindex = 0
for i in range(len(score)):
if score[i] > maxval:
maxval = score[i]
maxindex = i
print "SHIFT%d"%(maxindex)
sh = []
for x in m:
if x in separation_characters:
sh.append(x)
else:
sh.append(chr(((ord(x)+maxindex-97)%26 + 97)))
print "".join(sh)