xref: /openbsd/lib/libcrypto/bn/bn_div.c (revision 6dd041f3)
1 /* $OpenBSD: bn_div.c,v 1.41 2024/04/10 14:58:06 beck Exp $ */
2 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3  * All rights reserved.
4  *
5  * This package is an SSL implementation written
6  * by Eric Young (eay@cryptsoft.com).
7  * The implementation was written so as to conform with Netscapes SSL.
8  *
9  * This library is free for commercial and non-commercial use as long as
10  * the following conditions are aheared to.  The following conditions
11  * apply to all code found in this distribution, be it the RC4, RSA,
12  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13  * included with this distribution is covered by the same copyright terms
14  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15  *
16  * Copyright remains Eric Young's, and as such any Copyright notices in
17  * the code are not to be removed.
18  * If this package is used in a product, Eric Young should be given attribution
19  * as the author of the parts of the library used.
20  * This can be in the form of a textual message at program startup or
21  * in documentation (online or textual) provided with the package.
22  *
23  * Redistribution and use in source and binary forms, with or without
24  * modification, are permitted provided that the following conditions
25  * are met:
26  * 1. Redistributions of source code must retain the copyright
27  *    notice, this list of conditions and the following disclaimer.
28  * 2. Redistributions in binary form must reproduce the above copyright
29  *    notice, this list of conditions and the following disclaimer in the
30  *    documentation and/or other materials provided with the distribution.
31  * 3. All advertising materials mentioning features or use of this software
32  *    must display the following acknowledgement:
33  *    "This product includes cryptographic software written by
34  *     Eric Young (eay@cryptsoft.com)"
35  *    The word 'cryptographic' can be left out if the rouines from the library
36  *    being used are not cryptographic related :-).
37  * 4. If you include any Windows specific code (or a derivative thereof) from
38  *    the apps directory (application code) you must include an acknowledgement:
39  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40  *
41  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  *
53  * The licence and distribution terms for any publically available version or
54  * derivative of this code cannot be changed.  i.e. this code cannot simply be
55  * copied and put under another distribution licence
56  * [including the GNU Public Licence.]
57  */
58 
59 #include <assert.h>
60 #include <stdio.h>
61 
62 #include <openssl/opensslconf.h>
63 
64 #include <openssl/bn.h>
65 #include <openssl/err.h>
66 
67 #include "bn_arch.h"
68 #include "bn_local.h"
69 #include "bn_internal.h"
70 
71 BN_ULONG bn_div_3_words(const BN_ULONG *m, BN_ULONG d1, BN_ULONG d0);
72 
73 #ifndef HAVE_BN_DIV_WORDS
74 #if defined(BN_LLONG) && defined(BN_DIV2W)
75 
76 BN_ULONG
bn_div_words(BN_ULONG h,BN_ULONG l,BN_ULONG d)77 bn_div_words(BN_ULONG h, BN_ULONG l, BN_ULONG d)
78 {
79 	return ((BN_ULONG)(((((BN_ULLONG)h) << BN_BITS2)|l)/(BN_ULLONG)d));
80 }
81 
82 #else
83 
84 /* Divide h,l by d and return the result. */
85 /* I need to test this some more :-( */
86 BN_ULONG
bn_div_words(BN_ULONG h,BN_ULONG l,BN_ULONG d)87 bn_div_words(BN_ULONG h, BN_ULONG l, BN_ULONG d)
88 {
89 	BN_ULONG dh, dl, q,ret = 0, th, tl, t;
90 	int i, count = 2;
91 
92 	if (d == 0)
93 		return (BN_MASK2);
94 
95 	i = BN_num_bits_word(d);
96 	assert((i == BN_BITS2) || (h <= (BN_ULONG)1 << i));
97 
98 	i = BN_BITS2 - i;
99 	if (h >= d)
100 		h -= d;
101 
102 	if (i) {
103 		d <<= i;
104 		h = (h << i) | (l >> (BN_BITS2 - i));
105 		l <<= i;
106 	}
107 	dh = (d & BN_MASK2h) >> BN_BITS4;
108 	dl = (d & BN_MASK2l);
109 	for (;;) {
110 		if ((h >> BN_BITS4) == dh)
111 			q = BN_MASK2l;
112 		else
113 			q = h / dh;
114 
115 		th = q * dh;
116 		tl = dl * q;
117 		for (;;) {
118 			t = h - th;
119 			if ((t & BN_MASK2h) ||
120 			    ((tl) <= (
121 			    (t << BN_BITS4) |
122 			    ((l & BN_MASK2h) >> BN_BITS4))))
123 				break;
124 			q--;
125 			th -= dh;
126 			tl -= dl;
127 		}
128 		t = (tl >> BN_BITS4);
129 		tl = (tl << BN_BITS4) & BN_MASK2h;
130 		th += t;
131 
132 		if (l < tl)
133 			th++;
134 		l -= tl;
135 		if (h < th) {
136 			h += d;
137 			q--;
138 		}
139 		h -= th;
140 
141 		if (--count == 0)
142 			break;
143 
144 		ret = q << BN_BITS4;
145 		h = ((h << BN_BITS4) | (l >> BN_BITS4)) & BN_MASK2;
146 		l = (l & BN_MASK2l) << BN_BITS4;
147 	}
148 	ret |= q;
149 	return (ret);
150 }
151 #endif /* !defined(BN_LLONG) && defined(BN_DIV2W) */
152 #endif
153 
154 /*
155  * Divide a double word (h:l) by d, returning the quotient q and the remainder
156  * r, such that q * d + r is equal to the numerator.
157  */
158 #ifndef HAVE_BN_DIV_REM_WORDS
159 #ifndef HAVE_BN_DIV_REM_WORDS_INLINE
160 static inline void
bn_div_rem_words_inline(BN_ULONG h,BN_ULONG l,BN_ULONG d,BN_ULONG * out_q,BN_ULONG * out_r)161 bn_div_rem_words_inline(BN_ULONG h, BN_ULONG l, BN_ULONG d, BN_ULONG *out_q,
162     BN_ULONG *out_r)
163 {
164 	BN_ULONG q, r;
165 
166 	q = bn_div_words(h, l, d);
167 	r = (l - q * d) & BN_MASK2;
168 
169 	*out_q = q;
170 	*out_r = r;
171 }
172 #endif
173 
174 void
bn_div_rem_words(BN_ULONG h,BN_ULONG l,BN_ULONG d,BN_ULONG * out_q,BN_ULONG * out_r)175 bn_div_rem_words(BN_ULONG h, BN_ULONG l, BN_ULONG d, BN_ULONG *out_q,
176     BN_ULONG *out_r)
177 {
178 	bn_div_rem_words_inline(h, l, d, out_q, out_r);
179 }
180 #endif
181 
182 #ifndef HAVE_BN_DIV_3_WORDS
183 
184 /*
185  * Interface is somewhat quirky, |m| is pointer to most significant limb,
186  * and less significant limb is referred at |m[-1]|. This means that caller
187  * is responsible for ensuring that |m[-1]| is valid. Second condition that
188  * has to be met is that |d0|'s most significant bit has to be set. Or in
189  * other words divisor has to be "bit-aligned to the left." The subroutine
190  * considers four limbs, two of which are "overlapping," hence the name...
191  */
192 BN_ULONG
bn_div_3_words(const BN_ULONG * m,BN_ULONG d1,BN_ULONG d0)193 bn_div_3_words(const BN_ULONG *m, BN_ULONG d1, BN_ULONG d0)
194 {
195 	BN_ULONG n0, n1, q, t2h, t2l;
196 	BN_ULONG rem = 0;
197 
198 	n0 = m[0];
199 	n1 = m[-1];
200 
201 	if (n0 == d0)
202 		return BN_MASK2;
203 
204 	/* n0 < d0 */
205 	bn_div_rem_words(n0, n1, d0, &q, &rem);
206 
207 	bn_mulw(d1, q, &t2h, &t2l);
208 
209 	for (;;) {
210 		if (t2h < rem || (t2h == rem && t2l <= m[-2]))
211 			break;
212 		q--;
213 		rem += d0;
214 		if (rem < d0)
215 			break; /* don't let rem overflow */
216 		if (t2l < d1)
217 			t2h--;
218 		t2l -= d1;
219 	}
220 
221 	return q;
222 }
223 #endif /* !HAVE_BN_DIV_3_WORDS */
224 
225 /*
226  * BN_div_internal computes quotient := numerator / divisor, rounding towards
227  * zero and setting remainder such that quotient * divisor + remainder equals
228  * the numerator. Thus:
229  *
230  *   quotient->neg  == numerator->neg ^ divisor->neg   (unless result is zero)
231  *   remainder->neg == numerator->neg           (unless the remainder is zero)
232  *
233  * If either the quotient or remainder is NULL, the respective value is not
234  * returned.
235  */
236 static int
BN_div_internal(BIGNUM * quotient,BIGNUM * remainder,const BIGNUM * numerator,const BIGNUM * divisor,BN_CTX * ctx,int ct)237 BN_div_internal(BIGNUM *quotient, BIGNUM *remainder, const BIGNUM *numerator,
238     const BIGNUM *divisor, BN_CTX *ctx, int ct)
239 {
240 	int norm_shift, i, loop, r_neg;
241 	BIGNUM *tmp, wnum, *snum, *sdiv, *res;
242 	BN_ULONG *resp, *wnump;
243 	BN_ULONG d0, d1;
244 	int num_n, div_n;
245 	int no_branch = 0;
246 	int ret = 0;
247 
248 	BN_CTX_start(ctx);
249 
250 	/* Invalid zero-padding would have particularly bad consequences. */
251 	if (numerator->top > 0 && numerator->d[numerator->top - 1] == 0) {
252 		BNerror(BN_R_NOT_INITIALIZED);
253 		goto err;
254 	}
255 
256 	if (ct)
257 		no_branch = 1;
258 
259 	if (BN_is_zero(divisor)) {
260 		BNerror(BN_R_DIV_BY_ZERO);
261 		goto err;
262 	}
263 
264 	if (!no_branch) {
265 		if (BN_ucmp(numerator, divisor) < 0) {
266 			if (remainder != NULL) {
267 				if (!bn_copy(remainder, numerator))
268 					goto err;
269 			}
270 			if (quotient != NULL)
271 				BN_zero(quotient);
272 
273 			goto done;
274 		}
275 	}
276 
277 	if ((tmp = BN_CTX_get(ctx)) == NULL)
278 		goto err;
279 	if ((snum = BN_CTX_get(ctx)) == NULL)
280 		goto err;
281 	if ((sdiv = BN_CTX_get(ctx)) == NULL)
282 		goto err;
283 	if ((res = quotient) == NULL) {
284 		if ((res = BN_CTX_get(ctx)) == NULL)
285 			goto err;
286 	}
287 
288 	/* First we normalise the numbers. */
289 	norm_shift = BN_BITS2 - BN_num_bits(divisor) % BN_BITS2;
290 	if (!BN_lshift(sdiv, divisor, norm_shift))
291 		goto err;
292 	sdiv->neg = 0;
293 	norm_shift += BN_BITS2;
294 	if (!BN_lshift(snum, numerator, norm_shift))
295 		goto err;
296 	snum->neg = 0;
297 
298 	if (no_branch) {
299 		/*
300 		 * Since we don't know whether snum is larger than sdiv, we pad
301 		 * snum with enough zeroes without changing its value.
302 		 */
303 		if (snum->top <= sdiv->top + 1) {
304 			if (!bn_wexpand(snum, sdiv->top + 2))
305 				goto err;
306 			for (i = snum->top; i < sdiv->top + 2; i++)
307 				snum->d[i] = 0;
308 			snum->top = sdiv->top + 2;
309 		} else {
310 			if (!bn_wexpand(snum, snum->top + 1))
311 				goto err;
312 			snum->d[snum->top] = 0;
313 			snum->top++;
314 		}
315 	}
316 
317 	div_n = sdiv->top;
318 	num_n = snum->top;
319 	loop = num_n - div_n;
320 
321 	/*
322 	 * Setup a 'window' into snum - this is the part that corresponds to the
323 	 * current 'area' being divided.
324 	 */
325 	wnum.neg = 0;
326 	wnum.d = &(snum->d[loop]);
327 	wnum.top = div_n;
328 	/* only needed when BN_ucmp messes up the values between top and max */
329 	wnum.dmax  = snum->dmax - loop; /* so we don't step out of bounds */
330 	wnum.flags = snum->flags | BN_FLG_STATIC_DATA;
331 
332 	/* Get the top 2 words of sdiv */
333 	/* div_n=sdiv->top; */
334 	d0 = sdiv->d[div_n - 1];
335 	d1 = (div_n == 1) ? 0 : sdiv->d[div_n - 2];
336 
337 	/* pointer to the 'top' of snum */
338 	wnump = &(snum->d[num_n - 1]);
339 
340 	/* Setup to 'res' */
341 	if (!bn_wexpand(res, (loop + 1)))
342 		goto err;
343 	res->top = loop - no_branch;
344 	r_neg = numerator->neg ^ divisor->neg;
345 	resp = &(res->d[loop - 1]);
346 
347 	/* space for temp */
348 	if (!bn_wexpand(tmp, (div_n + 1)))
349 		goto err;
350 
351 	if (!no_branch) {
352 		if (BN_ucmp(&wnum, sdiv) >= 0) {
353 			bn_sub_words(wnum.d, wnum.d, sdiv->d, div_n);
354 			*resp = 1;
355 		} else
356 			res->top--;
357 	}
358 
359 	/*
360 	 * If res->top == 0 then clear the neg value otherwise decrease the resp
361 	 * pointer.
362 	 */
363 	if (res->top == 0)
364 		res->neg = 0;
365 	else
366 		resp--;
367 
368 	for (i = 0; i < loop - 1; i++, wnump--, resp--) {
369 		BN_ULONG q, l0;
370 
371 		/*
372 		 * The first part of the loop uses the top two words of snum and
373 		 * sdiv to calculate a BN_ULONG q such that:
374 		 *
375 		 *  | wnum - sdiv * q | < sdiv
376 		 */
377 		q = bn_div_3_words(wnump, d1, d0);
378 		l0 = bn_mul_words(tmp->d, sdiv->d, div_n, q);
379 		tmp->d[div_n] = l0;
380 		wnum.d--;
381 
382 		/*
383 		 * Ignore top values of the bignums just sub the two BN_ULONG
384 		 * arrays with bn_sub_words.
385 		 */
386 		if (bn_sub_words(wnum.d, wnum.d, tmp->d, div_n + 1)) {
387 			/*
388 			 * Note: As we have considered only the leading two
389 			 * BN_ULONGs in the calculation of q, sdiv * q might be
390 			 * greater than wnum (but then (q-1) * sdiv is less or
391 			 * equal than wnum).
392 			 */
393 			q--;
394 			if (bn_add_words(wnum.d, wnum.d, sdiv->d, div_n)) {
395 				/*
396 				 * We can't have an overflow here (assuming
397 				 * that q != 0, but if q == 0 then tmp is
398 				 * zero anyway).
399 				 */
400 				(*wnump)++;
401 			}
402 		}
403 		/* store part of the result */
404 		*resp = q;
405 	}
406 
407 	bn_correct_top(snum);
408 
409 	if (remainder != NULL) {
410 		/*
411 		 * Keep a copy of the neg flag in numerator because if
412 		 * remainder == numerator, BN_rshift() will overwrite it.
413 		 */
414 		int neg = numerator->neg;
415 
416 		BN_rshift(remainder, snum, norm_shift);
417 		BN_set_negative(remainder, neg);
418 	}
419 
420 	if (no_branch)
421 		bn_correct_top(res);
422 
423 	BN_set_negative(res, r_neg);
424 
425  done:
426 	ret = 1;
427  err:
428 	BN_CTX_end(ctx);
429 
430 	return ret;
431 }
432 
433 int
BN_div(BIGNUM * quotient,BIGNUM * remainder,const BIGNUM * numerator,const BIGNUM * divisor,BN_CTX * ctx)434 BN_div(BIGNUM *quotient, BIGNUM *remainder, const BIGNUM *numerator,
435     const BIGNUM *divisor, BN_CTX *ctx)
436 {
437 	int ct;
438 
439 	ct = BN_get_flags(numerator, BN_FLG_CONSTTIME) != 0 ||
440 	    BN_get_flags(divisor, BN_FLG_CONSTTIME) != 0;
441 
442 	return BN_div_internal(quotient, remainder, numerator, divisor, ctx, ct);
443 }
444 LCRYPTO_ALIAS(BN_div);
445 
446 int
BN_div_nonct(BIGNUM * quotient,BIGNUM * remainder,const BIGNUM * numerator,const BIGNUM * divisor,BN_CTX * ctx)447 BN_div_nonct(BIGNUM *quotient, BIGNUM *remainder, const BIGNUM *numerator,
448     const BIGNUM *divisor, BN_CTX *ctx)
449 {
450 	return BN_div_internal(quotient, remainder, numerator, divisor, ctx, 0);
451 }
452 
453 int
BN_div_ct(BIGNUM * quotient,BIGNUM * remainder,const BIGNUM * numerator,const BIGNUM * divisor,BN_CTX * ctx)454 BN_div_ct(BIGNUM *quotient, BIGNUM *remainder, const BIGNUM *numerator,
455     const BIGNUM *divisor, BN_CTX *ctx)
456 {
457 	return BN_div_internal(quotient, remainder, numerator, divisor, ctx, 1);
458 }
459