58 lines
1.4 KiB
Python
Executable file
58 lines
1.4 KiB
Python
Executable file
#!/usr/bin/env python3
|
|
|
|
"""Chiffrement affine"""
|
|
|
|
from inverse import inverser
|
|
from oppose import opposer
|
|
|
|
|
|
def main():
|
|
alphabet = input("Alphabet pour le chiffrement affine, terminez par Entrée : ")
|
|
a, b = input(
|
|
"Clé de chiffrement (deux nombres séparés par un espace, exemple: 2 4) "
|
|
).split(" ")[:2]
|
|
kc = (int(a), int(b))
|
|
|
|
action = input("Chiffrer ou déchiffrer ? ")
|
|
|
|
if action == "chiffrer":
|
|
message = input("Message à chiffrer : ")
|
|
c = chiffrer(message, alphabet, kc)
|
|
print(c)
|
|
elif action == "déchiffrer":
|
|
message = input("Message à déchiffrer : ")
|
|
m = dechiffrer(message, alphabet, kc)
|
|
print(m)
|
|
|
|
|
|
def chiffrer(message: str, alphabet: str, cle: tuple[int, int]):
|
|
n = len(alphabet)
|
|
a, b = cle
|
|
output = ""
|
|
for symbol in message:
|
|
m = list(alphabet).index(symbol)
|
|
c = (a * m + b) % n
|
|
output += alphabet[c]
|
|
|
|
return output
|
|
|
|
|
|
def dechiffrer(message: str, alphabet: str, cle: tuple[int, int]):
|
|
n = len(alphabet)
|
|
a, b = cle
|
|
inv_a = inverser(int(a), n)
|
|
if not inv_a:
|
|
print(f"{a} doit être inversible")
|
|
return
|
|
op_b = opposer(int(b), n)
|
|
output = ""
|
|
for symbol in message:
|
|
c = list(alphabet).index(symbol)
|
|
m = (inv_a * c + inv_a * op_b) % n
|
|
output += alphabet[m]
|
|
|
|
return output
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|