如何使用 openssl lib c 语言在算法 Diffie Hellman 中计算 2 个用户的共享秘密?

How to compute a shared secret for 2 users in algorithm Diffie Hellman using openssl lib c language?

我需要一些关于 openssl 算法 Diffie Hellman 的帮助 我有质数 (p)、生成器 (g)、用户 A 的私钥和用户 B 的 public 密钥。我需要计算共享密钥。我写了这段代码,但是代码一直执行到这一行

 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、priv key?函数 DH_compute_key 会使用我的 g 和 p 吗?

你犯了愚蠢的错误:

  1. dhSize 应输入为 DH_size(~第 24 行) DH_size 函数计算 struct DH 的大小给定 const struct DH * 你正在传递它 dh->priv_key 而不是传递它 dh (~第 28 行)

  2. 使用 DH_compute_key 的类似错误(~第 28 行)第三个参数应该是 dh 而不是 dh->priv_key

请相应修正并重试