【问题标题】:How to compute a shared secret for 2 users in algorithm Diffie Hellman using openssl lib c language?如何使用 openssl lib c 语言在算法 Diffie Hellman 中为 2 个用户计算共享密钥?
【发布时间】:2017-11-08 00:31:28
【问题描述】:

我需要一些有关 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 键值?函数 DH_compute_key 会使用我的 g 和 p 吗?

【问题讨论】:

  • printf(" dhSize = %d \n"); 缺少%d 格式说明符的参数。请启用编译器警告。
  • 我添加了,但控制台中没有显示任何内容。即使我不使用 printf,我的代码在计算 dhSize 后也不会执行。这是主要问题。
  • 然后使用调试器,我只是提到我注意到的一个错误。当您说“未执行”时,您的意思是程序在此之前崩溃,或者该行被忽略并执行后续代码。

标签: c algorithm openssl diffie-hellman


【解决方案1】:

你犯了愚蠢的错误:

  1. dhSize 应输入为DH_size(~第 24 行) 和DH_size 函数计算struct DH 的大小给定一个const struct DH * 你传递它dh-&gt;priv_key 而不是传递它dh (~line 28)

  2. 使用 DH_compute_key(~第 28 行)的类似错误应该是 dh 而不是 dh-&gt;priv_key

请修正后重试

【讨论】:

    猜你喜欢
    • 2011-12-17
    • 1970-01-01
    • 1970-01-01
    • 2013-06-12
    • 1970-01-01
    • 2021-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多