When g=2 and bit 2 of p is clear (p%8==3), g is a quadratic non-residue mod p. An odd priv_key makes pub_key fall outside the (p-1)/2 subgroup, leaking the low bit. Clear bit 0 to keep priv_key even, matching the OpenSSL software implementation. Signed-off-by: Weili Qian <qianweili@huawei.com> --- src/uadk_dh.c | 14 +++++++++++++- src/uadk_prov_dh.c | 15 ++++++++++++++- 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/src/uadk_dh.c b/src/uadk_dh.c index d5b1912..5e7b6d9 100644 --- a/src/uadk_dh.c +++ b/src/uadk_dh.c @@ -37,6 +37,7 @@ #define UADK_DH_MAX_MODULE_BIT 4096 #define DH_GENERATOR_2 2 #define DH_GENERATOR_5 5 +#define DH_QNR_BIT_INDEX 2 #define CHAR_BIT_SIZE 3 #define DH_PARAMS_CNT 3 #define CTX_MODE_NUM 2 @@ -146,6 +147,8 @@ static int uadk_e_dh_soft_compute_key(unsigned char *key, static int dh_generate_new_priv_key(const DH *dh, BIGNUM *new_priv_key) { const BIGNUM *q = DH_get0_q(dh); + const BIGNUM *g = DH_get0_g(dh); + const BIGNUM *p = DH_get0_p(dh); int bits; if (q) { @@ -155,10 +158,19 @@ static int dh_generate_new_priv_key(const DH *dh, BIGNUM *new_priv_key) } while (BN_is_zero(new_priv_key) || BN_is_one(new_priv_key)); } else { bits = DH_get_length(dh) ? - DH_get_length(dh) : BN_num_bits(DH_get0_p(dh)) - 1; + DH_get_length(dh) : BN_num_bits(p) - 1; if (!BN_priv_rand(new_priv_key, bits, BN_RAND_TOP_ONE, BN_RAND_BOTTOM_ANY)) return UADK_E_FAIL; + + /* + * When g=2 and p%8==3, g is a quadratic non-residue. + * If priv_key is odd, pub_key = g^priv mod p falls outside + * the (p-1)/2 subgroup. Clear bit 0 to keep priv_key even, + * matching OpenSSL soft implementation. + */ + if (BN_is_word(g, DH_GENERATOR_2) && !BN_is_bit_set(p, DH_QNR_BIT_INDEX)) + BN_clear_bit(new_priv_key, 0); } return UADK_E_SUCCESS; diff --git a/src/uadk_prov_dh.c b/src/uadk_prov_dh.c index d7d490d..2e4a832 100644 --- a/src/uadk_prov_dh.c +++ b/src/uadk_prov_dh.c @@ -37,6 +37,7 @@ #define DH4096BITS 4096 #define UADK_DH_MAX_MODULE_BIT 4096 #define DH_GENERATOR_2 2 +#define DH_QNR_BIT_INDEX 2 #define CHAR_BIT_SIZE 3 #define DH_PARAMS_CNT 3 #define CTX_MODE_NUM 2 @@ -505,15 +506,27 @@ static void uadk_DH_set_flags(DH *dh, int flags) static int uadk_dh_gen_prikey_undef(const DH *dh, BIGNUM *new_prikey) { + const BIGNUM *g = NULL; + const BIGNUM *p = NULL; int bits; + uadk_DH_get0_pqg(dh, &p, NULL, &g); bits = uadk_DH_get_length(dh) ? - uadk_DH_get_length(dh) : BN_num_bits(uadk_DH_get0_p(dh)) - 1; + uadk_DH_get_length(dh) : BN_num_bits(p) - 1; if (!BN_priv_rand(new_prikey, bits, BN_RAND_TOP_ONE, BN_RAND_BOTTOM_ANY)) { UADK_ERR("failed to BN_priv_rand\n"); return UADK_P_FAIL; } + /* + * When g=2 and p%8==3, g is a quadratic non-residue. + * If prikey is odd, pubkey = g^prikey mod p falls outside + * the (p-1)/2 subgroup. Clear bit 0 to keep prikey even, + * matching OpenSSL soft implementation. + */ + if (BN_is_word(g, DH_GENERATOR_2) && !BN_is_bit_set(p, DH_QNR_BIT_INDEX)) + BN_clear_bit(new_prikey, 0); + return UADK_P_SUCCESS; } -- 2.43.0