68 lines
1.6 KiB
Python
Executable file
68 lines
1.6 KiB
Python
Executable file
#!/usr/bin/env python3
|
|
|
|
"""Chiffrement affine"""
|
|
|
|
import sys
|
|
|
|
from inverse import inverser
|
|
from oppose import opposer
|
|
|
|
|
|
def main():
|
|
if len(sys.argv) == 2:
|
|
if sys.argv[1] == "chiffrer":
|
|
action = "chiffrer"
|
|
elif sys.argv[1] == "déchiffrer":
|
|
action = "déchiffrer"
|
|
else:
|
|
action = input("Chiffrer ou déchiffrer ? ")
|
|
|
|
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))
|
|
inv_a = inverser(a)
|
|
if not inv_a:
|
|
print(f"{a} doit être inversible")
|
|
return
|
|
op_b = opposer(b)
|
|
kd = (inv_a, (inv_a * op_b) % n)
|
|
|
|
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, kd)
|
|
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
|
|
output = ""
|
|
for symbol in message:
|
|
c = list(alphabet).index(symbol)
|
|
m = (a * c + a * b) % n
|
|
output += alphabet[m]
|
|
|
|
return output
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|