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

本文最后更新于:2022年5月1日 晚上

〇、问题

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

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


一、原因

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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() 函数后程序运行正确


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!