So for DHKE, I need to generate a large prime g (> 500 bits in this case), and then calculate N = 2g+1, then test if N is a prime. Repeat the process until such N is found.
To accomplish this, I generate a random number g, run fermatTest on it, then run fermatTest on N after. However, I noticed that the run time is extremely slow (sometime the program would take minutes)
Here is my implementation of Fermat test on arbitrary numbers:
def fermatTest(p):
for i in range(5): # probability of getting a fool: 1/32
a = secrets.randbelow(p)
if gcd(p,a) == 1:
if (pow(a,p-1,p) == 1):
return True
else:
return False
I noticed that to have a good Fermat test, I need to check p with multiple rounds of a, which reduce the chance of getting a Fermat's fool (composite behaves like prime), but also slow down the computation.
My questions are:
Is there a way to make this function faster? Or are there other known algorithms that are faster than Fermat?
You can use sympy library which has a sympy.isprime() function which uses a better implementation of Fermat's test (I could be wrong, but the idea is pretty much the same). However, right now I still have no idea on how to bring the overall time to be less than 30 seconds (sometimes you are lucky you can generate a Safe Prime within 1 second, but other time it can be up to 120s)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.