How to efficiently generate a random safe prime of given length? 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
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).