Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

generation of safe primes

I need to generate a safe prime which has the form 2p + 1 where p is also prime of a certain bit length (lets say 1024 bits). It is to be used in a DH key exchange.

I believe openssl can do this via

openssl gendh 1024

however this return's a base64 pem format

-----BEGIN DH PARAMETERS-----
MIGHAoGBANzQ1j1z7RGB8XUagrGWK5a8AABecNrovcIgalv1hQdkna2PZorHtbOa
wYe1eDy1t/EztsM2Cncwvj5LBO3Zqsd5tneehKf8JoT35/q1ZznfLD8s/quBgrH8
es2xjSD/9syOMMiSv7/72GPJ8hzhLrbTgNlZ+kYBAPw/GcTlYjc7AgEC
-----END DH PARAMETERS-----
  • How can I extract the safe prime number from this base64 pem?

  • is it easier to generate my own safe prime with my own code?

how can i test that a prime is 'safe' and of a certain bit length.

like image 656
The Unix Janitor Avatar asked Mar 21 '11 15:03

The Unix Janitor


People also ask

What are safe primes used for?

A safe prime is a prime number p of the form p = 2q + 1 where q is also prime. In such a case, q is called a Sophie Germain prime. Safe primes are used in some implementations of the Diffie– Hellman key exchange protocol, for example, to protect against certain types of attacks.

Why are safe primes safe?

It is usually this prime-order subgroup that is desirable, and the reason for using safe primes is so that the modulus is as small as possible relative to p. A prime number p = 2q + 1 is called a safe prime if q is prime.

What is the first safe prime number?

A safe prime is a prime number of the form (2 * p) + 1 where p is also a prime. The first few safe primes are 5, 7, 11, 23, 47, …


2 Answers

I agree with the comments made by @Luke. However, if for some reason you must use openssl command lines there are a few options but they'll only get you so far. None of these will do any significant arithmetic for you; they won't retrieve (p-1)/2 and check it for primality.

You can use the openssl dh command and parse the output. Try it with and without the -C option to see which works better for you. Examples.

openssl gendh -out testdh.pem 1024
openssl dh -in testdh.pem -noout -C
openssl dh -in testdh.pem -noout

If you can handle or prefer binary then you can parse the binary output for the DER-encoded DH structure.

openssl dh -in testdh.pem -outform der -out testdh.der

Another option is to parse the output of the ans1parse command:

openssl asn1parse -in testdh.pem
like image 43
President James K. Polk Avatar answered Sep 24 '22 06:09

President James K. Polk


@GregS has an approach that will probably work for you. Based on what you have told me, I would just create a C binary and leverage the BN_generate_prime(...) function in OpenSSL. That cuts out all of the intermediate parsing and despite adding a separate binary into the mix, it's probably easier than the road you are headed down.

like image 79
Luke Avatar answered Sep 20 '22 06:09

Luke