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.
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.
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.
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, …
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
@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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With