在我的项目中,为了实现一个组密钥协议,我决定为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
结构中,我如何生成公钥? 最佳答案
如果您阅读了DH_generate_key的文档,它会阅读(正如评论所说)。
DH_generate_key()期望DH包含共享参数DH->p和DH->g。它生成一个随机的私有DH值,除非已经设置了DH->priv_key,并计算相应的公共值DH->pub_key,然后可以发布。
所以Diffie-Hellman交换的公共“密钥”部分在“privkey->pub_key”中,您将其与共享参数“privkey->p”和“privkey->g”一起发布到另一边。