使用 openssl DH_compute_key() 函数计算 DH 密钥长度不对的问题

问题

最近在使用 DH_compute_key() 函数计算 DH 共享密钥时,发现计算得出的密钥长度少了一位,导致后续所有数据都出现了错误,最终导致程序崩溃。

BN_bn2bin() 函数也具有相同的问题


过程

查看 openssl 官方文档 发现以下内容:

DH_compute_key() computes the DH_compute_key() computes the 
shared secret from the private DH value in dh and the other 
party's public value in pub_key and stores it in key. key must 
point to DH_size(dh) bytes of memory. The padding style is RFC 
5246 (8.1.2) that strips leading zero bytes. It is not 
constant time due to the leading zero bytes being stripped. 
The return value should be considered public.


DH_compute_key_padded() is similar but stores a fixed number 
of bytes. The padding style is NIST SP 800-56A (C.1) that 
retains leading zero bytes. It is constant time due to the 
leading zero bytes being retained. The return value should be 
considered public.shared secret from the private DH value in 
dh and the other party's public value in pub_key and stores it 
in key. key must point to DH_size(dh) bytes of memory. The 
padding style is RFC 5246 (8.1.2) that strips leading zero 
bytes. It is not constant time due to the leading zero bytes 
being stripped. The return value should be considered public.

解决

就是说:DH_compute_key() 函数会去掉结果最前面的 ‘0x00’ 字节,而 DH_compute_key_padded() 不会

修改为使用 DH_compute_key_padded() 函数后程序运行正确。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
如果你想使用GMP(GNU Multiple Precision Arithmetic Library)来获取OpenSSL中RSA_generate_key函数生成的密钥,你需要进行一些额外的步骤。 首先,你需要将OpenSSL生成的RSA密钥转换为GMP库中的大数格式。然后,你可以使用GMP库提供的函数来处理这些大数。 以下是一个示例代码,展示了如何将OpenSSL生成的RSA密钥转换为GMP库中的大数: ```c #include <stdio.h> #include <openssl/rsa.h> #include <openssl/pem.h> #include <gmp.h> void opensslToGmp(RSA* rsa_key, mpz_t* n, mpz_t* e, mpz_t* d) { // 将RSA结构体中的大数转换为GMP库中的mpz_t类型 mpz_init(*n); mpz_init(*e); mpz_init(*d); mpz_import(*n, BN_num_bytes(rsa_key->n), 1, 1, 0, 0, rsa_key->n->d); mpz_import(*e, BN_num_bytes(rsa_key->e), 1, 1, 0, 0, rsa_key->e->d); mpz_import(*d, BN_num_bytes(rsa_key->d), 1, 1, 0, 0, rsa_key->d->d); } int main() { RSA* rsa_key = RSA_generate_key(2048, RSA_F4, NULL, NULL); mpz_t n, e, d; opensslToGmp(rsa_key, &n, &e, &d); // 在这里使用GMP库中的大数进行操作 // 清理内存 mpz_clear(n); mpz_clear(e); mpz_clear(d); RSA_free(rsa_key); return 0; } ``` 在上述示例代码中,我们定义了一个名为opensslToGmp的函数,用于将RSA结构体中的大数转换为GMP库中的mpz_t类型。在这个函数中,我们使用mpz_import函数将RSA结构体中的大数转换为GMP库中的大数。 在main函数中,我们使用RSA_generate_key函数生成一个2048位的RSA密钥对。然后,通过调用opensslToGmp函数将生成的RSA密钥转换为GMP库中的大数。 接下来,你可以使用GMP库中提供的函数来处理这些大数,进行你想要的操作。 请注意,在使用GMP库之前,你需要确保已经正确安装和配置了GMP库。 希望这个示例能对你有所帮助。如果还有其他问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值