在我的项目中,为了实施Group Key协议,我决定将OpenSSl的低级api用于Diffie Hellman(摘录自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
结构中生成公共密钥?
答案 0 :(得分:1)
如果您阅读了DH_generate_key的文档,则确实如此(如评论所述)。
DH_generate_key()期望dh包含共享参数dh-> p和dh-> g。除非已设置dh-> priv_key,否则它将生成一个随机的私有DH值,并计算相应的公共值dh-> pub_key,然后可以将其发布。
因此Diffie Hellman交换的公共“密钥”部分位于“ privkey-> pub_key ”中,并且将其与共享参数“ privkey-> p ”和“ privkey-> g ”。