In my project in order to implement a Group key agreement I decided to use the low-level apis of OpenSSl for Diffie Hellman (code snippet taken from documentation )
#include <libssl/dh.h>
// Some code here
DH *privkey;
int codes;
int secret_size;
/* Generate the parameters to be used */
if(NULL == (privkey = DH_new())) handleErrors();
if(1 != DH_generate_parameters_ex(privkey, 2048, DH_GENERATOR_2, NULL)) handleErrors();
if(1 != DH_check(privkey, &codes)) handleErrors();
if(codes != 0)
{
/* Problems have been found with the generated parameters */
/* Handle these here - we'll just abort for this example */
printf("DH_check failed\n");
abort();
}
/* Generate the public and private key pair */
if(1 != DH_generate_key(privkey)) handleErrors();
/* Send the public key to the peer.
* How this occurs will be specific to your situation (see main text below)
*/
// Another code here
//Cleanups
OPENSSL_free(secret);
BN_free(pubkey);
DH_free(privkey);
But from a generated DH
struct how I can generate a public key?
If you read the documentation for DH_generate_key, it does (as the comment says).
DH_generate_key() expects dh to contain the shared parameters dh->p and dh->g. It generates a random private DH value unless dh->priv_key is already set, and computes the corresponding public value dh->pub_key, which can then be published.
So the public "key" part of the Diffie Hellman exchange is in "privkey->pub_key" and you publish that along with your shared parameters "privkey->p" and "privkey->g" to the other side.