问题
最近在使用 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() 函数后程序运行正确。