2

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.

Broseph
  • 1,655
  • 1
  • 18
  • 38

1 Answers1

3

Disclaimer: I maintain gmpy2.

I would recommend using gmpy2.is_bpsw_prp instead of gmpy2.next_prime. The BPSW test will be faster and there are no known counter-examples. The is_prime and next_prime checks used to use, and may still use, a fixed set of bases and it is possible to composites that pass a series of known tests. IIRC, someone found a composite that passed the first 17 checks. By default, 25 checks are done but it is a weakness.

I am planning to include an APR-CL provable primality test in the next release of gmpy2.

There are specific guidelines for selecting RSA primes that should be followed to prevent accidentally choosing primes that create an n that can be easily factored.

casevh
  • 11,093
  • 1
  • 24
  • 35
  • Thanks! I did a bit of quick googling, and updated my code snippet with your suggested function. If you have any more suggestions please let me know :) . – Broseph Mar 12 '15 at 00:13