B
B
Bleno-git2019-07-07 13:27:52
Python
Bleno-git, 2019-07-07 13:27:52

How to speed up the generation of prime numbers? What size of primes is needed for RSA?

At the moment, it takes about 4-15 seconds to generate a prime number with 512 digits (I have a fairly powerful machine), but numbers with 1024 digits are required, and so the generation time can be up to several minutes. Requires speed up to 5-10 seconds, with 100% no more than 10 seconds. This code generates prime numbers of a given length:

def isPrime(n, k=20):
  if n == 2 or n == 3:
    return True
  if not n & 1:
    return False

  def check(a, s, d, n):
    x = pow(a, d, n)
    if x == 1:
      return True
    for i in range(s - 1):
      if x == n - 1:
        return True
      x = pow(x, 2, n)
    return x == n - 1

  s = 0
  d = n - 1

  while d % 2 == 0:
    d >>= 1
    s += 1

  for i in range(k):
    a = random.randrange(2, n - 1)
    if not check(a, s, d, n):
      return False
  return True
def genPrime(n):
    	n = n + 1 if n % 2 == 0 else n + 2
    	while not isPrime(n):
    		n += [1,6,5,4,3,2,1,4,3,2,1,2,1,4,3,2,1,2,1,4,3,2,1,6,5,4,3,2,1,2][n % 30]
    	return n
genPrime(random.randint(10**length, 10**(length + 1)))

Where length is the length of the number. How can you speed up the generation of numbers, and does RSA even need prime numbers of this length?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Roman Kitaev, 2019-07-07
@deliro

1. Take a normal algorithm
2. Rewrite in Cython

O
Oleg Pravdin, 2019-07-08
@opravdin

If the goal is to get a number, then

from Crypto.Util import number
number.getPrime(2048)

If the goal is to get a number and write the generation code yourself, then implement this

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question