This commit is contained in:
Alexander Munch-Hansen 2019-10-02 20:07:34 +02:00
parent 65b1f6fecf
commit 22daf29b6f
2 changed files with 23 additions and 6 deletions

View File

@ -129,7 +129,7 @@ def is_prime(n: int, k: int) -> bool:
return True
def gen_prime(b: int, k: int = 10) -> int:
def gen_prime(b: int, k: int = 4) -> int:
"""
Generate strong probable prime by drawing integers at random until one passes the is_prime test.
Adapted from pseudo-code at https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test.
@ -142,14 +142,31 @@ def gen_prime(b: int, k: int = 10) -> int:
n = random.randint(2**(b-1), (2**b)-1)
if n % 2 == 0:
continue
if is_prime(n, k):
# Check that the future value of q is prime
if is_prime(n, k) and is_prime(2*n+1, k):
return n
def find_primitive_root(p):
if p == 2:
return 1
p1 = 2
p2 = (p - 1) // p1
# test random g's until one is found that is a primitive root mod p
while True:
g = SystemRandom().randint(2, p - 1)
if not (pow(g, (p - 1) // p1, p) == 1):
if not pow(g, (p - 1) // p2, p) == 1:
return g
def run(donor: BloodType, recipient: BloodType):
p = gen_prime(128)
q = 2 * p + 1
g = SystemRandom().randint(2, q)
g = find_primitive_root(p)
#print("p:", p, "q:", q, "g:", g)
elgamal = ElGamal(g, q, p)

View File

@ -8,7 +8,7 @@ from secrets import SystemRandom
from typing import List, Union
from .week1 import BloodType, blood_cell_compatibility_lookup
from .week4 import gen_prime
from .week4 import gen_prime, find_primitive_root
class ElGamal:
@ -221,7 +221,7 @@ def run(da, db, ds, ra, rb, rs):
p = gen_prime(256)
q = 2*p+1
g = SystemRandom().randint(2, q)
g = find_primitive_root(p)
elgamal = ElGamal(g, q, p)
alice = Alice(ra=ra, rb=rb, rs=rs, elgamal=elgamal)