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

时间:2017-11-08 00:31:28

标签: c algorithm openssl diffie-hellman

我需要在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)printf,打印dhSize根本不执行

2)我不确定我是否正确设置了值g,p,priv key? DH_compute_key函数会使用我的g和p吗?

1 个答案:

答案 0 :(得分:0)

你犯的是愚蠢的错误:

  1. dhSize应输入为DH_size(〜第24行) DH_size函数计算struct DH的大小{em> const struct DH * 您传递dh->priv_key而不是传递dh(〜line) 28)

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

  3. 请相应修改,然后重试