diff --git a/week4.py b/week4.py index 3d4693e..6d27a34 100644 --- a/week4.py +++ b/week4.py @@ -8,22 +8,24 @@ from math import pow import numpy as np from crypto.week1 import BloodType, convert_from_string_to_enum, blood_cell_compatibility_lookup +# We can't encrypt 0, so we have to index from 1 convert_bloodtype_to_index = { - BloodType.O_NEGATIVE: 0, - BloodType.O_POSITIVE: 1, - BloodType.A_NEGATIVE: 2, - BloodType.A_POSITIVE: 3, - BloodType.B_NEGATIVE: 4, - BloodType.B_POSITIVE: 5, - BloodType.AB_NEGATIVE: 6, - BloodType.AB_POSITIVE: 7, + BloodType.O_NEGATIVE: 1, + BloodType.O_POSITIVE: 2, + BloodType.A_NEGATIVE: 3, + BloodType.A_POSITIVE: 4, + BloodType.B_NEGATIVE: 5, + BloodType.B_POSITIVE: 6, + BloodType.AB_NEGATIVE: 7, + BloodType.AB_POSITIVE: 8, } class ElGamal: - def __init__(self, g, q): + def __init__(self, g, q, p): self.gen_ = g self.order = q + self.p = p self.pk = None self.sk = None @@ -42,8 +44,8 @@ class ElGamal: def enc(self, m, pk): # sample random r \in Zq r = SystemRandom().randint(1, q) - g, h = pk + s = (h**r) % q p = (g**r) % q c = s * m @@ -56,7 +58,7 @@ class ElGamal: m = c1 / h return m - def ogen(self, r): + def ogen(self): # Here, q = 2p+1, thus we actually need to use the p here, instead of # self.order, but as we do not know p yet, .e we # TODO: Use p instead of self.order, s.t. self.order = 2p+1 @@ -68,22 +70,22 @@ class ElGamal: class Alice: def __init__(self, bloodtype, elgamal): self.elgamal = elgamal - self.gen_ = 9 - self.order = 453 - self.b = convert_bloodtype_to_index[convert_from_string_to_enum[bloodtype]] - self.sk = SystemRandom().randint(1, self.order) - self.pk = self.elgamal.gen(self.sk) - self.fake_pks = [self.elgamal.ogen(SystemRandom().randint(0, self.order)) + self.sk = elgamal.gen_key() + + self.pk = elgamal.gen(self.sk) + + self.b = convert_bloodtype_to_index[convert_from_string_to_enum[bloodtype]] + self.fake_pks = [self.elgamal.ogen() for _ in range(7)] def send_pks(self): all_pks = self.fake_pks - all_pks.insert(self.b, self.pk) + all_pks.insert(self.b-1, self.pk) return all_pks def retrieve(self, ciphers): - mb = self.elgamal.dec(ciphers[self.b]) + mb = self.elgamal.dec(ciphers[self.b-1]) return mb @@ -114,15 +116,14 @@ if __name__ == "__main__": q = 2*p + 1 g = SystemRandom().randint(2, q) - elgamal = ElGamal(g, q) - sk = elgamal.gen_key() + elgamal = ElGamal(g, q, p) + alice = Alice("B-", elgamal) + bob = Bob("B-", elgamal) + + bob.receive_pks(alice.send_pks()) + pls = alice.retrieve(bob.transfer_messages()) + print(pls) - m = 7 - pk = elgamal.gen(sk) - c = elgamal.enc(m, pk) - print(c) - d_m = elgamal.dec(c) - print("decrupted:", d_m)