cryptanalysis/decryptCaesar.py
2023-10-02 18:34:52 +02:00

62 lines
1.8 KiB
Python

# coding: utf-8
from argparse import ArgumentParser
import matplotlib.pyplot as plt
from functions import readFile
def checkArguments():
args = ArgumentParser(description='Cryptanalyst')
args.add_argument('-f', '--filename', help='Text to analyze')
return args.parse_args()
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 (1, 27):
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)
if __name__ == "__main__":
args = checkArguments()
cipherFile = None
if args.filename:
cipherFile = readFile(args.filename)
decryptCaesarText(cipherFile)