from C1 import encodeHexStrToRawBytes
from C3 import decryptMessage, decryptWithChiSquare
def readnThFile(fileName, pos):
'''
read the nth line of a file,
removes the '\n' characters
and return the newer line
'''
i = 0
with open(fileName, "r") as text:
for line in text:
line = line.replace('\n', '')
if i == pos:
return line
i += 1
return line
rawBytesStr = list()
results = list()
# read the file with the strings given to the challenge
# encode it to rawBytes, decrypt it with Chi Square function
#and save the result to results list
bestIndex = 0
bestKey = 0
minimumResult = 0
i = 0
with open("C4_strings.txt", "r") as text:
for line in text:
line = line.replace('\n', '')
rawBytesStr = encodeHexStrToRawBytes(line)
results = decryptWithChiSquare(rawBytesStr)
if i == 0:
minimumResult = min(results[0], key=results[0].get)
bestKey = results[1]
bestIndex = i
else:
if minimumResult > min(results[0], key=results[0].get):
minimumResult = min(results[0], key=results[0].get)
bestKey = results[1]
bestIndex = i
i += 1
#decryptMessage(rawBytesStr, decryptWithChiSquare(rawBytesStr)[1])
string = readnThFile("C4_strings.txt", bestIndex)
rawBytesStr = encodeHexStrToRawBytes(string)
print(decryptMessage(rawBytesStr, bestKey))