LibCrypt如何使用低级API获取生成的公钥

LibCrypt如何使用低级API获取生成的公钥,c,openssl,diffie-hellman,libcrypto,C,Openssl,Diffie Hellman,Libcrypto,在我的项目中,为了实现组密钥协议,我决定使用OpenSSl for Diffie Hellman的低级API(代码片段取自) #包括 //这里有一些代码 DH*私钥; int码; int秘密大小; /*生成要使用的参数*/ if(NULL==(privkey=DH_new())handleErrors(); 如果(1!=DH_generate_parameters_ex(privkey,2048,DH_GENERATOR_2,NULL))handleErrors(); 如果(1!=DH_检查(私

在我的项目中,为了实现组密钥协议,我决定使用OpenSSl for Diffie Hellman的低级API(代码片段取自)

#包括
//这里有一些代码
DH*私钥;
int码;
int秘密大小;
/*生成要使用的参数*/
if(NULL==(privkey=DH_new())handleErrors();
如果(1!=DH_generate_parameters_ex(privkey,2048,DH_GENERATOR_2,NULL))handleErrors();
如果(1!=DH_检查(私钥和代码))句柄错误();
如果(代码!=0)
{
/*已发现生成的参数存在问题*/
/*在这里处理这些-对于这个例子,我们将中止*/
printf(“DH_检查失败\n”);
中止();
}
/*生成公钥和私钥对*/
如果(1!=DH_generate_key(privkey))handleErrors();
/*将公钥发送给对等方。
*这种情况如何发生将取决于您的具体情况(见下文正文)
*/
//这里是另一个代码
//清理
OPENSSL_免费(保密);
免费BN_(公开密钥);
DH_free(私钥);

但是,从生成的
DH
struct如何生成公钥?

如果您阅读了文档,它会生成公钥(如注释所示)

DH_generate_key()希望DH包含共享参数DH->p和DH->g。它生成一个随机的私有DH值,除非已经设置了DH->priv_key,并计算相应的公共值DH->pub_key,然后可以发布该值

因此,Diffie-Hellman交换的公共“密钥”部分位于“privkey->pub_-key”中,您将其与共享参数“privkey->p”和“privkey->g”一起发布到另一端

#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);