Ask Your Question

Randomly generate a safe prime of given length

asked 2018-12-24 00:32:36 +0200

panther gravatar image

A prime p is said to be safe prime if (p-1)/2 is also a prime. Safe primes are heavily used in cryptography. In order to generate a random prime of 512 bits, I use

random_prime(2^512-1, false, 2^511)

How to randomly generate a safe prime of given length?

edit retag flag offensive close merge delete

2 Answers

Sort by ยป oldest newest most voted

answered 2018-12-24 01:10:01 +0200

tmonteil gravatar image

You can use a rejection method: try a new random prime until you get a safe one:

sage: def rdp(nbits=512):
....:     while True:
....:         p = random_prime(2^nbits-1, false, 2^(nbits-1))
....:         if ZZ((p+1)/2).is_prime():
....:             return p
sage: rdp()

For other number of bits:

sage: rdp(200)
edit flag offensive delete link more

answered 2019-04-05 20:16:39 +0200

A much faster method is to generate a random integer p, to try dividing both p and (p-1)/2 by the first 100000 primes (just generate a table with those primes, using any suitable method) and reject p as soon as it is found that either p or (p-1)/2 has a divisor. If this is successful, then use the Miller-Rabin test on p and on (p-2)/2, using the first 10 primes as witnesses.

This is much faster because most p value will be rejected quickly, while first finding a prime p is much work and this work is useless because most of the time you can quickly find that (p-1)/2 is NOT prime. Better evaluate p and (p-1)/2 together, not focusing on one of them while ignoring the other one for a long time.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower


Asked: 2018-12-24 00:32:36 +0200

Seen: 2,526 times

Last updated: Dec 24 '18