From a8409a544cf836e1e561b3794aeafbe161f747ed Mon Sep 17 00:00:00 2001 From: tb <> Date: Tue, 4 Feb 2025 05:09:53 +0000 Subject: Start cleaning up BN_div_reciprocal() a bit The fast path where no division is performed can be dealt with without BN_CTX, so do that up front so there's no need to clean up before return. Error check BN_CTX_get() on each use asd simplify the logic for optional input parameters. KNF for an ugly comment. ok jsing --- src/lib/libcrypto/bn/bn_recp.c | 47 +++++++++++++++++++++--------------------- 1 file changed, 23 insertions(+), 24 deletions(-) diff --git a/src/lib/libcrypto/bn/bn_recp.c b/src/lib/libcrypto/bn/bn_recp.c index 8f917e95db..757ed0c3d2 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.30 2025/01/22 12:53:16 tb Exp $ */ +/* $OpenBSD: bn_recp.c,v 1.31 2025/02/04 05:09:53 tb Exp $ */ /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) * All rights reserved. * @@ -139,34 +139,33 @@ BN_div_reciprocal(BIGNUM *dv, BIGNUM *rem, const BIGNUM *m, BN_RECP_CTX *recp, int i, j, ret = 0; BIGNUM *a, *b, *d, *r; + if (BN_ucmp(m, recp->N) < 0) { + if (dv != NULL) + BN_zero(dv); + if (rem != NULL) + return bn_copy(rem, m); + return 1; + } + BN_CTX_start(ctx); - a = BN_CTX_get(ctx); - b = BN_CTX_get(ctx); - if (dv != NULL) - d = dv; - else + if ((a = BN_CTX_get(ctx)) == NULL) + goto err; + if ((b = BN_CTX_get(ctx)) == NULL) + goto err; + + if ((d = dv) == NULL) d = BN_CTX_get(ctx); - if (rem != NULL) - r = rem; - else - r = BN_CTX_get(ctx); - if (a == NULL || b == NULL || d == NULL || r == NULL) + if (d == NULL) goto err; - if (BN_ucmp(m, recp->N) < 0) { - BN_zero(d); - if (!bn_copy(r, m)) { - BN_CTX_end(ctx); - return 0; - } - BN_CTX_end(ctx); - return 1; - } + if ((r = rem) == NULL) + r = BN_CTX_get(ctx); + if (r == NULL) + goto err; - /* We want the remainder - * Given input of ABCDEF / ab - * we need multiply ABCDEF by 3 digests of the reciprocal of ab - * + /* + * We want the remainder. Given input of ABCDEF / ab we need to + * multiply ABCDEF by 3 digits of the reciprocal of ab. */ /* i := max(BN_num_bits(m), 2*BN_num_bits(N)) */ -- cgit v1.2.3-55-g6feb