More specifically, is the gmpy2.next_prime
function good enough to find the large primes needed? Or should I be using one of the other many gmpy2.*_prp
functions?
For example, is the following code good enough for finding suitable primes for encryption?
import os
import gmpy2
def random(bytez):
seed = reduce(lambda a, b: (a << 8)|ord(b), os.urandom(bytez), 0)
return gmpy2.mpz_urandomb(gmpy2.random_state(seed), bytez*8)
def find_prime(bytez=128):
p = random(bytez)|1
while not gmpy2.is_bpsw_prp(p):
p = random(bytez)|1
return p
def good_pair(p, q):
n = p*q
k = gmpy2.ceil(gmpy2.log2(n))
if abs(p - q) > 2**(k/2 - 100):
return n
return 0
def make_rsa_keypair():
p, q = find_prime(), find_prime()
n = good_pair(p, q)
while not n:
p, q = find_prime(), find_prime()
n = good_pair(p, q)
tot = n - (p + q - 1)
e = (1 << 16) + 1
d = gmpy2.invert(e, tot)
return {
'public':{
'n':n,
'e':e,
},
'private':{
'n':n,
'd':d,
}
}
UPDATE: updated the code with the suggestion.