10

A prime $p$ is said to be safe prime if $(p-1)/2$ is also a prime. How to efficiently generate a safe prime? I have written the following code in sagemath which generates a random safe prime of 1536 bits. This code took 426 seconds to generate a safe prime. That's very inefficient. Is there a faster way to efficiently generate a safe prime?

while True:
    p = random_prime(2^1536-1, false, 2^(1535))
    if ZZ((p-1)/2).is_prime():
        return p
satya
  • 1,484
  • 10
  • 32

2 Answers2

16

There is no more efficient way of generating a safe prime. Even in OpenSSL's optimized code, it can take a long time to generate a safe prime (30 seconds, a minute, 2 minutes). Run "openssl gendh 1024" on your computer to see (on my 2015 MacBook pro it can take a long time, but the variance is really high so try a few times).

The comments talk about safe primes for RSA. Indeed, safe primes are not needed for RSA. However, they are needed for generating parameters for finite-field cryptography (Diffie-Hellman over a finite field), and for other applications in cryptography. For example, zero-knowledge range proofs use a group with an unknown order, and this is defined by an RSA modulus and Pedersen commitments over that modulus. When using safe primes, this ensures that the group is large and furthermore that a random group element is a generator with overwhelming probability. See Section 1.2 of Efficient Protocols for Set Membership and Range Proofs for more about this particular application.

So, in more advanced cryptography, there are plenty of applications for safe primes (indeed, RSA encryption is not one of them).

Yehuda Lindell
  • 28,270
  • 1
  • 69
  • 86
7

You can speed up the generation of safe primes by sieving for $p$ and $(p-1)/2$ simultanously. According to Safe prime generation with a combined sieve by Michael J. Wiener sieving small primes up to $2^{16}$ this way is about 15x faster than the naive algorithm.

Be aware that the running time for finding a prime has a huge variation, so just measuring once and saying "it takes 426s" doesn't say much (average time could easily be a magnitude lower or higher).

j.p.
  • 1,657
  • 20
  • 17