104 lines
2.9 KiB
Python
104 lines
2.9 KiB
Python
# coding: utf-8
|
|
|
|
from argparse import ArgumentParser
|
|
import matplotlib.pyplot as plt
|
|
from lorem import text as loremtext
|
|
from functions import readFile
|
|
|
|
|
|
def checkArguments():
|
|
args = ArgumentParser(description='Cryptanalyst')
|
|
args.add_argument('-f', '--filename', help='Text to analyze')
|
|
args.add_argument('-s', '--stats', help='Statistics', action='store_true')
|
|
args.add_argument('-d', '--decrypt', help='Decrypt Caesar text', action='store_true')
|
|
return args.parse_args()
|
|
|
|
def stats(file=None):
|
|
"""
|
|
This function get a stats of all letter occurrence in a text
|
|
"""
|
|
if file is None:
|
|
dataFile = loremtext()
|
|
else:
|
|
dataFile = file
|
|
|
|
#dataFile = str()
|
|
#for d in text:
|
|
# u = unidecode(d.lower(), 'utf-8')
|
|
# dataFile += sub(r'[^a-z]', '', u)
|
|
|
|
lettersOccurence = []
|
|
|
|
# Init our tab
|
|
for i in range (0, 26):
|
|
lettersOccurence.append(0)
|
|
|
|
letterToAscii = ord('a') # Get the ASCII code
|
|
for letter in dataFile:
|
|
l = ord(letter) - letterToAscii
|
|
if l >= 0 and l <= 26:
|
|
lettersOccurence[l] += 1
|
|
|
|
x = [chr(letter + 65) for letter in range(0, 26)]
|
|
y = [tmp for tmp in lettersOccurence]
|
|
|
|
largeur = 0.5
|
|
plt.bar(x, y, largeur)
|
|
plt.show()
|
|
|
|
def decryptCaesarText(cipherFile):
|
|
"""
|
|
This function breach the caesar ciphertext with all key
|
|
"""
|
|
if cipherFile is None:
|
|
return
|
|
|
|
letterAToAscii = ord('A') # Get the ASCII code
|
|
letterZToAscii = ord('Z') # Get the ASCII code
|
|
letteraToAscii = ord('a') # Get the ASCII code
|
|
letterzToAscii = ord('z') # Get the ASCII code
|
|
for key in range (0, 26):
|
|
foo = []
|
|
for line in cipherFile:
|
|
newLine = str()
|
|
for letter in line:
|
|
letter = letter.upper()
|
|
letterAscii = ord(letter)
|
|
if letterAscii >= letterAToAscii and letterAscii <= letterZToAscii:
|
|
newLetter = getNewLetter(letterAscii, letterAToAscii, key)
|
|
elif letterAscii >= letteraToAscii and letterAscii <= letterzToAscii:
|
|
newLetter = getNewLetter(letteraToAscii, key)
|
|
else:
|
|
newLetter = letter
|
|
|
|
newLine = newLine + newLetter
|
|
|
|
foo.append(newLine)
|
|
|
|
print(f"key: {key}")
|
|
print(foo)
|
|
|
|
def getNewLetter(letterAscii, letterToAscii, key):
|
|
"""
|
|
This function return the new letter and we substract with the key.
|
|
The function return the new letter into a char
|
|
"""
|
|
letterAscii = letterAscii - letterToAscii
|
|
res = ((letterAscii - key) % 26) + letterToAscii
|
|
return chr(res)
|
|
|
|
def main():
|
|
args = checkArguments()
|
|
cipherFile = None
|
|
|
|
if args.filename:
|
|
cipherFile = readFile(args.filename)
|
|
|
|
if args.stats:
|
|
stats(cipherFile)
|
|
if args.decrypt:
|
|
decryptCaesarText(cipherFile)
|
|
|
|
if __name__ == "__main__":
|
|
main()
|