From 587eb12f2939f2de7ec3b59d80ce14dfa6c9e436 Mon Sep 17 00:00:00 2001 From: tb <> Date: Tue, 4 Feb 2025 12:47:58 +0000 Subject: Inline BN_reciprocal() in its only caller This is simpler, doesn't need an auxiliary function of dubious value, avouds an auxiliary variable and gets rid of a bunch of comments that are hard to make sense of. This doesn't bother to invalidate recp->shift since on error you should not be reusing the RECP_CTX without reinitializing it. ok jsing --- src/lib/libcrypto/bn/bn_recp.c | 46 +++++++++--------------------------------- 1 file changed, 10 insertions(+), 36 deletions(-) diff --git a/src/lib/libcrypto/bn/bn_recp.c b/src/lib/libcrypto/bn/bn_recp.c index 757ed0c3d2..d5070bc003 100644 --- a/src/lib/libcrypto/bn/bn_recp.c +++ b/src/lib/libcrypto/bn/bn_recp.c @@ -1,4 +1,4 @@ -/* $OpenBSD: bn_recp.c,v 1.31 2025/02/04 05:09:53 tb Exp $ */ +/* $OpenBSD: bn_recp.c,v 1.32 2025/02/04 12:47:58 tb Exp $ */ /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) * All rights reserved. * @@ -104,34 +104,6 @@ BN_RECP_CTX_free(BN_RECP_CTX *recp) freezero(recp, sizeof(*recp)); } -/* len is the expected size of the result - * We actually calculate with an extra word of precision, so - * we can do faster division if the remainder is not required. - */ -/* r := 2^len / m */ -static int -BN_reciprocal(BIGNUM *r, const BIGNUM *m, int len, BN_CTX *ctx) -{ - int ret = -1; - BIGNUM *t; - - BN_CTX_start(ctx); - if ((t = BN_CTX_get(ctx)) == NULL) - goto err; - - if (!BN_set_bit(t, len)) - goto err; - - if (!BN_div_ct(r, NULL, t, m, ctx)) - goto err; - - ret = len; - -err: - BN_CTX_end(ctx); - return ret; -} - int BN_div_reciprocal(BIGNUM *dv, BIGNUM *rem, const BIGNUM *m, BN_RECP_CTX *recp, BN_CTX *ctx) @@ -174,13 +146,15 @@ BN_div_reciprocal(BIGNUM *dv, BIGNUM *rem, const BIGNUM *m, BN_RECP_CTX *recp, if (j > i) i = j; - /* Nr := round(2^i / N) */ - if (i != recp->shift) - recp->shift = BN_reciprocal(recp->Nr, recp->N, i, ctx); - - /* BN_reciprocal returns i, or -1 for an error */ - if (recp->shift == -1) - goto err; + /* Compute Nr := (1 << i) / N if necessary. */ + if (i != recp->shift) { + BN_zero(recp->Nr); + if (!BN_set_bit(recp->Nr, i)) + goto err; + if (!BN_div_ct(recp->Nr, NULL, recp->Nr, recp->N, ctx)) + goto err; + recp->shift = i; + } /* d := |round(round(m / 2^BN_num_bits(N)) * recp->Nr / 2^(i - BN_num_bits(N)))| * = |round(round(m / 2^BN_num_bits(N)) * round(2^i / N) / 2^(i - BN_num_bits(N)))| -- cgit v1.2.3-55-g6feb