我需要一些关于openssl中Diffie-Hellman算法的帮助我有素数(p),生成器(g),用户A的私钥和用户B的公钥。我需要计算共享密钥。我写了这个代码,但代码一直执行到这行
int dhSize = DH_size(dh->priv_key);
这是完整的代码:
#include <stdio.h>
#include <openssl/dh.h>
const char* userA_PrivateKey = "90ff0";
const char* userB_PublicKey = "9d1a59";
const char* p = "66c2fa";
const char* g = "2";
int main(void)
{
DH *dh = DH_new();
BN_dec2bn(&dh->g, g);
BN_hex2bn(&dh->p, p);
BN_hex2bn(&dh->priv_key, userA_PrivateKey);
BIGNUM *pubKeyUserB = NULL;
BN_dec2bn(&pubKeyUserB, userB_PublicKey);
//Compute the shared secret
int secret_size;
unsigned char *secret;
printf(" Compute DH_size n");
int dhSize = DH_size(dh->priv_key);
printf(" dhSize = %d n"); //NOT EXECUTED
secret = OPENSSL_malloc(sizeof(unsigned char) * dhSize);
if(0 > (secret_size = DH_compute_key(secret, pubKeyUserB, dh->priv_key)))
{
printf("error n");
}
return 0;
}
我有两个问题:
1) 打印dhSize的printf在所有中都没有执行
2) 我不确定我是否正确设置了值g,p,priva-key?函数DH_computer_key会使用我的g和p吗?
你犯了愚蠢的错误:
-
dhSize
应键入为DH_size
(~第24行)DH_size
函数计算struct DH
的大小,给定const struct DH *
您正在传递dh->priv_key
而不是传递dh
(~第28行) -
在使用
DH_compute_key
(~第28行)时出现类似错误,第三个自变量应该是dh
而不是dh->priv_key
。
请相应修复并重试