https://projecteuler.net/problem=59
Each character on a computer is assigned a unique code and the preferred standard is ASCII (American Standard Code for Information Interchange). For example, uppercase A = 65, asterisk (*) = 42, and lowercase k = 107.
A modern encryption method is to take a text file, convert the bytes to ASCII, then XOR each byte with a given value, taken from a secret key. The advantage with the XOR function is that using the same encryption key on the cipher text, restores the plain text; for example, 65 XOR 42 = 107, then 107 XOR 42 = 65.
For unbreakable encryption, the key is the same length as the plain text message, and the key is made up of random bytes. The user would keep the encrypted message and the encryption key in different locations, and without both "halves", it is impossible to decrypt the message.
Unfortunately, this method is impractical for most users, so the modified method is to use a password as a key. If the password is shorter than the message, which is likely, the key is repeated cyclically throughout the message. The balance for this method is using a sufficiently long password key for security, but short enough to be memorable.
Your task has been made easy, as the encryption key consists of three lower case characters. Using cipher.txt (in this directory), a file containing the encrypted ASCII codes, and the knowledge that the plain text must contain common English words, decrypt the message and find the sum of the ASCII values in the original text.
The following cell shows examples of how to perform XOR in Python and how to go back and forth between characters and integers:
In [272]:
assert 65 ^ 42 == 107
assert 107 ^ 42 == 65
assert ord('a') == 97
assert chr(97) == 'a'
Certain functions in the itertools module may be useful for computing permutations:
In [273]:
import itertools
In [2]:
# YOUR CODE HERE
def Decryptor(key, filename):
file = open(filename, "r")
filestring = file.read()
#http://stackoverflow.com/questions/7844118/how-to-convert-comma-delimited-string-to-list-in-python
filelist = filestring.split(",")
full_key = ""
#creates repeated key the length of the file contents (cycle() function would work if i could make it finite)
for n in range(0,int(len(filelist)/len(key)) + 1):
full_key += key
dec_string = ""
for n in range(0,len(filelist)):
dec_string += chr(ord(full_key[n]) ^ int(filelist[n]))
file.close()
return dec_string
In [4]:
Decryptor("slo", "cipher.txt")
Out[4]:
In [276]:
def CheckSpaces(inputstring):
#http://stackoverflow.com/questions/1155617/count-occurrence-of-a-character-in-a-string
spacecount = inputstring.count(" ")
#according to wolfram Alpha, the average length of an english character is 5.
#if there are less than 1/3 of the spaces there should be, the string is probably not english
if spacecount >= len(inputstring)/15:
return True
else:
return False
In [277]:
print(CheckSpaces("I am an english phrase"))
print(CheckSpaces("iamnotanenglishphrase"))
print(CheckSpaces("neitheramibut idohaveatleastonespace"))
In [278]:
def CheckPunctuation(inputstring):
#checks for common punctuation, makes sure they are at the end of a sentence
if "?" in inputstring:
if inputstring.count("? ") < inputstring.count("?") - 1:
return False
if "!" in inputstring:
if inputstring.count("! ") < inputstring.count("!") - 1:
return False
if "," in inputstring:
if inputstring.count(", ") < inputstring.count(","):
return False
#period could possibly be in a decimal number, more lenient
if "." in inputstring:
if inputstring.count(". ") < inputstring.count(".")/2:
return False
#if there's no punctuation per 150 chars, false
if inputstring.count(".") + inputstring.count(",") + inputstring.count("?") + inputstring.count("!") < int(len(inputstring)/150) + 1:
return False
return True
In [279]:
print(CheckPunctuation("This. is? a, sentence. This is another! Are? these. correct?"))
print(CheckPunctuation("Thi?is!not.formatted.correctly. The,sentences.run?together!"))
print(CheckPunctuation("Thishasnosentencesatall"))
In [280]:
def ForbiddenChars(inputstring):
violations = 0
#if rare characters appear too often, not english
for char in inputstring:
if char in ("[]{}_@^<>*|%~&#"):
violations += 1
if violations > len(inputstring)/100:
return False
else:
return True
In [281]:
print(ForbiddenChars(Decryptor("god", "cipher.txt")))
print(ForbiddenChars(Decryptor("abc", "cipher.txt")))
In [282]:
def FindKey(file):
#http://stackoverflow.com/questions/228730/how-do-i-iterate-through-a-string-in-python
from string import ascii_lowercase
text = ""
for a in ascii_lowercase:
for b in ascii_lowercase:
for c in ascii_lowercase:
text = Decryptor(a+b+c, file)
if CheckSpaces(text) == True:
if CheckPunctuation(text) == True:
if ForbiddenChars(text) == True:
print("")
print("Key is " + a + b + c)
print(text)
In [283]:
FindKey("cipher.txt")
In [ ]:
# This cell will be used for grading, leave it at the end of the notebook.