LibCrypt 如何使用低级 api 获取我生成的 public 密钥

LibCrypt how to get my generated public key using low level apis

在我的项目中,为了实现组密钥协议,我决定为 Diffie Hellman 使用 OpenSSL 的低级 API(代码片段取自 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);

但是如何从生成的 DH 结构生成 public 密钥?

如果您阅读 DH_generate_key 的文档,它确实如此(正如评论所说)。

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.

因此,Diffie Hellman 交换的 public "key" 部分位于“privkey->pub_key”,您将其发布使用您的共享参数“privkey->p”和“privkey->g”到另一侧。