xref: /aosp_15_r20/external/boringssl/src/crypto/fipsmodule/bn/mul.c (revision 8fb009dc861624b67b6cdb62ea21f0f22d0c584b)
1 /* Copyright (C) 1995-1998 Eric Young ([email protected])
2  * All rights reserved.
3  *
4  * This package is an SSL implementation written
5  * by Eric Young ([email protected]).
6  * The implementation was written so as to conform with Netscapes SSL.
7  *
8  * This library is free for commercial and non-commercial use as long as
9  * the following conditions are aheared to.  The following conditions
10  * apply to all code found in this distribution, be it the RC4, RSA,
11  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
12  * included with this distribution is covered by the same copyright terms
13  * except that the holder is Tim Hudson ([email protected]).
14  *
15  * Copyright remains Eric Young's, and as such any Copyright notices in
16  * the code are not to be removed.
17  * If this package is used in a product, Eric Young should be given attribution
18  * as the author of the parts of the library used.
19  * This can be in the form of a textual message at program startup or
20  * in documentation (online or textual) provided with the package.
21  *
22  * Redistribution and use in source and binary forms, with or without
23  * modification, are permitted provided that the following conditions
24  * are met:
25  * 1. Redistributions of source code must retain the copyright
26  *    notice, this list of conditions and the following disclaimer.
27  * 2. Redistributions in binary form must reproduce the above copyright
28  *    notice, this list of conditions and the following disclaimer in the
29  *    documentation and/or other materials provided with the distribution.
30  * 3. All advertising materials mentioning features or use of this software
31  *    must display the following acknowledgement:
32  *    "This product includes cryptographic software written by
33  *     Eric Young ([email protected])"
34  *    The word 'cryptographic' can be left out if the rouines from the library
35  *    being used are not cryptographic related :-).
36  * 4. If you include any Windows specific code (or a derivative thereof) from
37  *    the apps directory (application code) you must include an acknowledgement:
38  *    "This product includes software written by Tim Hudson ([email protected])"
39  *
40  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
41  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
44  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50  * SUCH DAMAGE.
51  *
52  * The licence and distribution terms for any publically available version or
53  * derivative of this code cannot be changed.  i.e. this code cannot simply be
54  * copied and put under another distribution licence
55  * [including the GNU Public Licence.] */
56 
57 #include <openssl/bn.h>
58 
59 #include <assert.h>
60 #include <stdlib.h>
61 #include <string.h>
62 
63 #include <openssl/err.h>
64 #include <openssl/mem.h>
65 
66 #include "internal.h"
67 #include "../../internal.h"
68 
69 
70 #define BN_MUL_RECURSIVE_SIZE_NORMAL 16
71 #define BN_SQR_RECURSIVE_SIZE_NORMAL BN_MUL_RECURSIVE_SIZE_NORMAL
72 
73 
bn_abs_sub_words(BN_ULONG * r,const BN_ULONG * a,const BN_ULONG * b,size_t num,BN_ULONG * tmp)74 static void bn_abs_sub_words(BN_ULONG *r, const BN_ULONG *a, const BN_ULONG *b,
75                              size_t num, BN_ULONG *tmp) {
76   BN_ULONG borrow = bn_sub_words(tmp, a, b, num);
77   bn_sub_words(r, b, a, num);
78   bn_select_words(r, 0 - borrow, r /* tmp < 0 */, tmp /* tmp >= 0 */, num);
79 }
80 
bn_mul_normal(BN_ULONG * r,const BN_ULONG * a,size_t na,const BN_ULONG * b,size_t nb)81 static void bn_mul_normal(BN_ULONG *r, const BN_ULONG *a, size_t na,
82                           const BN_ULONG *b, size_t nb) {
83   if (na < nb) {
84     size_t itmp = na;
85     na = nb;
86     nb = itmp;
87     const BN_ULONG *ltmp = a;
88     a = b;
89     b = ltmp;
90   }
91   BN_ULONG *rr = &(r[na]);
92   if (nb == 0) {
93     OPENSSL_memset(r, 0, na * sizeof(BN_ULONG));
94     return;
95   }
96   rr[0] = bn_mul_words(r, a, na, b[0]);
97 
98   for (;;) {
99     if (--nb == 0) {
100       return;
101     }
102     rr[1] = bn_mul_add_words(&(r[1]), a, na, b[1]);
103     if (--nb == 0) {
104       return;
105     }
106     rr[2] = bn_mul_add_words(&(r[2]), a, na, b[2]);
107     if (--nb == 0) {
108       return;
109     }
110     rr[3] = bn_mul_add_words(&(r[3]), a, na, b[3]);
111     if (--nb == 0) {
112       return;
113     }
114     rr[4] = bn_mul_add_words(&(r[4]), a, na, b[4]);
115     rr += 4;
116     r += 4;
117     b += 4;
118   }
119 }
120 
121 // bn_sub_part_words sets |r| to |a| - |b|. It returns the borrow bit, which is
122 // one if the operation underflowed and zero otherwise. |cl| is the common
123 // length, that is, the shorter of len(a) or len(b). |dl| is the delta length,
124 // that is, len(a) - len(b). |r|'s length matches the larger of |a| and |b|, or
125 // cl + abs(dl).
126 //
127 // TODO(davidben): Make this take |size_t|. The |cl| + |dl| calling convention
128 // is confusing.
bn_sub_part_words(BN_ULONG * r,const BN_ULONG * a,const BN_ULONG * b,int cl,int dl)129 static BN_ULONG bn_sub_part_words(BN_ULONG *r, const BN_ULONG *a,
130                                   const BN_ULONG *b, int cl, int dl) {
131   assert(cl >= 0);
132   BN_ULONG borrow = bn_sub_words(r, a, b, cl);
133   if (dl == 0) {
134     return borrow;
135   }
136 
137   r += cl;
138   a += cl;
139   b += cl;
140 
141   if (dl < 0) {
142     // |a| is shorter than |b|. Complete the subtraction as if the excess words
143     // in |a| were zeros.
144     dl = -dl;
145     for (int i = 0; i < dl; i++) {
146       r[i] = CRYPTO_subc_w(0, b[i], borrow, &borrow);
147     }
148   } else {
149     // |b| is shorter than |a|. Complete the subtraction as if the excess words
150     // in |b| were zeros.
151     for (int i = 0; i < dl; i++) {
152       r[i] = CRYPTO_subc_w(a[i], 0, borrow, &borrow);
153     }
154   }
155 
156   return borrow;
157 }
158 
159 // bn_abs_sub_part_words computes |r| = |a| - |b|, storing the absolute value
160 // and returning a mask of all ones if the result was negative and all zeros if
161 // the result was positive. |cl| and |dl| follow the |bn_sub_part_words| calling
162 // convention.
163 //
164 // TODO(davidben): Make this take |size_t|. The |cl| + |dl| calling convention
165 // is confusing.
bn_abs_sub_part_words(BN_ULONG * r,const BN_ULONG * a,const BN_ULONG * b,int cl,int dl,BN_ULONG * tmp)166 static BN_ULONG bn_abs_sub_part_words(BN_ULONG *r, const BN_ULONG *a,
167                                       const BN_ULONG *b, int cl, int dl,
168                                       BN_ULONG *tmp) {
169   BN_ULONG borrow = bn_sub_part_words(tmp, a, b, cl, dl);
170   bn_sub_part_words(r, b, a, cl, -dl);
171   int r_len = cl + (dl < 0 ? -dl : dl);
172   borrow = 0 - borrow;
173   bn_select_words(r, borrow, r /* tmp < 0 */, tmp /* tmp >= 0 */, r_len);
174   return borrow;
175 }
176 
bn_abs_sub_consttime(BIGNUM * r,const BIGNUM * a,const BIGNUM * b,BN_CTX * ctx)177 int bn_abs_sub_consttime(BIGNUM *r, const BIGNUM *a, const BIGNUM *b,
178                          BN_CTX *ctx) {
179   int cl = a->width < b->width ? a->width : b->width;
180   int dl = a->width - b->width;
181   int r_len = a->width < b->width ? b->width : a->width;
182   BN_CTX_start(ctx);
183   BIGNUM *tmp = BN_CTX_get(ctx);
184   int ok = tmp != NULL &&
185            bn_wexpand(r, r_len) &&
186            bn_wexpand(tmp, r_len);
187   if (ok) {
188     bn_abs_sub_part_words(r->d, a->d, b->d, cl, dl, tmp->d);
189     r->width = r_len;
190   }
191   BN_CTX_end(ctx);
192   return ok;
193 }
194 
195 // Karatsuba recursive multiplication algorithm
196 // (cf. Knuth, The Art of Computer Programming, Vol. 2)
197 
198 // bn_mul_recursive sets |r| to |a| * |b|, using |t| as scratch space. |r| has
199 // length 2*|n2|, |a| has length |n2| + |dna|, |b| has length |n2| + |dnb|, and
200 // |t| has length 4*|n2|. |n2| must be a power of two. Finally, we must have
201 // -|BN_MUL_RECURSIVE_SIZE_NORMAL|/2 <= |dna| <= 0 and
202 // -|BN_MUL_RECURSIVE_SIZE_NORMAL|/2 <= |dnb| <= 0.
203 //
204 // TODO(davidben): Simplify and |size_t| the calling convention around lengths
205 // here.
bn_mul_recursive(BN_ULONG * r,const BN_ULONG * a,const BN_ULONG * b,int n2,int dna,int dnb,BN_ULONG * t)206 static void bn_mul_recursive(BN_ULONG *r, const BN_ULONG *a, const BN_ULONG *b,
207                              int n2, int dna, int dnb, BN_ULONG *t) {
208   // |n2| is a power of two.
209   assert(n2 != 0 && (n2 & (n2 - 1)) == 0);
210   // Check |dna| and |dnb| are in range.
211   assert(-BN_MUL_RECURSIVE_SIZE_NORMAL/2 <= dna && dna <= 0);
212   assert(-BN_MUL_RECURSIVE_SIZE_NORMAL/2 <= dnb && dnb <= 0);
213 
214   // Only call bn_mul_comba 8 if n2 == 8 and the
215   // two arrays are complete [steve]
216   if (n2 == 8 && dna == 0 && dnb == 0) {
217     bn_mul_comba8(r, a, b);
218     return;
219   }
220 
221   // Else do normal multiply
222   if (n2 < BN_MUL_RECURSIVE_SIZE_NORMAL) {
223     bn_mul_normal(r, a, n2 + dna, b, n2 + dnb);
224     if (dna + dnb < 0) {
225       OPENSSL_memset(&r[2 * n2 + dna + dnb], 0,
226                      sizeof(BN_ULONG) * -(dna + dnb));
227     }
228     return;
229   }
230 
231   // Split |a| and |b| into a0,a1 and b0,b1, where a0 and b0 have size |n|.
232   // Split |t| into t0,t1,t2,t3, each of size |n|, with the remaining 4*|n| used
233   // for recursive calls.
234   // Split |r| into r0,r1,r2,r3. We must contribute a0*b0 to r0,r1, a0*a1+b0*b1
235   // to r1,r2, and a1*b1 to r2,r3. The middle term we will compute as:
236   //
237   //   a0*a1 + b0*b1 = (a0 - a1)*(b1 - b0) + a1*b1 + a0*b0
238   //
239   // Note that we know |n| >= |BN_MUL_RECURSIVE_SIZE_NORMAL|/2 above, so
240   // |tna| and |tnb| are non-negative.
241   int n = n2 / 2, tna = n + dna, tnb = n + dnb;
242 
243   // t0 = a0 - a1 and t1 = b1 - b0. The result will be multiplied, so we XOR
244   // their sign masks, giving the sign of (a0 - a1)*(b1 - b0). t0 and t1
245   // themselves store the absolute value.
246   BN_ULONG neg = bn_abs_sub_part_words(t, a, &a[n], tna, n - tna, &t[n2]);
247   neg ^= bn_abs_sub_part_words(&t[n], &b[n], b, tnb, tnb - n, &t[n2]);
248 
249   // Compute:
250   // t2,t3 = t0 * t1 = |(a0 - a1)*(b1 - b0)|
251   // r0,r1 = a0 * b0
252   // r2,r3 = a1 * b1
253   if (n == 4 && dna == 0 && dnb == 0) {
254     bn_mul_comba4(&t[n2], t, &t[n]);
255 
256     bn_mul_comba4(r, a, b);
257     bn_mul_comba4(&r[n2], &a[n], &b[n]);
258   } else if (n == 8 && dna == 0 && dnb == 0) {
259     bn_mul_comba8(&t[n2], t, &t[n]);
260 
261     bn_mul_comba8(r, a, b);
262     bn_mul_comba8(&r[n2], &a[n], &b[n]);
263   } else {
264     BN_ULONG *p = &t[n2 * 2];
265     bn_mul_recursive(&t[n2], t, &t[n], n, 0, 0, p);
266     bn_mul_recursive(r, a, b, n, 0, 0, p);
267     bn_mul_recursive(&r[n2], &a[n], &b[n], n, dna, dnb, p);
268   }
269 
270   // t0,t1,c = r0,r1 + r2,r3 = a0*b0 + a1*b1
271   BN_ULONG c = bn_add_words(t, r, &r[n2], n2);
272 
273   // t2,t3,c = t0,t1,c + neg*t2,t3 = (a0 - a1)*(b1 - b0) + a1*b1 + a0*b0.
274   // The second term is stored as the absolute value, so we do this with a
275   // constant-time select.
276   BN_ULONG c_neg = c - bn_sub_words(&t[n2 * 2], t, &t[n2], n2);
277   BN_ULONG c_pos = c + bn_add_words(&t[n2], t, &t[n2], n2);
278   bn_select_words(&t[n2], neg, &t[n2 * 2], &t[n2], n2);
279   static_assert(sizeof(BN_ULONG) <= sizeof(crypto_word_t),
280                 "crypto_word_t is too small");
281   c = constant_time_select_w(neg, c_neg, c_pos);
282 
283   // We now have our three components. Add them together.
284   // r1,r2,c = r1,r2 + t2,t3,c
285   c += bn_add_words(&r[n], &r[n], &t[n2], n2);
286 
287   // Propagate the carry bit to the end.
288   for (int i = n + n2; i < n2 + n2; i++) {
289     BN_ULONG old = r[i];
290     r[i] = old + c;
291     c = r[i] < old;
292   }
293 
294   // The product should fit without carries.
295   declassify_assert(c == 0);
296 }
297 
298 // bn_mul_part_recursive sets |r| to |a| * |b|, using |t| as scratch space. |r|
299 // has length 4*|n|, |a| has length |n| + |tna|, |b| has length |n| + |tnb|, and
300 // |t| has length 8*|n|. |n| must be a power of two. Additionally, we must have
301 // 0 <= tna < n and 0 <= tnb < n, and |tna| and |tnb| must differ by at most
302 // one.
303 //
304 // TODO(davidben): Make this take |size_t| and perhaps the actual lengths of |a|
305 // and |b|.
bn_mul_part_recursive(BN_ULONG * r,const BN_ULONG * a,const BN_ULONG * b,int n,int tna,int tnb,BN_ULONG * t)306 static void bn_mul_part_recursive(BN_ULONG *r, const BN_ULONG *a,
307                                   const BN_ULONG *b, int n, int tna, int tnb,
308                                   BN_ULONG *t) {
309   // |n| is a power of two.
310   assert(n != 0 && (n & (n - 1)) == 0);
311   // Check |tna| and |tnb| are in range.
312   assert(0 <= tna && tna < n);
313   assert(0 <= tnb && tnb < n);
314   assert(-1 <= tna - tnb && tna - tnb <= 1);
315 
316   int n2 = n * 2;
317   if (n < 8) {
318     bn_mul_normal(r, a, n + tna, b, n + tnb);
319     OPENSSL_memset(r + n2 + tna + tnb, 0, n2 - tna - tnb);
320     return;
321   }
322 
323   // Split |a| and |b| into a0,a1 and b0,b1, where a0 and b0 have size |n|. |a1|
324   // and |b1| have size |tna| and |tnb|, respectively.
325   // Split |t| into t0,t1,t2,t3, each of size |n|, with the remaining 4*|n| used
326   // for recursive calls.
327   // Split |r| into r0,r1,r2,r3. We must contribute a0*b0 to r0,r1, a0*a1+b0*b1
328   // to r1,r2, and a1*b1 to r2,r3. The middle term we will compute as:
329   //
330   //   a0*a1 + b0*b1 = (a0 - a1)*(b1 - b0) + a1*b1 + a0*b0
331 
332   // t0 = a0 - a1 and t1 = b1 - b0. The result will be multiplied, so we XOR
333   // their sign masks, giving the sign of (a0 - a1)*(b1 - b0). t0 and t1
334   // themselves store the absolute value.
335   BN_ULONG neg = bn_abs_sub_part_words(t, a, &a[n], tna, n - tna, &t[n2]);
336   neg ^= bn_abs_sub_part_words(&t[n], &b[n], b, tnb, tnb - n, &t[n2]);
337 
338   // Compute:
339   // t2,t3 = t0 * t1 = |(a0 - a1)*(b1 - b0)|
340   // r0,r1 = a0 * b0
341   // r2,r3 = a1 * b1
342   if (n == 8) {
343     bn_mul_comba8(&t[n2], t, &t[n]);
344     bn_mul_comba8(r, a, b);
345 
346     bn_mul_normal(&r[n2], &a[n], tna, &b[n], tnb);
347     // |bn_mul_normal| only writes |tna| + |tna| words. Zero the rest.
348     OPENSSL_memset(&r[n2 + tna + tnb], 0, sizeof(BN_ULONG) * (n2 - tna - tnb));
349   } else {
350     BN_ULONG *p = &t[n2 * 2];
351     bn_mul_recursive(&t[n2], t, &t[n], n, 0, 0, p);
352     bn_mul_recursive(r, a, b, n, 0, 0, p);
353 
354     OPENSSL_memset(&r[n2], 0, sizeof(BN_ULONG) * n2);
355     if (tna < BN_MUL_RECURSIVE_SIZE_NORMAL &&
356         tnb < BN_MUL_RECURSIVE_SIZE_NORMAL) {
357       bn_mul_normal(&r[n2], &a[n], tna, &b[n], tnb);
358     } else {
359       int i = n;
360       for (;;) {
361         i /= 2;
362         if (i < tna || i < tnb) {
363           // E.g., n == 16, i == 8 and tna == 11. |tna| and |tnb| are within one
364           // of each other, so if |tna| is larger and tna > i, then we know
365           // tnb >= i, and this call is valid.
366           bn_mul_part_recursive(&r[n2], &a[n], &b[n], i, tna - i, tnb - i, p);
367           break;
368         }
369         if (i == tna || i == tnb) {
370           // If there is only a bottom half to the number, just do it. We know
371           // the larger of |tna - i| and |tnb - i| is zero. The other is zero or
372           // -1 by because of |tna| and |tnb| differ by at most one.
373           bn_mul_recursive(&r[n2], &a[n], &b[n], i, tna - i, tnb - i, p);
374           break;
375         }
376 
377         // This loop will eventually terminate when |i| falls below
378         // |BN_MUL_RECURSIVE_SIZE_NORMAL| because we know one of |tna| and |tnb|
379         // exceeds that.
380       }
381     }
382   }
383 
384   // t0,t1,c = r0,r1 + r2,r3 = a0*b0 + a1*b1
385   BN_ULONG c = bn_add_words(t, r, &r[n2], n2);
386 
387   // t2,t3,c = t0,t1,c + neg*t2,t3 = (a0 - a1)*(b1 - b0) + a1*b1 + a0*b0.
388   // The second term is stored as the absolute value, so we do this with a
389   // constant-time select.
390   BN_ULONG c_neg = c - bn_sub_words(&t[n2 * 2], t, &t[n2], n2);
391   BN_ULONG c_pos = c + bn_add_words(&t[n2], t, &t[n2], n2);
392   bn_select_words(&t[n2], neg, &t[n2 * 2], &t[n2], n2);
393   static_assert(sizeof(BN_ULONG) <= sizeof(crypto_word_t),
394                 "crypto_word_t is too small");
395   c = constant_time_select_w(neg, c_neg, c_pos);
396 
397   // We now have our three components. Add them together.
398   // r1,r2,c = r1,r2 + t2,t3,c
399   c += bn_add_words(&r[n], &r[n], &t[n2], n2);
400 
401   // Propagate the carry bit to the end.
402   for (int i = n + n2; i < n2 + n2; i++) {
403     BN_ULONG old = r[i];
404     r[i] = old + c;
405     c = r[i] < old;
406   }
407 
408   // The product should fit without carries.
409   declassify_assert(c == 0);
410 }
411 
412 // bn_mul_impl implements |BN_mul| and |bn_mul_consttime|. Note this function
413 // breaks |BIGNUM| invariants and may return a negative zero. This is handled by
414 // the callers.
bn_mul_impl(BIGNUM * r,const BIGNUM * a,const BIGNUM * b,BN_CTX * ctx)415 static int bn_mul_impl(BIGNUM *r, const BIGNUM *a, const BIGNUM *b,
416                        BN_CTX *ctx) {
417   int al = a->width;
418   int bl = b->width;
419   if (al == 0 || bl == 0) {
420     BN_zero(r);
421     return 1;
422   }
423 
424   int ret = 0;
425   BIGNUM *rr;
426   BN_CTX_start(ctx);
427   if (r == a || r == b) {
428     rr = BN_CTX_get(ctx);
429     if (rr == NULL) {
430       goto err;
431     }
432   } else {
433     rr = r;
434   }
435   rr->neg = a->neg ^ b->neg;
436 
437   int i = al - bl;
438   if (i == 0) {
439     if (al == 8) {
440       if (!bn_wexpand(rr, 16)) {
441         goto err;
442       }
443       rr->width = 16;
444       bn_mul_comba8(rr->d, a->d, b->d);
445       goto end;
446     }
447   }
448 
449   int top = al + bl;
450   static const int kMulNormalSize = 16;
451   if (al >= kMulNormalSize && bl >= kMulNormalSize) {
452     if (-1 <= i && i <= 1) {
453       // Find the largest power of two less than or equal to the larger length.
454       int j;
455       if (i >= 0) {
456         j = BN_num_bits_word((BN_ULONG)al);
457       } else {
458         j = BN_num_bits_word((BN_ULONG)bl);
459       }
460       j = 1 << (j - 1);
461       assert(j <= al || j <= bl);
462       BIGNUM *t = BN_CTX_get(ctx);
463       if (t == NULL) {
464         goto err;
465       }
466       if (al > j || bl > j) {
467         // We know |al| and |bl| are at most one from each other, so if al > j,
468         // bl >= j, and vice versa. Thus we can use |bn_mul_part_recursive|.
469         //
470         // TODO(davidben): This codepath is almost unused in standard
471         // algorithms. Is this optimization necessary? See notes in
472         // https://boringssl-review.googlesource.com/q/I0bd604e2cd6a75c266f64476c23a730ca1721ea6
473         assert(al >= j && bl >= j);
474         if (!bn_wexpand(t, j * 8) ||
475             !bn_wexpand(rr, j * 4)) {
476           goto err;
477         }
478         bn_mul_part_recursive(rr->d, a->d, b->d, j, al - j, bl - j, t->d);
479       } else {
480         // al <= j && bl <= j. Additionally, we know j <= al or j <= bl, so one
481         // of al - j or bl - j is zero. The other, by the bound on |i| above, is
482         // zero or -1. Thus, we can use |bn_mul_recursive|.
483         if (!bn_wexpand(t, j * 4) ||
484             !bn_wexpand(rr, j * 2)) {
485           goto err;
486         }
487         bn_mul_recursive(rr->d, a->d, b->d, j, al - j, bl - j, t->d);
488       }
489       rr->width = top;
490       goto end;
491     }
492   }
493 
494   if (!bn_wexpand(rr, top)) {
495     goto err;
496   }
497   rr->width = top;
498   bn_mul_normal(rr->d, a->d, al, b->d, bl);
499 
500 end:
501   if (r != rr && !BN_copy(r, rr)) {
502     goto err;
503   }
504   ret = 1;
505 
506 err:
507   BN_CTX_end(ctx);
508   return ret;
509 }
510 
BN_mul(BIGNUM * r,const BIGNUM * a,const BIGNUM * b,BN_CTX * ctx)511 int BN_mul(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx) {
512   if (!bn_mul_impl(r, a, b, ctx)) {
513     return 0;
514   }
515 
516   // This additionally fixes any negative zeros created by |bn_mul_impl|.
517   bn_set_minimal_width(r);
518   return 1;
519 }
520 
bn_mul_consttime(BIGNUM * r,const BIGNUM * a,const BIGNUM * b,BN_CTX * ctx)521 int bn_mul_consttime(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx) {
522   // Prevent negative zeros.
523   if (a->neg || b->neg) {
524     OPENSSL_PUT_ERROR(BN, BN_R_NEGATIVE_NUMBER);
525     return 0;
526   }
527 
528   return bn_mul_impl(r, a, b, ctx);
529 }
530 
bn_mul_small(BN_ULONG * r,size_t num_r,const BN_ULONG * a,size_t num_a,const BN_ULONG * b,size_t num_b)531 void bn_mul_small(BN_ULONG *r, size_t num_r, const BN_ULONG *a, size_t num_a,
532                   const BN_ULONG *b, size_t num_b) {
533   if (num_r != num_a + num_b) {
534     abort();
535   }
536   // TODO(davidben): Should this call |bn_mul_comba4| too? |BN_mul| does not
537   // hit that code.
538   if (num_a == 8 && num_b == 8) {
539     bn_mul_comba8(r, a, b);
540   } else {
541     bn_mul_normal(r, a, num_a, b, num_b);
542   }
543 }
544 
545 // tmp must have 2*n words
bn_sqr_normal(BN_ULONG * r,const BN_ULONG * a,size_t n,BN_ULONG * tmp)546 static void bn_sqr_normal(BN_ULONG *r, const BN_ULONG *a, size_t n,
547                           BN_ULONG *tmp) {
548   if (n == 0) {
549     return;
550   }
551 
552   size_t max = n * 2;
553   const BN_ULONG *ap = a;
554   BN_ULONG *rp = r;
555   rp[0] = rp[max - 1] = 0;
556   rp++;
557 
558   // Compute the contribution of a[i] * a[j] for all i < j.
559   if (n > 1) {
560     ap++;
561     rp[n - 1] = bn_mul_words(rp, ap, n - 1, ap[-1]);
562     rp += 2;
563   }
564   if (n > 2) {
565     for (size_t i = n - 2; i > 0; i--) {
566       ap++;
567       rp[i] = bn_mul_add_words(rp, ap, i, ap[-1]);
568       rp += 2;
569     }
570   }
571 
572   // The final result fits in |max| words, so none of the following operations
573   // will overflow.
574 
575   // Double |r|, giving the contribution of a[i] * a[j] for all i != j.
576   bn_add_words(r, r, r, max);
577 
578   // Add in the contribution of a[i] * a[i] for all i.
579   bn_sqr_words(tmp, a, n);
580   bn_add_words(r, r, tmp, max);
581 }
582 
583 // bn_sqr_recursive sets |r| to |a|^2, using |t| as scratch space. |r| has
584 // length 2*|n2|, |a| has length |n2|, and |t| has length 4*|n2|. |n2| must be
585 // a power of two.
bn_sqr_recursive(BN_ULONG * r,const BN_ULONG * a,size_t n2,BN_ULONG * t)586 static void bn_sqr_recursive(BN_ULONG *r, const BN_ULONG *a, size_t n2,
587                              BN_ULONG *t) {
588   // |n2| is a power of two.
589   assert(n2 != 0 && (n2 & (n2 - 1)) == 0);
590 
591   if (n2 == 4) {
592     bn_sqr_comba4(r, a);
593     return;
594   }
595   if (n2 == 8) {
596     bn_sqr_comba8(r, a);
597     return;
598   }
599   if (n2 < BN_SQR_RECURSIVE_SIZE_NORMAL) {
600     bn_sqr_normal(r, a, n2, t);
601     return;
602   }
603 
604   // Split |a| into a0,a1, each of size |n|.
605   // Split |t| into t0,t1,t2,t3, each of size |n|, with the remaining 4*|n| used
606   // for recursive calls.
607   // Split |r| into r0,r1,r2,r3. We must contribute a0^2 to r0,r1, 2*a0*a1 to
608   // r1,r2, and a1^2 to r2,r3.
609   size_t n = n2 / 2;
610   BN_ULONG *t_recursive = &t[n2 * 2];
611 
612   // t0 = |a0 - a1|.
613   bn_abs_sub_words(t, a, &a[n], n, &t[n]);
614   // t2,t3 = t0^2 = |a0 - a1|^2 = a0^2 - 2*a0*a1 + a1^2
615   bn_sqr_recursive(&t[n2], t, n, t_recursive);
616 
617   // r0,r1 = a0^2
618   bn_sqr_recursive(r, a, n, t_recursive);
619 
620   // r2,r3 = a1^2
621   bn_sqr_recursive(&r[n2], &a[n], n, t_recursive);
622 
623   // t0,t1,c = r0,r1 + r2,r3 = a0^2 + a1^2
624   BN_ULONG c = bn_add_words(t, r, &r[n2], n2);
625   // t2,t3,c = t0,t1,c - t2,t3 = 2*a0*a1
626   c -= bn_sub_words(&t[n2], t, &t[n2], n2);
627 
628   // We now have our three components. Add them together.
629   // r1,r2,c = r1,r2 + t2,t3,c
630   c += bn_add_words(&r[n], &r[n], &t[n2], n2);
631 
632   // Propagate the carry bit to the end.
633   for (size_t i = n + n2; i < n2 + n2; i++) {
634     BN_ULONG old = r[i];
635     r[i] = old + c;
636     c = r[i] < old;
637   }
638 
639   // The square should fit without carries.
640   assert(c == 0);
641 }
642 
BN_mul_word(BIGNUM * bn,BN_ULONG w)643 int BN_mul_word(BIGNUM *bn, BN_ULONG w) {
644   if (!bn->width) {
645     return 1;
646   }
647 
648   if (w == 0) {
649     BN_zero(bn);
650     return 1;
651   }
652 
653   BN_ULONG ll = bn_mul_words(bn->d, bn->d, bn->width, w);
654   if (ll) {
655     if (!bn_wexpand(bn, bn->width + 1)) {
656       return 0;
657     }
658     bn->d[bn->width++] = ll;
659   }
660 
661   return 1;
662 }
663 
bn_sqr_consttime(BIGNUM * r,const BIGNUM * a,BN_CTX * ctx)664 int bn_sqr_consttime(BIGNUM *r, const BIGNUM *a, BN_CTX *ctx) {
665   int al = a->width;
666   if (al <= 0) {
667     r->width = 0;
668     r->neg = 0;
669     return 1;
670   }
671 
672   int ret = 0;
673   BN_CTX_start(ctx);
674   BIGNUM *rr = (a != r) ? r : BN_CTX_get(ctx);
675   BIGNUM *tmp = BN_CTX_get(ctx);
676   if (!rr || !tmp) {
677     goto err;
678   }
679 
680   int max = 2 * al;  // Non-zero (from above)
681   if (!bn_wexpand(rr, max)) {
682     goto err;
683   }
684 
685   if (al == 4) {
686     bn_sqr_comba4(rr->d, a->d);
687   } else if (al == 8) {
688     bn_sqr_comba8(rr->d, a->d);
689   } else {
690     if (al < BN_SQR_RECURSIVE_SIZE_NORMAL) {
691       BN_ULONG t[BN_SQR_RECURSIVE_SIZE_NORMAL * 2];
692       bn_sqr_normal(rr->d, a->d, al, t);
693     } else {
694       // If |al| is a power of two, we can use |bn_sqr_recursive|.
695       if (al != 0 && (al & (al - 1)) == 0) {
696         if (!bn_wexpand(tmp, al * 4)) {
697           goto err;
698         }
699         bn_sqr_recursive(rr->d, a->d, al, tmp->d);
700       } else {
701         if (!bn_wexpand(tmp, max)) {
702           goto err;
703         }
704         bn_sqr_normal(rr->d, a->d, al, tmp->d);
705       }
706     }
707   }
708 
709   rr->neg = 0;
710   rr->width = max;
711 
712   if (rr != r && !BN_copy(r, rr)) {
713     goto err;
714   }
715   ret = 1;
716 
717 err:
718   BN_CTX_end(ctx);
719   return ret;
720 }
721 
BN_sqr(BIGNUM * r,const BIGNUM * a,BN_CTX * ctx)722 int BN_sqr(BIGNUM *r, const BIGNUM *a, BN_CTX *ctx) {
723   if (!bn_sqr_consttime(r, a, ctx)) {
724     return 0;
725   }
726 
727   bn_set_minimal_width(r);
728   return 1;
729 }
730 
bn_sqr_small(BN_ULONG * r,size_t num_r,const BN_ULONG * a,size_t num_a)731 void bn_sqr_small(BN_ULONG *r, size_t num_r, const BN_ULONG *a, size_t num_a) {
732   if (num_r != 2 * num_a || num_a > BN_SMALL_MAX_WORDS) {
733     abort();
734   }
735   if (num_a == 4) {
736     bn_sqr_comba4(r, a);
737   } else if (num_a == 8) {
738     bn_sqr_comba8(r, a);
739   } else {
740     BN_ULONG tmp[2 * BN_SMALL_MAX_WORDS];
741     bn_sqr_normal(r, a, num_a, tmp);
742     OPENSSL_cleanse(tmp, 2 * num_a * sizeof(BN_ULONG));
743   }
744 }
745