crypto_projet/test_ElGamal.py

57 lines
1.7 KiB
Python
Raw Normal View History

from sympy import primitive_root, randprime
from ElGamal import (
Add_cipher,
Decrypt_cc,
Decrypt_ce,
Encrypt_cc,
Encrypt_ce,
KeyGen,
KeyGen_central,
Decrypt_central_cc,
Decrypt_central_ce,
)
if __name__ == "__main__":
# On prend le groupe de (randprime - 1)
ordre = randprime(2, 1 << 10)
gen = primitive_root(ordre)
m = 22
pk, sk = KeyGen(gen, ordre)
print(f"Private key: {pk}, public key: {sk}")
cipher = Encrypt_cc(gen, ordre, pk, m)
# print(f"Cipher of {m}: {cipher}")
clear = Decrypt_cc(gen, ordre, sk, cipher)
print(f"Cleartext message : {clear}")
assert clear == m
cipher = 0
clear = 0
cipher = Encrypt_ce(gen, ordre, pk, m)
print(f"Cipher_ce: {cipher}")
clear = Decrypt_ce(gen, ordre, sk, cipher)
print(f"Cleartext_ce: {clear}")
assert clear == m
ciphers = [(1, 1), (1, 2), (1, 3)]
assert Add_cipher(ciphers) == 1 + 2 + 3
# Le chiffrement par clé publique est déchiffrable par la clé privée reconstituée.
privkeys, pubkey = KeyGen_central(gen, ordre, 2)
clear = 12
print(f"Clés privées : {privkeys}")
print(f"Clé publique : {pubkey}")
crypt = Encrypt_cc(gen, ordre, pubkey, clear)
assert clear == Decrypt_central_cc(gen, ordre, privkeys, crypt)
assert clear != Decrypt_cc(
gen, ordre, privkeys[0], Encrypt_cc(gen, ordre, pubkey, clear)
)
assert clear != Decrypt_cc(
gen, ordre, privkeys[1], Encrypt_cc(gen, ordre, pubkey, clear)
)
crypt = Encrypt_ce(gen, ordre, pubkey, clear)
assert clear == Decrypt_central_ce(gen, ordre, privkeys, crypt)
assert clear != Decrypt_central_ce(gen, ordre, [privkeys[0]], crypt)