cours_progra/bac1/q1/24nov/encryption.py

106 lines
2.5 KiB
Python
Raw Normal View History

2022-12-07 15:32:56 +01:00
def lecture(nom : str) -> str:
"""get all character of a file
:nom: file name
:returns: string of the file's content
"""
with open(nom, 'r') as file:
return file.read()
def nettoyage(texte : str) -> str:
"""clean the text from it's space and uppsercase
:texte: Sentence to cclean
:returns: the string cleaned
"""
texte = texte.lower()
alphabet = 'abcdefghijklmnopqrstuvwxyz'
ret = ''
for char in texte:
if char in alphabet:
ret += char
return ret
def chiffrement_decalage(texte : str, u : int) -> str:
"""Encrypt a string with cesar
:texte: String to encrypt
:u: Key for ceasar encryption
:returns: encrypted text
"""
alphabet = 'abcdefghijklmnopqrstuvwxyz'
decalage = dict()
for k, l in enumerate(alphabet):
decalage[l] = alphabet[(k+u) % len(alphabet)]
ret = ''
for l in texte:
ret += decalage[l]
return ret
def dechiffrement_decalage(texte, u):
"""decrypt text encoded with cesar
:texte: the string to decode
:u: ceasar key to decode
:returns: the string decoded with the key
"""
return chiffrement_decalage(texte, -u)
def chiffrement_substitution(texte, dico):
ret = ''
for l in texte:
if l in dico:
ret += dico[l]
else:
ret += l
return ret
def dechiffrement_substitution(texte, dico):
invert = dict()
for k, v in dico.items():
invert[v] = k
return chiffrement_substitution(texte, invert)
def file_to_dict(filename):
ret = dict()
with open(filename) as f:
for l in f:
ret[l.split()[0]] = l.split()[1]
return ret
if __name__ == "__main__":
import sys
if(len(sys.argv) == 5):
if sys.argv[1] == 'd':
if sys.argv[2] == 'c':
text = nettoyage(lecture(sys.argv[3]))
print(chiffrement_decalage(text, int(sys.argv[4])))
if sys.argv[2] == 'd':
text = nettoyage(lecture(sys.argv[3]))
print(dechiffrement_decalage(text, sys.argv[4]))
if sys.argv[1] == 's':
if sys.argv[2] == 'c':
text = nettoyage(lecture(sys.argv[3]))
dico = file_to_dict(sys.argv[4])
print(chiffrement_substitution(text, dico))
if sys.argv[2] == 'd':
text = nettoyage(lecture(sys.argv[3]))
dico = file_to_dict(sys.argv[4])
print(dechiffrement_substitution(text, dico))