doc: update FIPS provider version information
[openssl.git] / test / bntest.c
1 /*
2  * Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9 #include <assert.h>
10 #include <errno.h>
11 #include <stdio.h>
12 #include <string.h>
13 #ifdef __TANDEM
14 # include <strings.h> /* strcasecmp */
15 #endif
16 #include <ctype.h>
17
18 #include <openssl/bn.h>
19 #include <openssl/crypto.h>
20 #include <openssl/err.h>
21 #include <openssl/rand.h>
22 #include "internal/nelem.h"
23 #include "internal/numbers.h"
24 #include "testutil.h"
25
26 /*
27  * Things in boring, not in openssl.
28  */
29 #define HAVE_BN_SQRT 0
30
31 typedef struct filetest_st {
32     const char *name;
33     int (*func)(STANZA *s);
34 } FILETEST;
35
36 typedef struct mpitest_st {
37     const char *base10;
38     const char *mpi;
39     size_t mpi_len;
40 } MPITEST;
41
42 static const int NUM0 = 100;           /* number of tests */
43 static const int NUM1 = 50;            /* additional tests for some functions */
44 static const int NUM_PRIME_TESTS = 20;
45 static BN_CTX *ctx;
46
47 /*
48  * Polynomial coefficients used in GFM tests.
49  */
50 #ifndef OPENSSL_NO_EC2M
51 static int p0[] = { 163, 7, 6, 3, 0, -1 };
52 static int p1[] = { 193, 15, 0, -1 };
53 #endif
54
55 /*
56  * Look for |key| in the stanza and return it or NULL if not found.
57  */
58 static const char *findattr(STANZA *s, const char *key)
59 {
60     int i = s->numpairs;
61     PAIR *pp = s->pairs;
62
63     for ( ; --i >= 0; pp++)
64         if (OPENSSL_strcasecmp(pp->key, key) == 0)
65             return pp->value;
66     return NULL;
67 }
68
69 /*
70  * Parse BIGNUM from sparse hex-strings, return |BN_hex2bn| result.
71  */
72 static int parse_bigBN(BIGNUM **out, const char *bn_strings[])
73 {
74     char *bigstring = glue_strings(bn_strings, NULL);
75     int ret = BN_hex2bn(out, bigstring);
76
77     OPENSSL_free(bigstring);
78     return ret;
79 }
80
81 /*
82  * Parse BIGNUM, return number of bytes parsed.
83  */
84 static int parseBN(BIGNUM **out, const char *in)
85 {
86     *out = NULL;
87     return BN_hex2bn(out, in);
88 }
89
90 static int parsedecBN(BIGNUM **out, const char *in)
91 {
92     *out = NULL;
93     return BN_dec2bn(out, in);
94 }
95
96 static BIGNUM *getBN(STANZA *s, const char *attribute)
97 {
98     const char *hex;
99     BIGNUM *ret = NULL;
100
101     if ((hex = findattr(s, attribute)) == NULL) {
102         TEST_error("%s:%d: Can't find %s", s->test_file, s->start, attribute);
103         return NULL;
104     }
105
106     if (parseBN(&ret, hex) != (int)strlen(hex)) {
107         TEST_error("Could not decode '%s'", hex);
108         return NULL;
109     }
110     return ret;
111 }
112
113 static int getint(STANZA *s, int *out, const char *attribute)
114 {
115     BIGNUM *ret;
116     BN_ULONG word;
117     int st = 0;
118
119     if (!TEST_ptr(ret = getBN(s, attribute))
120             || !TEST_ulong_le(word = BN_get_word(ret), INT_MAX))
121         goto err;
122
123     *out = (int)word;
124     st = 1;
125  err:
126     BN_free(ret);
127     return st;
128 }
129
130 static int equalBN(const char *op, const BIGNUM *expected, const BIGNUM *actual)
131 {
132     if (BN_cmp(expected, actual) == 0)
133         return 1;
134
135     TEST_error("unexpected %s value", op);
136     TEST_BN_eq(expected, actual);
137     return 0;
138 }
139
140 /*
141  * Return a "random" flag for if a BN should be negated.
142  */
143 static int rand_neg(void)
144 {
145     static unsigned int neg = 0;
146     static int sign[8] = { 0, 0, 0, 1, 1, 0, 1, 1 };
147
148     return sign[(neg++) % 8];
149 }
150
151 static int test_swap(void)
152 {
153     BIGNUM *a = NULL, *b = NULL, *c = NULL, *d = NULL;
154     int top, cond, st = 0;
155
156     if (!TEST_ptr(a = BN_new())
157             || !TEST_ptr(b = BN_new())
158             || !TEST_ptr(c = BN_new())
159             || !TEST_ptr(d = BN_new()))
160         goto err;
161
162     if (!(TEST_true(BN_bntest_rand(a, 1024, 1, 0))
163             && TEST_true(BN_bntest_rand(b, 1024, 1, 0))
164             && TEST_ptr(BN_copy(c, a))
165             && TEST_ptr(BN_copy(d, b))))
166         goto err;
167     top = BN_num_bits(a) / BN_BITS2;
168
169     /* regular swap */
170     BN_swap(a, b);
171     if (!equalBN("swap", a, d)
172             || !equalBN("swap", b, c))
173         goto err;
174
175     /* regular swap: same pointer */
176     BN_swap(a, a);
177     if (!equalBN("swap with same pointer", a, d))
178         goto err;
179
180     /* conditional swap: true */
181     cond = 1;
182     BN_consttime_swap(cond, a, b, top);
183     if (!equalBN("cswap true", a, c)
184             || !equalBN("cswap true", b, d))
185         goto err;
186
187     /* conditional swap: true, same pointer */
188     BN_consttime_swap(cond, a, a, top);
189     if (!equalBN("cswap true", a, c))
190         goto err;
191
192     /* conditional swap: false */
193     cond = 0;
194     BN_consttime_swap(cond, a, b, top);
195     if (!equalBN("cswap false", a, c)
196             || !equalBN("cswap false", b, d))
197         goto err;
198
199     /* conditional swap: false, same pointer */
200     BN_consttime_swap(cond, a, a, top);
201     if (!equalBN("cswap false", a, c))
202         goto err;
203
204     /* same tests but checking flag swap */
205     BN_set_flags(a, BN_FLG_CONSTTIME);
206
207     BN_swap(a, b);
208     if (!equalBN("swap, flags", a, d)
209             || !equalBN("swap, flags", b, c)
210             || !TEST_true(BN_get_flags(b, BN_FLG_CONSTTIME))
211             || !TEST_false(BN_get_flags(a, BN_FLG_CONSTTIME)))
212         goto err;
213
214     cond = 1;
215     BN_consttime_swap(cond, a, b, top);
216     if (!equalBN("cswap true, flags", a, c)
217             || !equalBN("cswap true, flags", b, d)
218             || !TEST_true(BN_get_flags(a, BN_FLG_CONSTTIME))
219             || !TEST_false(BN_get_flags(b, BN_FLG_CONSTTIME)))
220         goto err;
221
222     cond = 0;
223     BN_consttime_swap(cond, a, b, top);
224     if (!equalBN("cswap false, flags", a, c)
225             || !equalBN("cswap false, flags", b, d)
226             || !TEST_true(BN_get_flags(a, BN_FLG_CONSTTIME))
227             || !TEST_false(BN_get_flags(b, BN_FLG_CONSTTIME)))
228         goto err;
229
230     st = 1;
231  err:
232     BN_free(a);
233     BN_free(b);
234     BN_free(c);
235     BN_free(d);
236     return st;
237 }
238
239 static int test_sub(void)
240 {
241     BIGNUM *a = NULL, *b = NULL, *c = NULL;
242     int i, st = 0;
243
244     if (!TEST_ptr(a = BN_new())
245             || !TEST_ptr(b = BN_new())
246             || !TEST_ptr(c = BN_new()))
247         goto err;
248
249     for (i = 0; i < NUM0 + NUM1; i++) {
250         if (i < NUM1) {
251             if (!(TEST_true(BN_bntest_rand(a, 512, 0, 0)))
252                     && TEST_ptr(BN_copy(b, a))
253                     && TEST_int_ne(BN_set_bit(a, i), 0)
254                     && TEST_true(BN_add_word(b, i)))
255                 goto err;
256         } else {
257             if (!TEST_true(BN_bntest_rand(b, 400 + i - NUM1, 0, 0)))
258                 goto err;
259             BN_set_negative(a, rand_neg());
260             BN_set_negative(b, rand_neg());
261         }
262         if (!(TEST_true(BN_sub(c, a, b))
263                 && TEST_true(BN_add(c, c, b))
264                 && TEST_true(BN_sub(c, c, a))
265                 && TEST_BN_eq_zero(c)))
266             goto err;
267     }
268     st = 1;
269  err:
270     BN_free(a);
271     BN_free(b);
272     BN_free(c);
273     return st;
274 }
275
276 static int test_div_recip(void)
277 {
278     BIGNUM *a = NULL, *b = NULL, *c = NULL, *d = NULL, *e = NULL;
279     BN_RECP_CTX *recp = NULL;
280     int st = 0, i;
281
282     if (!TEST_ptr(a = BN_new())
283             || !TEST_ptr(b = BN_new())
284             || !TEST_ptr(c = BN_new())
285             || !TEST_ptr(d = BN_new())
286             || !TEST_ptr(e = BN_new())
287             || !TEST_ptr(recp = BN_RECP_CTX_new()))
288         goto err;
289
290     for (i = 0; i < NUM0 + NUM1; i++) {
291         if (i < NUM1) {
292             if (!(TEST_true(BN_bntest_rand(a, 400, 0, 0))
293                     && TEST_ptr(BN_copy(b, a))
294                     && TEST_true(BN_lshift(a, a, i))
295                     && TEST_true(BN_add_word(a, i))))
296                 goto err;
297         } else {
298             if (!(TEST_true(BN_bntest_rand(b, 50 + 3 * (i - NUM1), 0, 0))))
299                 goto err;
300         }
301         BN_set_negative(a, rand_neg());
302         BN_set_negative(b, rand_neg());
303         if (!(TEST_true(BN_RECP_CTX_set(recp, b, ctx))
304                 && TEST_true(BN_div_recp(d, c, a, recp, ctx))
305                 && TEST_true(BN_mul(e, d, b, ctx))
306                 && TEST_true(BN_add(d, e, c))
307                 && TEST_true(BN_sub(d, d, a))
308                 && TEST_BN_eq_zero(d)))
309             goto err;
310     }
311     st = 1;
312  err:
313     BN_free(a);
314     BN_free(b);
315     BN_free(c);
316     BN_free(d);
317     BN_free(e);
318     BN_RECP_CTX_free(recp);
319     return st;
320 }
321
322 static struct {
323     int n, divisor, result, remainder;
324 } signed_mod_tests[] = {
325     {  10,   3,   3,   1 },
326     { -10,   3,  -3,  -1 },
327     {  10,  -3,  -3,   1 },
328     { -10,  -3,   3,  -1 },
329 };
330
331 static BIGNUM *set_signed_bn(int value)
332 {
333     BIGNUM *bn = BN_new();
334
335     if (bn == NULL)
336         return NULL;
337     if (!BN_set_word(bn, value < 0 ? -value : value)) {
338         BN_free(bn);
339         return NULL;
340     }
341     BN_set_negative(bn, value < 0);
342     return bn;
343 }
344
345 static int test_signed_mod_replace_ab(int n)
346 {
347     BIGNUM *a = NULL, *b = NULL, *c = NULL, *d = NULL;
348     int st = 0;
349
350     if (!TEST_ptr(a = set_signed_bn(signed_mod_tests[n].n))
351             || !TEST_ptr(b = set_signed_bn(signed_mod_tests[n].divisor))
352             || !TEST_ptr(c = set_signed_bn(signed_mod_tests[n].result))
353             || !TEST_ptr(d = set_signed_bn(signed_mod_tests[n].remainder)))
354         goto err;
355
356     if (TEST_true(BN_div(a, b, a, b, ctx))
357             && TEST_BN_eq(a, c)
358             && TEST_BN_eq(b, d))
359         st = 1;
360  err:
361     BN_free(a);
362     BN_free(b);
363     BN_free(c);
364     BN_free(d);
365     return st;
366 }
367
368 static int test_signed_mod_replace_ba(int n)
369 {
370     BIGNUM *a = NULL, *b = NULL, *c = NULL, *d = NULL;
371     int st = 0;
372
373     if (!TEST_ptr(a = set_signed_bn(signed_mod_tests[n].n))
374             || !TEST_ptr(b = set_signed_bn(signed_mod_tests[n].divisor))
375             || !TEST_ptr(c = set_signed_bn(signed_mod_tests[n].result))
376             || !TEST_ptr(d = set_signed_bn(signed_mod_tests[n].remainder)))
377         goto err;
378
379     if (TEST_true(BN_div(b, a, a, b, ctx))
380             && TEST_BN_eq(b, c)
381             && TEST_BN_eq(a, d))
382         st = 1;
383  err:
384     BN_free(a);
385     BN_free(b);
386     BN_free(c);
387     BN_free(d);
388     return st;
389 }
390
391 static int test_mod(void)
392 {
393     BIGNUM *a = NULL, *b = NULL, *c = NULL, *d = NULL, *e = NULL;
394     int st = 0, i;
395
396     if (!TEST_ptr(a = BN_new())
397             || !TEST_ptr(b = BN_new())
398             || !TEST_ptr(c = BN_new())
399             || !TEST_ptr(d = BN_new())
400             || !TEST_ptr(e = BN_new()))
401         goto err;
402
403     if (!(TEST_true(BN_bntest_rand(a, 1024, 0, 0))))
404         goto err;
405     for (i = 0; i < NUM0; i++) {
406         if (!(TEST_true(BN_bntest_rand(b, 450 + i * 10, 0, 0))))
407             goto err;
408         BN_set_negative(a, rand_neg());
409         BN_set_negative(b, rand_neg());
410         if (!(TEST_true(BN_mod(c, a, b, ctx))
411                 && TEST_true(BN_div(d, e, a, b, ctx))
412                 && TEST_BN_eq(e, c)
413                 && TEST_true(BN_mul(c, d, b, ctx))
414                 && TEST_true(BN_add(d, c, e))
415                 && TEST_BN_eq(d, a)))
416             goto err;
417     }
418     st = 1;
419  err:
420     BN_free(a);
421     BN_free(b);
422     BN_free(c);
423     BN_free(d);
424     BN_free(e);
425     return st;
426 }
427
428 static const char *bn1strings[] = {
429     "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
430     "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
431     "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
432     "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
433     "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
434     "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
435     "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
436     "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000000000FFFFFFFF00",
437     "0000000000000000000000000000000000000000000000000000000000000000",
438     "0000000000000000000000000000000000000000000000000000000000000000",
439     "0000000000000000000000000000000000000000000000000000000000000000",
440     "0000000000000000000000000000000000000000000000000000000000000000",
441     "0000000000000000000000000000000000000000000000000000000000000000",
442     "0000000000000000000000000000000000000000000000000000000000000000",
443     "0000000000000000000000000000000000000000000000000000000000000000",
444     "00000000000000000000000000000000000000000000000000FFFFFFFFFFFFFF",
445     NULL
446 };
447
448 static const char *bn2strings[] = {
449     "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
450     "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
451     "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
452     "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
453     "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
454     "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
455     "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
456     "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000000000FFFFFFFF0000000000",
457     "0000000000000000000000000000000000000000000000000000000000000000",
458     "0000000000000000000000000000000000000000000000000000000000000000",
459     "0000000000000000000000000000000000000000000000000000000000000000",
460     "0000000000000000000000000000000000000000000000000000000000000000",
461     "0000000000000000000000000000000000000000000000000000000000000000",
462     "0000000000000000000000000000000000000000000000000000000000000000",
463     "0000000000000000000000000000000000000000000000000000000000000000",
464     "000000000000000000000000000000000000000000FFFFFFFFFFFFFF00000000",
465     NULL
466 };
467
468 /*
469  * Test constant-time modular exponentiation with 1024-bit inputs, which on
470  * x86_64 cause a different code branch to be taken.
471  */
472 static int test_modexp_mont5(void)
473 {
474     BIGNUM *a = NULL, *p = NULL, *m = NULL, *d = NULL, *e = NULL;
475     BIGNUM *b = NULL, *n = NULL, *c = NULL;
476     BN_MONT_CTX *mont = NULL;
477     int st = 0;
478
479     if (!TEST_ptr(a = BN_new())
480             || !TEST_ptr(p = BN_new())
481             || !TEST_ptr(m = BN_new())
482             || !TEST_ptr(d = BN_new())
483             || !TEST_ptr(e = BN_new())
484             || !TEST_ptr(b = BN_new())
485             || !TEST_ptr(n = BN_new())
486             || !TEST_ptr(c = BN_new())
487             || !TEST_ptr(mont = BN_MONT_CTX_new()))
488         goto err;
489
490     /* must be odd for montgomery */
491     if (!(TEST_true(BN_bntest_rand(m, 1024, 0, 1))
492             /* Zero exponent */
493             && TEST_true(BN_bntest_rand(a, 1024, 0, 0))))
494         goto err;
495     BN_zero(p);
496
497     if (!TEST_true(BN_mod_exp_mont_consttime(d, a, p, m, ctx, NULL)))
498         goto err;
499     if (!TEST_BN_eq_one(d))
500         goto err;
501
502     /* Regression test for carry bug in mulx4x_mont */
503     if (!(TEST_true(BN_hex2bn(&a,
504         "7878787878787878787878787878787878787878787878787878787878787878"
505         "7878787878787878787878787878787878787878787878787878787878787878"
506         "7878787878787878787878787878787878787878787878787878787878787878"
507         "7878787878787878787878787878787878787878787878787878787878787878"))
508         && TEST_true(BN_hex2bn(&b,
509         "095D72C08C097BA488C5E439C655A192EAFB6380073D8C2664668EDDB4060744"
510         "E16E57FB4EDB9AE10A0CEFCDC28A894F689A128379DB279D48A2E20849D68593"
511         "9B7803BCF46CEBF5C533FB0DD35B080593DE5472E3FE5DB951B8BFF9B4CB8F03"
512         "9CC638A5EE8CDD703719F8000E6A9F63BEED5F2FCD52FF293EA05A251BB4AB81"))
513         && TEST_true(BN_hex2bn(&n,
514         "D78AF684E71DB0C39CFF4E64FB9DB567132CB9C50CC98009FEB820B26F2DED9B"
515         "91B9B5E2B83AE0AE4EB4E0523CA726BFBE969B89FD754F674CE99118C3F2D1C5"
516         "D81FDC7C54E02B60262B241D53C040E99E45826ECA37A804668E690E1AFC1CA4"
517         "2C9A15D84D4954425F0B7642FC0BD9D7B24E2618D2DCC9B729D944BADACFDDAF"))))
518         goto err;
519
520     if (!(TEST_true(BN_MONT_CTX_set(mont, n, ctx))
521             && TEST_true(BN_mod_mul_montgomery(c, a, b, mont, ctx))
522             && TEST_true(BN_mod_mul_montgomery(d, b, a, mont, ctx))
523             && TEST_BN_eq(c, d)))
524         goto err;
525
526     /* Regression test for carry bug in sqr[x]8x_mont */
527     if (!(TEST_true(parse_bigBN(&n, bn1strings))
528             && TEST_true(parse_bigBN(&a, bn2strings))))
529         goto err;
530     BN_free(b);
531     if (!(TEST_ptr(b = BN_dup(a))
532             && TEST_true(BN_MONT_CTX_set(mont, n, ctx))
533             && TEST_true(BN_mod_mul_montgomery(c, a, a, mont, ctx))
534             && TEST_true(BN_mod_mul_montgomery(d, a, b, mont, ctx))
535             && TEST_BN_eq(c, d)))
536         goto err;
537
538     /* Regression test for carry bug in bn_sqrx8x_internal */
539     {
540         static const char *ahex[] = {
541                       "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
542             "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
543             "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
544             "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
545             "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF8FFEADBCFC4DAE7FFF908E92820306B",
546             "9544D954000000006C0000000000000000000000000000000000000000000000",
547             "00000000000000000000FF030202FFFFF8FFEBDBCFC4DAE7FFF908E92820306B",
548             "9544D954000000006C000000FF0302030000000000FFFFFFFFFFFFFFFFFFFFFF",
549             "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF01FC00FF02FFFFFFFF",
550             "00FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00FCFD",
551             "FCFFFFFFFFFF000000000000000000FF0302030000000000FFFFFFFFFFFFFFFF",
552             "FF00FCFDFDFF030202FF00000000FFFFFFFFFFFFFFFFFF00FCFDFCFFFFFFFFFF",
553             NULL
554         };
555         static const char *nhex[] = {
556                       "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
557             "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
558             "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
559             "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
560             "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF8F8F8F8000000",
561             "00000010000000006C0000000000000000000000000000000000000000000000",
562             "00000000000000000000000000000000000000FFFFFFFFFFFFF8F8F8F8000000",
563             "00000010000000006C000000000000000000000000FFFFFFFFFFFFFFFFFFFFFF",
564             "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
565             "00FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
566             "FFFFFFFFFFFF000000000000000000000000000000000000FFFFFFFFFFFFFFFF",
567             "FFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
568             NULL
569         };
570
571         if (!(TEST_true(parse_bigBN(&a, ahex))
572                 && TEST_true(parse_bigBN(&n, nhex))))
573             goto err;
574     }
575     BN_free(b);
576     if (!(TEST_ptr(b = BN_dup(a))
577             && TEST_true(BN_MONT_CTX_set(mont, n, ctx))))
578         goto err;
579
580     if (!TEST_true(BN_mod_mul_montgomery(c, a, a, mont, ctx))
581             || !TEST_true(BN_mod_mul_montgomery(d, a, b, mont, ctx))
582             || !TEST_BN_eq(c, d))
583         goto err;
584
585     /* Regression test for bug in BN_from_montgomery_word */
586     if (!(TEST_true(BN_hex2bn(&a,
587         "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
588         "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
589         "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"))
590          && TEST_true(BN_hex2bn(&n,
591         "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
592         "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"))
593         && TEST_true(BN_MONT_CTX_set(mont, n, ctx))
594         && TEST_false(BN_mod_mul_montgomery(d, a, a, mont, ctx))))
595         goto err;
596
597     /* Regression test for bug in rsaz_1024_mul_avx2 */
598     if (!(TEST_true(BN_hex2bn(&a,
599         "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
600         "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
601         "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
602         "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF2020202020DF"))
603         && TEST_true(BN_hex2bn(&b,
604         "2020202020202020202020202020202020202020202020202020202020202020"
605         "2020202020202020202020202020202020202020202020202020202020202020"
606         "20202020202020FF202020202020202020202020202020202020202020202020"
607         "2020202020202020202020202020202020202020202020202020202020202020"))
608         && TEST_true(BN_hex2bn(&n,
609         "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
610         "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
611         "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
612         "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF2020202020FF"))
613         && TEST_true(BN_MONT_CTX_set(mont, n, ctx))
614         && TEST_true(BN_mod_exp_mont_consttime(c, a, b, n, ctx, mont))
615         && TEST_true(BN_mod_exp_mont(d, a, b, n, ctx, mont))
616         && TEST_BN_eq(c, d)))
617         goto err;
618
619     /*
620      * rsaz_1024_mul_avx2 expects fully-reduced inputs.
621      * BN_mod_exp_mont_consttime should reduce the input first.
622      */
623     if (!(TEST_true(BN_hex2bn(&a,
624         "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
625         "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
626         "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
627         "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF2020202020DF"))
628         && TEST_true(BN_hex2bn(&b,
629         "1FA53F26F8811C58BE0357897AA5E165693230BC9DF5F01DFA6A2D59229EC69D"
630         "9DE6A89C36E3B6957B22D6FAAD5A3C73AE587B710DBE92E83D3A9A3339A085CB"
631         "B58F508CA4F837924BB52CC1698B7FDC2FD74362456A595A5B58E38E38E38E38"
632         "E38E38E38E38E38E38E38E38E38E38E38E38E38E38E38E38E38E38E38E38E38E"))
633         && TEST_true(BN_hex2bn(&n,
634         "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
635         "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
636         "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
637         "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF2020202020DF"))
638         && TEST_true(BN_MONT_CTX_set(mont, n, ctx))
639         && TEST_true(BN_mod_exp_mont_consttime(c, a, b, n, ctx, mont))))
640         goto err;
641     BN_zero(d);
642     if (!TEST_BN_eq(c, d))
643         goto err;
644
645     /*
646      * Regression test for overflow bug in bn_sqr_comba4/8 for
647      * mips-linux-gnu and mipsel-linux-gnu 32bit targets.
648      */
649     {
650         static const char *ehex[] = {
651             "95564994a96c45954227b845a1e99cb939d5a1da99ee91acc962396ae999a9ee",
652             "38603790448f2f7694c242a875f0cad0aae658eba085f312d2febbbd128dd2b5",
653             "8f7d1149f03724215d704344d0d62c587ae3c5939cba4b9b5f3dc5e8e911ef9a",
654             "5ce1a5a749a4989d0d8368f6e1f8cdf3a362a6c97fb02047ff152b480a4ad985",
655             "2d45efdf0770542992afca6a0590d52930434bba96017afbc9f99e112950a8b1",
656             "a359473ec376f329bdae6a19f503be6d4be7393c4e43468831234e27e3838680",
657             "b949390d2e416a3f9759e5349ab4c253f6f29f819a6fe4cbfd27ada34903300e",
658             "da021f62839f5878a36f1bc3085375b00fd5fa3e68d316c0fdace87a97558465",
659             NULL};
660         static const char *phex[] = {
661             "f95dc0f980fbd22e90caa5a387cc4a369f3f830d50dd321c40db8c09a7e1a241",
662             "a536e096622d3280c0c1ba849c1f4a79bf490f60006d081e8cf69960189f0d31",
663             "2cd9e17073a3fba7881b21474a13b334116cb2f5dbf3189a6de3515d0840f053",
664             "c776d3982d391b6d04d642dda5cc6d1640174c09875addb70595658f89efb439",
665             "dc6fbd55f903aadd307982d3f659207f265e1ec6271b274521b7a5e28e8fd7a5",
666             "5df089292820477802a43cf5b6b94e999e8c9944ddebb0d0e95a60f88cb7e813",
667             "ba110d20e1024774107dd02949031864923b3cb8c3f7250d6d1287b0a40db6a4",
668             "7bd5a469518eb65aa207ddc47d8c6e5fc8e0c105be8fc1d4b57b2e27540471d5",
669             NULL};
670         static const char *mhex[] = {
671             "fef15d5ce4625f1bccfbba49fc8439c72bf8202af039a2259678941b60bb4a8f",
672             "2987e965d58fd8cf86a856674d519763d0e1211cc9f8596971050d56d9b35db3",
673             "785866cfbca17cfdbed6060be3629d894f924a89fdc1efc624f80d41a22f1900",
674             "9503fcc3824ef62ccb9208430c26f2d8ceb2c63488ec4c07437aa4c96c43dd8b",
675             "9289ed00a712ff66ee195dc71f5e4ead02172b63c543d69baf495f5fd63ba7bc",
676             "c633bd309c016e37736da92129d0b053d4ab28d21ad7d8b6fab2a8bbdc8ee647",
677             "d2fbcf2cf426cf892e6f5639e0252993965dfb73ccd277407014ea784aaa280c",
678             "b7b03972bc8b0baa72360bdb44b82415b86b2f260f877791cd33ba8f2d65229b",
679             NULL};
680
681         if (!TEST_true(parse_bigBN(&e, ehex))
682                 || !TEST_true(parse_bigBN(&p, phex))
683                 || !TEST_true(parse_bigBN(&m, mhex))
684                 || !TEST_true(BN_mod_exp_mont_consttime(d, e, p, m, ctx, NULL))
685                 || !TEST_true(BN_mod_exp_simple(a, e, p, m, ctx))
686                 || !TEST_BN_eq(a, d))
687             goto err;
688     }
689
690     /* Zero input */
691     if (!TEST_true(BN_bntest_rand(p, 1024, 0, 0)))
692         goto err;
693     BN_zero(a);
694     if (!TEST_true(BN_mod_exp_mont_consttime(d, a, p, m, ctx, NULL))
695             || !TEST_BN_eq_zero(d))
696         goto err;
697
698     /*
699      * Craft an input whose Montgomery representation is 1, i.e., shorter
700      * than the modulus m, in order to test the const time precomputation
701      * scattering/gathering.
702      */
703     if (!(TEST_true(BN_one(a))
704             && TEST_true(BN_MONT_CTX_set(mont, m, ctx))))
705         goto err;
706     if (!TEST_true(BN_from_montgomery(e, a, mont, ctx))
707             || !TEST_true(BN_mod_exp_mont_consttime(d, e, p, m, ctx, NULL))
708             || !TEST_true(BN_mod_exp_simple(a, e, p, m, ctx))
709             || !TEST_BN_eq(a, d))
710         goto err;
711
712     /* Finally, some regular test vectors. */
713     if (!(TEST_true(BN_bntest_rand(e, 1024, 0, 0))
714             && TEST_true(BN_mod_exp_mont_consttime(d, e, p, m, ctx, NULL))
715             && TEST_true(BN_mod_exp_simple(a, e, p, m, ctx))
716             && TEST_BN_eq(a, d)))
717         goto err;
718
719     st = 1;
720
721  err:
722     BN_MONT_CTX_free(mont);
723     BN_free(a);
724     BN_free(p);
725     BN_free(m);
726     BN_free(d);
727     BN_free(e);
728     BN_free(b);
729     BN_free(n);
730     BN_free(c);
731     return st;
732 }
733
734 #ifndef OPENSSL_NO_EC2M
735 static int test_gf2m_add(void)
736 {
737     BIGNUM *a = NULL, *b = NULL, *c = NULL;
738     int i, st = 0;
739
740     if (!TEST_ptr(a = BN_new())
741             || !TEST_ptr(b = BN_new())
742             || !TEST_ptr(c = BN_new()))
743         goto err;
744
745     for (i = 0; i < NUM0; i++) {
746         if (!(TEST_true(BN_rand(a, 512, 0, 0))
747                 && TEST_ptr(BN_copy(b, BN_value_one()))))
748             goto err;
749         BN_set_negative(a, rand_neg());
750         BN_set_negative(b, rand_neg());
751         if (!(TEST_true(BN_GF2m_add(c, a, b))
752                 /* Test that two added values have the correct parity. */
753                 && TEST_false((BN_is_odd(a) && BN_is_odd(c))
754                         || (!BN_is_odd(a) && !BN_is_odd(c)))))
755             goto err;
756         if (!(TEST_true(BN_GF2m_add(c, c, c))
757                 /* Test that c + c = 0. */
758                 && TEST_BN_eq_zero(c)))
759             goto err;
760     }
761     st = 1;
762  err:
763     BN_free(a);
764     BN_free(b);
765     BN_free(c);
766     return st;
767 }
768
769 static int test_gf2m_mod(void)
770 {
771     BIGNUM *a = NULL, *b[2] = {NULL, NULL}, *c = NULL, *d = NULL, *e = NULL;
772     int i, j, st = 0;
773
774     if (!TEST_ptr(a = BN_new())
775             || !TEST_ptr(b[0] = BN_new())
776             || !TEST_ptr(b[1] = BN_new())
777             || !TEST_ptr(c = BN_new())
778             || !TEST_ptr(d = BN_new())
779             || !TEST_ptr(e = BN_new()))
780         goto err;
781
782     if (!(TEST_true(BN_GF2m_arr2poly(p0, b[0]))
783             && TEST_true(BN_GF2m_arr2poly(p1, b[1]))))
784         goto err;
785
786     for (i = 0; i < NUM0; i++) {
787         if (!TEST_true(BN_bntest_rand(a, 1024, 0, 0)))
788             goto err;
789         for (j = 0; j < 2; j++) {
790             if (!(TEST_true(BN_GF2m_mod(c, a, b[j]))
791                     && TEST_true(BN_GF2m_add(d, a, c))
792                     && TEST_true(BN_GF2m_mod(e, d, b[j]))
793                     /* Test that a + (a mod p) mod p == 0. */
794                     && TEST_BN_eq_zero(e)))
795                 goto err;
796         }
797     }
798     st = 1;
799  err:
800     BN_free(a);
801     BN_free(b[0]);
802     BN_free(b[1]);
803     BN_free(c);
804     BN_free(d);
805     BN_free(e);
806     return st;
807 }
808
809 static int test_gf2m_mul(void)
810 {
811     BIGNUM *a, *b[2] = {NULL, NULL}, *c = NULL, *d = NULL;
812     BIGNUM *e = NULL, *f = NULL, *g = NULL, *h = NULL;
813     int i, j, st = 0;
814
815     if (!TEST_ptr(a = BN_new())
816             || !TEST_ptr(b[0] = BN_new())
817             || !TEST_ptr(b[1] = BN_new())
818             || !TEST_ptr(c = BN_new())
819             || !TEST_ptr(d = BN_new())
820             || !TEST_ptr(e = BN_new())
821             || !TEST_ptr(f = BN_new())
822             || !TEST_ptr(g = BN_new())
823             || !TEST_ptr(h = BN_new()))
824         goto err;
825
826     if (!(TEST_true(BN_GF2m_arr2poly(p0, b[0]))
827             && TEST_true(BN_GF2m_arr2poly(p1, b[1]))))
828         goto err;
829
830     for (i = 0; i < NUM0; i++) {
831         if (!(TEST_true(BN_bntest_rand(a, 1024, 0, 0))
832                 && TEST_true(BN_bntest_rand(c, 1024, 0, 0))
833                 && TEST_true(BN_bntest_rand(d, 1024, 0, 0))))
834             goto err;
835         for (j = 0; j < 2; j++) {
836             if (!(TEST_true(BN_GF2m_mod_mul(e, a, c, b[j], ctx))
837                     && TEST_true(BN_GF2m_add(f, a, d))
838                     && TEST_true(BN_GF2m_mod_mul(g, f, c, b[j], ctx))
839                     && TEST_true(BN_GF2m_mod_mul(h, d, c, b[j], ctx))
840                     && TEST_true(BN_GF2m_add(f, e, g))
841                     && TEST_true(BN_GF2m_add(f, f, h))
842                     /* Test that (a+d)*c = a*c + d*c. */
843                     && TEST_BN_eq_zero(f)))
844                 goto err;
845         }
846     }
847     st = 1;
848
849  err:
850     BN_free(a);
851     BN_free(b[0]);
852     BN_free(b[1]);
853     BN_free(c);
854     BN_free(d);
855     BN_free(e);
856     BN_free(f);
857     BN_free(g);
858     BN_free(h);
859     return st;
860 }
861
862 static int test_gf2m_sqr(void)
863 {
864     BIGNUM *a = NULL, *b[2] = {NULL, NULL}, *c = NULL, *d = NULL;
865     int i, j, st = 0;
866
867     if (!TEST_ptr(a = BN_new())
868             || !TEST_ptr(b[0] = BN_new())
869             || !TEST_ptr(b[1] = BN_new())
870             || !TEST_ptr(c = BN_new())
871             || !TEST_ptr(d = BN_new()))
872         goto err;
873
874     if (!(TEST_true(BN_GF2m_arr2poly(p0, b[0]))
875             && TEST_true(BN_GF2m_arr2poly(p1, b[1]))))
876         goto err;
877
878     for (i = 0; i < NUM0; i++) {
879         if (!TEST_true(BN_bntest_rand(a, 1024, 0, 0)))
880                 goto err;
881         for (j = 0; j < 2; j++) {
882             if (!(TEST_true(BN_GF2m_mod_sqr(c, a, b[j], ctx))
883                     && TEST_true(BN_copy(d, a))
884                     && TEST_true(BN_GF2m_mod_mul(d, a, d, b[j], ctx))
885                     && TEST_true(BN_GF2m_add(d, c, d))
886                     /* Test that a*a = a^2. */
887                     && TEST_BN_eq_zero(d)))
888                 goto err;
889         }
890     }
891     st = 1;
892  err:
893     BN_free(a);
894     BN_free(b[0]);
895     BN_free(b[1]);
896     BN_free(c);
897     BN_free(d);
898     return st;
899 }
900
901 static int test_gf2m_modinv(void)
902 {
903     BIGNUM *a = NULL, *b[2] = {NULL, NULL}, *c = NULL, *d = NULL;
904     int i, j, st = 0;
905
906     if (!TEST_ptr(a = BN_new())
907             || !TEST_ptr(b[0] = BN_new())
908             || !TEST_ptr(b[1] = BN_new())
909             || !TEST_ptr(c = BN_new())
910             || !TEST_ptr(d = BN_new()))
911         goto err;
912
913     if (!(TEST_true(BN_GF2m_arr2poly(p0, b[0]))
914             && TEST_true(BN_GF2m_arr2poly(p1, b[1]))))
915         goto err;
916
917     for (i = 0; i < NUM0; i++) {
918         if (!TEST_true(BN_bntest_rand(a, 512, 0, 0)))
919             goto err;
920         for (j = 0; j < 2; j++) {
921             if (!(TEST_true(BN_GF2m_mod_inv(c, a, b[j], ctx))
922                     && TEST_true(BN_GF2m_mod_mul(d, a, c, b[j], ctx))
923                     /* Test that ((1/a)*a) = 1. */
924                     && TEST_BN_eq_one(d)))
925                 goto err;
926         }
927     }
928     st = 1;
929  err:
930     BN_free(a);
931     BN_free(b[0]);
932     BN_free(b[1]);
933     BN_free(c);
934     BN_free(d);
935     return st;
936 }
937
938 static int test_gf2m_moddiv(void)
939 {
940     BIGNUM *a = NULL, *b[2] = {NULL, NULL}, *c = NULL, *d = NULL;
941     BIGNUM *e = NULL, *f = NULL;
942     int i, j, st = 0;
943
944     if (!TEST_ptr(a = BN_new())
945             || !TEST_ptr(b[0] = BN_new())
946             || !TEST_ptr(b[1] = BN_new())
947             || !TEST_ptr(c = BN_new())
948             || !TEST_ptr(d = BN_new())
949             || !TEST_ptr(e = BN_new())
950             || !TEST_ptr(f = BN_new()))
951         goto err;
952
953     if (!(TEST_true(BN_GF2m_arr2poly(p0, b[0]))
954             && TEST_true(BN_GF2m_arr2poly(p1, b[1]))))
955         goto err;
956
957     for (i = 0; i < NUM0; i++) {
958         if (!(TEST_true(BN_bntest_rand(a, 512, 0, 0))
959                 && TEST_true(BN_bntest_rand(c, 512, 0, 0))))
960             goto err;
961         for (j = 0; j < 2; j++) {
962             if (!(TEST_true(BN_GF2m_mod_div(d, a, c, b[j], ctx))
963                     && TEST_true(BN_GF2m_mod_mul(e, d, c, b[j], ctx))
964                     && TEST_true(BN_GF2m_mod_div(f, a, e, b[j], ctx))
965                     /* Test that ((a/c)*c)/a = 1. */
966                     && TEST_BN_eq_one(f)))
967                 goto err;
968         }
969     }
970     st = 1;
971  err:
972     BN_free(a);
973     BN_free(b[0]);
974     BN_free(b[1]);
975     BN_free(c);
976     BN_free(d);
977     BN_free(e);
978     BN_free(f);
979     return st;
980 }
981
982 static int test_gf2m_modexp(void)
983 {
984     BIGNUM *a = NULL, *b[2] = {NULL, NULL}, *c = NULL, *d = NULL;
985     BIGNUM *e = NULL, *f = NULL;
986     int i, j, st = 0;
987
988     if (!TEST_ptr(a = BN_new())
989             || !TEST_ptr(b[0] = BN_new())
990             || !TEST_ptr(b[1] = BN_new())
991             || !TEST_ptr(c = BN_new())
992             || !TEST_ptr(d = BN_new())
993             || !TEST_ptr(e = BN_new())
994             || !TEST_ptr(f = BN_new()))
995         goto err;
996
997     if (!(TEST_true(BN_GF2m_arr2poly(p0, b[0]))
998             && TEST_true(BN_GF2m_arr2poly(p1, b[1]))))
999         goto err;
1000
1001     for (i = 0; i < NUM0; i++) {
1002         if (!(TEST_true(BN_bntest_rand(a, 512, 0, 0))
1003                 && TEST_true(BN_bntest_rand(c, 512, 0, 0))
1004                 && TEST_true(BN_bntest_rand(d, 512, 0, 0))))
1005             goto err;
1006         for (j = 0; j < 2; j++) {
1007             if (!(TEST_true(BN_GF2m_mod_exp(e, a, c, b[j], ctx))
1008                     && TEST_true(BN_GF2m_mod_exp(f, a, d, b[j], ctx))
1009                     && TEST_true(BN_GF2m_mod_mul(e, e, f, b[j], ctx))
1010                     && TEST_true(BN_add(f, c, d))
1011                     && TEST_true(BN_GF2m_mod_exp(f, a, f, b[j], ctx))
1012                     && TEST_true(BN_GF2m_add(f, e, f))
1013                     /* Test that a^(c+d)=a^c*a^d. */
1014                     && TEST_BN_eq_zero(f)))
1015                 goto err;
1016         }
1017     }
1018     st = 1;
1019  err:
1020     BN_free(a);
1021     BN_free(b[0]);
1022     BN_free(b[1]);
1023     BN_free(c);
1024     BN_free(d);
1025     BN_free(e);
1026     BN_free(f);
1027     return st;
1028 }
1029
1030 static int test_gf2m_modsqrt(void)
1031 {
1032     BIGNUM *a = NULL, *b[2] = {NULL, NULL}, *c = NULL, *d = NULL;
1033     BIGNUM *e = NULL, *f = NULL;
1034     int i, j, st = 0;
1035
1036     if (!TEST_ptr(a = BN_new())
1037             || !TEST_ptr(b[0] = BN_new())
1038             || !TEST_ptr(b[1] = BN_new())
1039             || !TEST_ptr(c = BN_new())
1040             || !TEST_ptr(d = BN_new())
1041             || !TEST_ptr(e = BN_new())
1042             || !TEST_ptr(f = BN_new()))
1043         goto err;
1044
1045     if (!(TEST_true(BN_GF2m_arr2poly(p0, b[0]))
1046             && TEST_true(BN_GF2m_arr2poly(p1, b[1]))))
1047         goto err;
1048
1049     for (i = 0; i < NUM0; i++) {
1050         if (!TEST_true(BN_bntest_rand(a, 512, 0, 0)))
1051             goto err;
1052
1053         for (j = 0; j < 2; j++) {
1054             if (!(TEST_true(BN_GF2m_mod(c, a, b[j]))
1055                     && TEST_true(BN_GF2m_mod_sqrt(d, a, b[j], ctx))
1056                     && TEST_true(BN_GF2m_mod_sqr(e, d, b[j], ctx))
1057                     && TEST_true(BN_GF2m_add(f, c, e))
1058                     /* Test that d^2 = a, where d = sqrt(a). */
1059                     && TEST_BN_eq_zero(f)))
1060                 goto err;
1061         }
1062     }
1063     st = 1;
1064  err:
1065     BN_free(a);
1066     BN_free(b[0]);
1067     BN_free(b[1]);
1068     BN_free(c);
1069     BN_free(d);
1070     BN_free(e);
1071     BN_free(f);
1072     return st;
1073 }
1074
1075 static int test_gf2m_modsolvequad(void)
1076 {
1077     BIGNUM *a = NULL, *b[2] = {NULL, NULL}, *c = NULL, *d = NULL;
1078     BIGNUM *e = NULL;
1079     int i, j, s = 0, t, st = 0;
1080
1081     if (!TEST_ptr(a = BN_new())
1082             || !TEST_ptr(b[0] = BN_new())
1083             || !TEST_ptr(b[1] = BN_new())
1084             || !TEST_ptr(c = BN_new())
1085             || !TEST_ptr(d = BN_new())
1086             || !TEST_ptr(e = BN_new()))
1087         goto err;
1088
1089     if (!(TEST_true(BN_GF2m_arr2poly(p0, b[0]))
1090             && TEST_true(BN_GF2m_arr2poly(p1, b[1]))))
1091         goto err;
1092
1093     for (i = 0; i < NUM0; i++) {
1094         if (!TEST_true(BN_bntest_rand(a, 512, 0, 0)))
1095             goto err;
1096         for (j = 0; j < 2; j++) {
1097             t = BN_GF2m_mod_solve_quad(c, a, b[j], ctx);
1098             if (t) {
1099                 s++;
1100                 if (!(TEST_true(BN_GF2m_mod_sqr(d, c, b[j], ctx))
1101                         && TEST_true(BN_GF2m_add(d, c, d))
1102                         && TEST_true(BN_GF2m_mod(e, a, b[j]))
1103                         && TEST_true(BN_GF2m_add(e, e, d))
1104                         /*
1105                          * Test that solution of quadratic c
1106                          * satisfies c^2 + c = a.
1107                          */
1108                         && TEST_BN_eq_zero(e)))
1109                     goto err;
1110             }
1111         }
1112     }
1113     if (!TEST_int_ge(s, 0)) {
1114         TEST_info("%d tests found no roots; probably an error", NUM0);
1115         goto err;
1116     }
1117     st = 1;
1118  err:
1119     BN_free(a);
1120     BN_free(b[0]);
1121     BN_free(b[1]);
1122     BN_free(c);
1123     BN_free(d);
1124     BN_free(e);
1125     return st;
1126 }
1127 #endif
1128
1129 static int test_kronecker(void)
1130 {
1131     BIGNUM *a = NULL, *b = NULL, *r = NULL, *t = NULL;
1132     int i, legendre, kronecker, st = 0;
1133
1134     if (!TEST_ptr(a = BN_new())
1135             || !TEST_ptr(b = BN_new())
1136             || !TEST_ptr(r = BN_new())
1137             || !TEST_ptr(t = BN_new()))
1138         goto err;
1139
1140     /*
1141      * We test BN_kronecker(a, b, ctx) just for b odd (Jacobi symbol). In
1142      * this case we know that if b is prime, then BN_kronecker(a, b, ctx) is
1143      * congruent to $a^{(b-1)/2}$, modulo $b$ (Legendre symbol). So we
1144      * generate a random prime b and compare these values for a number of
1145      * random a's.  (That is, we run the Solovay-Strassen primality test to
1146      * confirm that b is prime, except that we don't want to test whether b
1147      * is prime but whether BN_kronecker works.)
1148      */
1149
1150     if (!TEST_true(BN_generate_prime_ex(b, 512, 0, NULL, NULL, NULL)))
1151         goto err;
1152     BN_set_negative(b, rand_neg());
1153
1154     for (i = 0; i < NUM0; i++) {
1155         if (!TEST_true(BN_bntest_rand(a, 512, 0, 0)))
1156             goto err;
1157         BN_set_negative(a, rand_neg());
1158
1159         /* t := (|b|-1)/2  (note that b is odd) */
1160         if (!TEST_true(BN_copy(t, b)))
1161             goto err;
1162         BN_set_negative(t, 0);
1163         if (!TEST_true(BN_sub_word(t, 1)))
1164             goto err;
1165         if (!TEST_true(BN_rshift1(t, t)))
1166             goto err;
1167         /* r := a^t mod b */
1168         BN_set_negative(b, 0);
1169
1170         if (!TEST_true(BN_mod_exp_recp(r, a, t, b, ctx)))
1171             goto err;
1172         BN_set_negative(b, 1);
1173
1174         if (BN_is_word(r, 1))
1175             legendre = 1;
1176         else if (BN_is_zero(r))
1177             legendre = 0;
1178         else {
1179             if (!TEST_true(BN_add_word(r, 1)))
1180                 goto err;
1181             if (!TEST_int_eq(BN_ucmp(r, b), 0)) {
1182                 TEST_info("Legendre symbol computation failed");
1183                 goto err;
1184             }
1185             legendre = -1;
1186         }
1187
1188         if (!TEST_int_ge(kronecker = BN_kronecker(a, b, ctx), -1))
1189             goto err;
1190         /* we actually need BN_kronecker(a, |b|) */
1191         if (BN_is_negative(a) && BN_is_negative(b))
1192             kronecker = -kronecker;
1193
1194         if (!TEST_int_eq(legendre, kronecker))
1195             goto err;
1196     }
1197
1198     st = 1;
1199  err:
1200     BN_free(a);
1201     BN_free(b);
1202     BN_free(r);
1203     BN_free(t);
1204     return st;
1205 }
1206
1207 static int file_sum(STANZA *s)
1208 {
1209     BIGNUM *a = NULL, *b = NULL, *sum = NULL, *ret = NULL;
1210     BN_ULONG b_word;
1211     int st = 0;
1212
1213     if (!TEST_ptr(a = getBN(s, "A"))
1214             || !TEST_ptr(b = getBN(s, "B"))
1215             || !TEST_ptr(sum = getBN(s, "Sum"))
1216             || !TEST_ptr(ret = BN_new()))
1217         goto err;
1218
1219     if (!TEST_true(BN_add(ret, a, b))
1220             || !equalBN("A + B", sum, ret)
1221             || !TEST_true(BN_sub(ret, sum, a))
1222             || !equalBN("Sum - A", b, ret)
1223             || !TEST_true(BN_sub(ret, sum, b))
1224             || !equalBN("Sum - B", a, ret))
1225         goto err;
1226
1227     /*
1228      * Test that the functions work when |r| and |a| point to the same BIGNUM,
1229      * or when |r| and |b| point to the same BIGNUM.
1230      * There is no test for all of |r|, |a|, and |b| pointint to the same BIGNUM.
1231      */
1232     if (!TEST_true(BN_copy(ret, a))
1233             || !TEST_true(BN_add(ret, ret, b))
1234             || !equalBN("A + B (r is a)", sum, ret)
1235             || !TEST_true(BN_copy(ret, b))
1236             || !TEST_true(BN_add(ret, a, ret))
1237             || !equalBN("A + B (r is b)", sum, ret)
1238             || !TEST_true(BN_copy(ret, sum))
1239             || !TEST_true(BN_sub(ret, ret, a))
1240             || !equalBN("Sum - A (r is a)", b, ret)
1241             || !TEST_true(BN_copy(ret, a))
1242             || !TEST_true(BN_sub(ret, sum, ret))
1243             || !equalBN("Sum - A (r is b)", b, ret)
1244             || !TEST_true(BN_copy(ret, sum))
1245             || !TEST_true(BN_sub(ret, ret, b))
1246             || !equalBN("Sum - B (r is a)", a, ret)
1247             || !TEST_true(BN_copy(ret, b))
1248             || !TEST_true(BN_sub(ret, sum, ret))
1249             || !equalBN("Sum - B (r is b)", a, ret))
1250         goto err;
1251
1252     /*
1253      * Test BN_uadd() and BN_usub() with the prerequisites they are
1254      * documented as having. Note that these functions are frequently used
1255      * when the prerequisites don't hold. In those cases, they are supposed
1256      * to work as if the prerequisite hold, but we don't test that yet.
1257      */
1258     if (!BN_is_negative(a) && !BN_is_negative(b) && BN_cmp(a, b) >= 0) {
1259         if (!TEST_true(BN_uadd(ret, a, b))
1260                 || !equalBN("A +u B", sum, ret)
1261                 || !TEST_true(BN_usub(ret, sum, a))
1262                 || !equalBN("Sum -u A", b, ret)
1263                 || !TEST_true(BN_usub(ret, sum, b))
1264                 || !equalBN("Sum -u B", a, ret))
1265             goto err;
1266         /*
1267          * Test that the functions work when |r| and |a| point to the same
1268          * BIGNUM, or when |r| and |b| point to the same BIGNUM.
1269          * There is no test for all of |r|, |a|, and |b| pointint to the same
1270          * BIGNUM.
1271          */
1272         if (!TEST_true(BN_copy(ret, a))
1273                 || !TEST_true(BN_uadd(ret, ret, b))
1274                 || !equalBN("A +u B (r is a)", sum, ret)
1275                 || !TEST_true(BN_copy(ret, b))
1276                 || !TEST_true(BN_uadd(ret, a, ret))
1277                 || !equalBN("A +u B (r is b)", sum, ret)
1278                 || !TEST_true(BN_copy(ret, sum))
1279                 || !TEST_true(BN_usub(ret, ret, a))
1280                 || !equalBN("Sum -u A (r is a)", b, ret)
1281                 || !TEST_true(BN_copy(ret, a))
1282                 || !TEST_true(BN_usub(ret, sum, ret))
1283                 || !equalBN("Sum -u A (r is b)", b, ret)
1284                 || !TEST_true(BN_copy(ret, sum))
1285                 || !TEST_true(BN_usub(ret, ret, b))
1286                 || !equalBN("Sum -u B (r is a)", a, ret)
1287                 || !TEST_true(BN_copy(ret, b))
1288                 || !TEST_true(BN_usub(ret, sum, ret))
1289                 || !equalBN("Sum -u B (r is b)", a, ret))
1290             goto err;
1291     }
1292
1293     /*
1294      * Test with BN_add_word() and BN_sub_word() if |b| is small enough.
1295      */
1296     b_word = BN_get_word(b);
1297     if (!BN_is_negative(b) && b_word != (BN_ULONG)-1) {
1298         if (!TEST_true(BN_copy(ret, a))
1299                 || !TEST_true(BN_add_word(ret, b_word))
1300                 || !equalBN("A + B (word)", sum, ret)
1301                 || !TEST_true(BN_copy(ret, sum))
1302                 || !TEST_true(BN_sub_word(ret, b_word))
1303                 || !equalBN("Sum - B (word)", a, ret))
1304             goto err;
1305     }
1306     st = 1;
1307
1308  err:
1309     BN_free(a);
1310     BN_free(b);
1311     BN_free(sum);
1312     BN_free(ret);
1313     return st;
1314 }
1315
1316 static int file_lshift1(STANZA *s)
1317 {
1318     BIGNUM *a = NULL, *lshift1 = NULL, *zero = NULL, *ret = NULL;
1319     BIGNUM *two = NULL, *remainder = NULL;
1320     int st = 0;
1321
1322     if (!TEST_ptr(a = getBN(s, "A"))
1323             || !TEST_ptr(lshift1 = getBN(s, "LShift1"))
1324             || !TEST_ptr(zero = BN_new())
1325             || !TEST_ptr(ret = BN_new())
1326             || !TEST_ptr(two = BN_new())
1327             || !TEST_ptr(remainder = BN_new()))
1328         goto err;
1329
1330     BN_zero(zero);
1331
1332     if (!TEST_true(BN_set_word(two, 2))
1333             || !TEST_true(BN_add(ret, a, a))
1334             || !equalBN("A + A", lshift1, ret)
1335             || !TEST_true(BN_mul(ret, a, two, ctx))
1336             || !equalBN("A * 2", lshift1, ret)
1337             || !TEST_true(BN_div(ret, remainder, lshift1, two, ctx))
1338             || !equalBN("LShift1 / 2", a, ret)
1339             || !equalBN("LShift1 % 2", zero, remainder)
1340             || !TEST_true(BN_lshift1(ret, a))
1341             || !equalBN("A << 1", lshift1, ret)
1342             || !TEST_true(BN_rshift1(ret, lshift1))
1343             || !equalBN("LShift >> 1", a, ret)
1344             || !TEST_true(BN_rshift1(ret, lshift1))
1345             || !equalBN("LShift >> 1", a, ret))
1346         goto err;
1347
1348     /* Set the LSB to 1 and test rshift1 again. */
1349     if (!TEST_true(BN_set_bit(lshift1, 0))
1350             || !TEST_true(BN_div(ret, NULL /* rem */ , lshift1, two, ctx))
1351             || !equalBN("(LShift1 | 1) / 2", a, ret)
1352             || !TEST_true(BN_rshift1(ret, lshift1))
1353             || !equalBN("(LShift | 1) >> 1", a, ret))
1354         goto err;
1355
1356     st = 1;
1357  err:
1358     BN_free(a);
1359     BN_free(lshift1);
1360     BN_free(zero);
1361     BN_free(ret);
1362     BN_free(two);
1363     BN_free(remainder);
1364
1365     return st;
1366 }
1367
1368 static int file_lshift(STANZA *s)
1369 {
1370     BIGNUM *a = NULL, *lshift = NULL, *ret = NULL;
1371     int n = 0, st = 0;
1372
1373     if (!TEST_ptr(a = getBN(s, "A"))
1374             || !TEST_ptr(lshift = getBN(s, "LShift"))
1375             || !TEST_ptr(ret = BN_new())
1376             || !getint(s, &n, "N"))
1377         goto err;
1378
1379     if (!TEST_true(BN_lshift(ret, a, n))
1380             || !equalBN("A << N", lshift, ret)
1381             || !TEST_true(BN_rshift(ret, lshift, n))
1382             || !equalBN("A >> N", a, ret))
1383         goto err;
1384
1385     st = 1;
1386  err:
1387     BN_free(a);
1388     BN_free(lshift);
1389     BN_free(ret);
1390     return st;
1391 }
1392
1393 static int file_rshift(STANZA *s)
1394 {
1395     BIGNUM *a = NULL, *rshift = NULL, *ret = NULL;
1396     int n = 0, st = 0;
1397
1398     if (!TEST_ptr(a = getBN(s, "A"))
1399             || !TEST_ptr(rshift = getBN(s, "RShift"))
1400             || !TEST_ptr(ret = BN_new())
1401             || !getint(s, &n, "N"))
1402         goto err;
1403
1404     if (!TEST_true(BN_rshift(ret, a, n))
1405             || !equalBN("A >> N", rshift, ret))
1406         goto err;
1407
1408     /* If N == 1, try with rshift1 as well */
1409     if (n == 1) {
1410         if (!TEST_true(BN_rshift1(ret, a))
1411                 || !equalBN("A >> 1 (rshift1)", rshift, ret))
1412             goto err;
1413     }
1414     st = 1;
1415
1416  err:
1417     BN_free(a);
1418     BN_free(rshift);
1419     BN_free(ret);
1420     return st;
1421 }
1422
1423 static int file_square(STANZA *s)
1424 {
1425     BIGNUM *a = NULL, *square = NULL, *zero = NULL, *ret = NULL;
1426     BIGNUM *remainder = NULL, *tmp = NULL;
1427     int st = 0;
1428
1429     if (!TEST_ptr(a = getBN(s, "A"))
1430             || !TEST_ptr(square = getBN(s, "Square"))
1431             || !TEST_ptr(zero = BN_new())
1432             || !TEST_ptr(ret = BN_new())
1433             || !TEST_ptr(remainder = BN_new()))
1434         goto err;
1435
1436     BN_zero(zero);
1437     if (!TEST_true(BN_sqr(ret, a, ctx))
1438             || !equalBN("A^2", square, ret)
1439             || !TEST_true(BN_mul(ret, a, a, ctx))
1440             || !equalBN("A * A", square, ret)
1441             || !TEST_true(BN_div(ret, remainder, square, a, ctx))
1442             || !equalBN("Square / A", a, ret)
1443             || !equalBN("Square % A", zero, remainder))
1444         goto err;
1445
1446 #if HAVE_BN_SQRT
1447     BN_set_negative(a, 0);
1448     if (!TEST_true(BN_sqrt(ret, square, ctx))
1449             || !equalBN("sqrt(Square)", a, ret))
1450         goto err;
1451
1452     /* BN_sqrt should fail on non-squares and negative numbers. */
1453     if (!TEST_BN_eq_zero(square)) {
1454         if (!TEST_ptr(tmp = BN_new())
1455                 || !TEST_true(BN_copy(tmp, square)))
1456             goto err;
1457         BN_set_negative(tmp, 1);
1458
1459         if (!TEST_int_eq(BN_sqrt(ret, tmp, ctx), 0))
1460             goto err;
1461         ERR_clear_error();
1462
1463         BN_set_negative(tmp, 0);
1464         if (BN_add(tmp, tmp, BN_value_one()))
1465             goto err;
1466         if (!TEST_int_eq(BN_sqrt(ret, tmp, ctx)))
1467             goto err;
1468         ERR_clear_error();
1469     }
1470 #endif
1471
1472     st = 1;
1473  err:
1474     BN_free(a);
1475     BN_free(square);
1476     BN_free(zero);
1477     BN_free(ret);
1478     BN_free(remainder);
1479     BN_free(tmp);
1480     return st;
1481 }
1482
1483 static int file_product(STANZA *s)
1484 {
1485     BIGNUM *a = NULL, *b = NULL, *product = NULL, *ret = NULL;
1486     BIGNUM *remainder = NULL, *zero = NULL;
1487     int st = 0;
1488
1489     if (!TEST_ptr(a = getBN(s, "A"))
1490             || !TEST_ptr(b = getBN(s, "B"))
1491             || !TEST_ptr(product = getBN(s, "Product"))
1492             || !TEST_ptr(ret = BN_new())
1493             || !TEST_ptr(remainder = BN_new())
1494             || !TEST_ptr(zero = BN_new()))
1495         goto err;
1496
1497     BN_zero(zero);
1498
1499     if (!TEST_true(BN_mul(ret, a, b, ctx))
1500             || !equalBN("A * B", product, ret)
1501             || !TEST_true(BN_div(ret, remainder, product, a, ctx))
1502             || !equalBN("Product / A", b, ret)
1503             || !equalBN("Product % A", zero, remainder)
1504             || !TEST_true(BN_div(ret, remainder, product, b, ctx))
1505             || !equalBN("Product / B", a, ret)
1506             || !equalBN("Product % B", zero, remainder))
1507         goto err;
1508
1509     st = 1;
1510  err:
1511     BN_free(a);
1512     BN_free(b);
1513     BN_free(product);
1514     BN_free(ret);
1515     BN_free(remainder);
1516     BN_free(zero);
1517     return st;
1518 }
1519
1520 static int file_quotient(STANZA *s)
1521 {
1522     BIGNUM *a = NULL, *b = NULL, *quotient = NULL, *remainder = NULL;
1523     BIGNUM *ret = NULL, *ret2 = NULL, *nnmod = NULL;
1524     BN_ULONG b_word, ret_word;
1525     int st = 0;
1526
1527     if (!TEST_ptr(a = getBN(s, "A"))
1528             || !TEST_ptr(b = getBN(s, "B"))
1529             || !TEST_ptr(quotient = getBN(s, "Quotient"))
1530             || !TEST_ptr(remainder = getBN(s, "Remainder"))
1531             || !TEST_ptr(ret = BN_new())
1532             || !TEST_ptr(ret2 = BN_new())
1533             || !TEST_ptr(nnmod = BN_new()))
1534         goto err;
1535
1536     if (!TEST_true(BN_div(ret, ret2, a, b, ctx))
1537             || !equalBN("A / B", quotient, ret)
1538             || !equalBN("A % B", remainder, ret2)
1539             || !TEST_true(BN_mul(ret, quotient, b, ctx))
1540             || !TEST_true(BN_add(ret, ret, remainder))
1541             || !equalBN("Quotient * B + Remainder", a, ret))
1542         goto err;
1543
1544     /*
1545      * Test with BN_mod_word() and BN_div_word() if the divisor is
1546      * small enough.
1547      */
1548     b_word = BN_get_word(b);
1549     if (!BN_is_negative(b) && b_word != (BN_ULONG)-1) {
1550         BN_ULONG remainder_word = BN_get_word(remainder);
1551
1552         assert(remainder_word != (BN_ULONG)-1);
1553         if (!TEST_ptr(BN_copy(ret, a)))
1554             goto err;
1555         ret_word = BN_div_word(ret, b_word);
1556         if (ret_word != remainder_word) {
1557 #ifdef BN_DEC_FMT1
1558             TEST_error(
1559                     "Got A %% B (word) = " BN_DEC_FMT1 ", wanted " BN_DEC_FMT1,
1560                     ret_word, remainder_word);
1561 #else
1562             TEST_error("Got A %% B (word) mismatch");
1563 #endif
1564             goto err;
1565         }
1566         if (!equalBN ("A / B (word)", quotient, ret))
1567             goto err;
1568
1569         ret_word = BN_mod_word(a, b_word);
1570         if (ret_word != remainder_word) {
1571 #ifdef BN_DEC_FMT1
1572             TEST_error(
1573                     "Got A %% B (word) = " BN_DEC_FMT1 ", wanted " BN_DEC_FMT1 "",
1574                     ret_word, remainder_word);
1575 #else
1576             TEST_error("Got A %% B (word) mismatch");
1577 #endif
1578             goto err;
1579         }
1580     }
1581
1582     /* Test BN_nnmod. */
1583     if (!BN_is_negative(b)) {
1584         if (!TEST_true(BN_copy(nnmod, remainder))
1585                 || (BN_is_negative(nnmod)
1586                         && !TEST_true(BN_add(nnmod, nnmod, b)))
1587                 || !TEST_true(BN_nnmod(ret, a, b, ctx))
1588                 || !equalBN("A % B (non-negative)", nnmod, ret))
1589             goto err;
1590     }
1591
1592     st = 1;
1593  err:
1594     BN_free(a);
1595     BN_free(b);
1596     BN_free(quotient);
1597     BN_free(remainder);
1598     BN_free(ret);
1599     BN_free(ret2);
1600     BN_free(nnmod);
1601     return st;
1602 }
1603
1604 static int file_modmul(STANZA *s)
1605 {
1606     BIGNUM *a = NULL, *b = NULL, *m = NULL, *mod_mul = NULL, *ret = NULL;
1607     int st = 0;
1608
1609     if (!TEST_ptr(a = getBN(s, "A"))
1610             || !TEST_ptr(b = getBN(s, "B"))
1611             || !TEST_ptr(m = getBN(s, "M"))
1612             || !TEST_ptr(mod_mul = getBN(s, "ModMul"))
1613             || !TEST_ptr(ret = BN_new()))
1614         goto err;
1615
1616     if (!TEST_true(BN_mod_mul(ret, a, b, m, ctx))
1617             || !equalBN("A * B (mod M)", mod_mul, ret))
1618         goto err;
1619
1620     if (BN_is_odd(m)) {
1621         /* Reduce |a| and |b| and test the Montgomery version. */
1622         BN_MONT_CTX *mont = BN_MONT_CTX_new();
1623         BIGNUM *a_tmp = BN_new();
1624         BIGNUM *b_tmp = BN_new();
1625
1626         if (mont == NULL || a_tmp == NULL || b_tmp == NULL
1627                 || !TEST_true(BN_MONT_CTX_set(mont, m, ctx))
1628                 || !TEST_true(BN_nnmod(a_tmp, a, m, ctx))
1629                 || !TEST_true(BN_nnmod(b_tmp, b, m, ctx))
1630                 || !TEST_true(BN_to_montgomery(a_tmp, a_tmp, mont, ctx))
1631                 || !TEST_true(BN_to_montgomery(b_tmp, b_tmp, mont, ctx))
1632                 || !TEST_true(BN_mod_mul_montgomery(ret, a_tmp, b_tmp,
1633                                                     mont, ctx))
1634                 || !TEST_true(BN_from_montgomery(ret, ret, mont, ctx))
1635                 || !equalBN("A * B (mod M) (mont)", mod_mul, ret))
1636             st = 0;
1637         else
1638             st = 1;
1639         BN_MONT_CTX_free(mont);
1640         BN_free(a_tmp);
1641         BN_free(b_tmp);
1642         if (st == 0)
1643             goto err;
1644     }
1645
1646     st = 1;
1647  err:
1648     BN_free(a);
1649     BN_free(b);
1650     BN_free(m);
1651     BN_free(mod_mul);
1652     BN_free(ret);
1653     return st;
1654 }
1655
1656 static int file_modexp(STANZA *s)
1657 {
1658     BIGNUM *a = NULL, *e = NULL, *m = NULL, *mod_exp = NULL, *ret = NULL;
1659     BIGNUM *b = NULL, *c = NULL, *d = NULL;
1660     int st = 0;
1661
1662     if (!TEST_ptr(a = getBN(s, "A"))
1663             || !TEST_ptr(e = getBN(s, "E"))
1664             || !TEST_ptr(m = getBN(s, "M"))
1665             || !TEST_ptr(mod_exp = getBN(s, "ModExp"))
1666             || !TEST_ptr(ret = BN_new())
1667             || !TEST_ptr(d = BN_new()))
1668         goto err;
1669
1670     if (!TEST_true(BN_mod_exp(ret, a, e, m, ctx))
1671             || !equalBN("A ^ E (mod M)", mod_exp, ret))
1672         goto err;
1673
1674     if (BN_is_odd(m)) {
1675         if (!TEST_true(BN_mod_exp_mont(ret, a, e, m, ctx, NULL))
1676                 || !equalBN("A ^ E (mod M) (mont)", mod_exp, ret)
1677                 || !TEST_true(BN_mod_exp_mont_consttime(ret, a, e, m,
1678                                                         ctx, NULL))
1679                 || !equalBN("A ^ E (mod M) (mont const", mod_exp, ret))
1680             goto err;
1681     }
1682
1683     /* Regression test for carry propagation bug in sqr8x_reduction */
1684     BN_hex2bn(&a, "050505050505");
1685     BN_hex2bn(&b, "02");
1686     BN_hex2bn(&c,
1687         "4141414141414141414141274141414141414141414141414141414141414141"
1688         "4141414141414141414141414141414141414141414141414141414141414141"
1689         "4141414141414141414141800000000000000000000000000000000000000000"
1690         "0000000000000000000000000000000000000000000000000000000000000000"
1691         "0000000000000000000000000000000000000000000000000000000000000000"
1692         "0000000000000000000000000000000000000000000000000000000001");
1693     if (!TEST_true(BN_mod_exp(d, a, b, c, ctx))
1694         || !TEST_true(BN_mul(e, a, a, ctx))
1695         || !TEST_BN_eq(d, e))
1696         goto err;
1697
1698     st = 1;
1699  err:
1700     BN_free(a);
1701     BN_free(b);
1702     BN_free(c);
1703     BN_free(d);
1704     BN_free(e);
1705     BN_free(m);
1706     BN_free(mod_exp);
1707     BN_free(ret);
1708     return st;
1709 }
1710
1711 static int file_exp(STANZA *s)
1712 {
1713     BIGNUM *a = NULL, *e = NULL, *exp = NULL, *ret = NULL;
1714     int st = 0;
1715
1716     if (!TEST_ptr(a = getBN(s, "A"))
1717             || !TEST_ptr(e = getBN(s, "E"))
1718             || !TEST_ptr(exp = getBN(s, "Exp"))
1719             || !TEST_ptr(ret = BN_new()))
1720         goto err;
1721
1722     if (!TEST_true(BN_exp(ret, a, e, ctx))
1723             || !equalBN("A ^ E", exp, ret))
1724         goto err;
1725
1726     st = 1;
1727  err:
1728     BN_free(a);
1729     BN_free(e);
1730     BN_free(exp);
1731     BN_free(ret);
1732     return st;
1733 }
1734
1735 static int file_modsqrt(STANZA *s)
1736 {
1737     BIGNUM *a = NULL, *p = NULL, *mod_sqrt = NULL, *ret = NULL, *ret2 = NULL;
1738     int st = 0;
1739
1740     if (!TEST_ptr(a = getBN(s, "A"))
1741             || !TEST_ptr(p = getBN(s, "P"))
1742             || !TEST_ptr(mod_sqrt = getBN(s, "ModSqrt"))
1743             || !TEST_ptr(ret = BN_new())
1744             || !TEST_ptr(ret2 = BN_new()))
1745         goto err;
1746
1747     if (BN_is_negative(mod_sqrt)) {
1748         /* A negative testcase */
1749         if (!TEST_ptr_null(BN_mod_sqrt(ret, a, p, ctx)))
1750             goto err;
1751
1752         st = 1;
1753         goto err;
1754     }
1755
1756     /* There are two possible answers. */
1757     if (!TEST_ptr(BN_mod_sqrt(ret, a, p, ctx))
1758             || !TEST_true(BN_sub(ret2, p, ret)))
1759         goto err;
1760
1761     /* The first condition should NOT be a test. */
1762     if (BN_cmp(ret2, mod_sqrt) != 0
1763             && !equalBN("sqrt(A) (mod P)", mod_sqrt, ret))
1764         goto err;
1765
1766     st = 1;
1767  err:
1768     BN_free(a);
1769     BN_free(p);
1770     BN_free(mod_sqrt);
1771     BN_free(ret);
1772     BN_free(ret2);
1773     return st;
1774 }
1775
1776 static int file_gcd(STANZA *s)
1777 {
1778     BIGNUM *a = NULL, *b = NULL, *gcd = NULL, *ret = NULL;
1779     int st = 0;
1780
1781     if (!TEST_ptr(a = getBN(s, "A"))
1782             || !TEST_ptr(b = getBN(s, "B"))
1783             || !TEST_ptr(gcd = getBN(s, "GCD"))
1784             || !TEST_ptr(ret = BN_new()))
1785         goto err;
1786
1787     if (!TEST_true(BN_gcd(ret, a, b, ctx))
1788             || !equalBN("gcd(A,B)", gcd, ret))
1789         goto err;
1790
1791     st = 1;
1792  err:
1793     BN_free(a);
1794     BN_free(b);
1795     BN_free(gcd);
1796     BN_free(ret);
1797     return st;
1798 }
1799
1800 static int test_bn2padded(void)
1801 {
1802     uint8_t zeros[256], out[256], reference[128];
1803     size_t bytes;
1804     BIGNUM *n;
1805     int st = 0;
1806
1807     /* Test edge case at 0. */
1808     if (!TEST_ptr((n = BN_new())))
1809         goto err;
1810     if (!TEST_int_eq(BN_bn2binpad(n, NULL, 0), 0))
1811         goto err;
1812     memset(out, -1, sizeof(out));
1813     if (!TEST_int_eq(BN_bn2binpad(n, out, sizeof(out)), sizeof(out)))
1814         goto err;
1815     memset(zeros, 0, sizeof(zeros));
1816     if (!TEST_mem_eq(zeros, sizeof(zeros), out, sizeof(out)))
1817         goto err;
1818
1819     /* Test a random numbers at various byte lengths. */
1820     for (bytes = 128 - 7; bytes <= 128; bytes++) {
1821 # define TOP_BIT_ON 0
1822 # define BOTTOM_BIT_NOTOUCH 0
1823         if (!TEST_true(BN_rand(n, bytes * 8, TOP_BIT_ON, BOTTOM_BIT_NOTOUCH)))
1824             goto err;
1825         if (!TEST_int_eq(BN_num_bytes(n), bytes)
1826                 || !TEST_int_eq(BN_bn2bin(n, reference), bytes))
1827             goto err;
1828         /* Empty buffer should fail. */
1829         if (!TEST_int_eq(BN_bn2binpad(n, NULL, 0), -1))
1830             goto err;
1831         /* One byte short should fail. */
1832         if (!TEST_int_eq(BN_bn2binpad(n, out, bytes - 1), -1))
1833             goto err;
1834         /* Exactly right size should encode. */
1835         if (!TEST_int_eq(BN_bn2binpad(n, out, bytes), bytes)
1836                 || !TEST_mem_eq(out, bytes, reference, bytes))
1837             goto err;
1838         /* Pad up one byte extra. */
1839         if (!TEST_int_eq(BN_bn2binpad(n, out, bytes + 1), bytes + 1)
1840                 || !TEST_mem_eq(out + 1, bytes, reference, bytes)
1841                 || !TEST_mem_eq(out, 1, zeros, 1))
1842             goto err;
1843         /* Pad up to 256. */
1844         if (!TEST_int_eq(BN_bn2binpad(n, out, sizeof(out)), sizeof(out))
1845                 || !TEST_mem_eq(out + sizeof(out) - bytes, bytes,
1846                                 reference, bytes)
1847                 || !TEST_mem_eq(out, sizeof(out) - bytes,
1848                                 zeros, sizeof(out) - bytes))
1849             goto err;
1850     }
1851
1852     st = 1;
1853  err:
1854     BN_free(n);
1855     return st;
1856 }
1857
1858 static const MPITEST kSignedTests_BE[] = {
1859     {"-1", "\xff", 1},
1860     {"0", "", 0},
1861     {"1", "\x01", 1},
1862     /*
1863      * The above cover the basics, now let's go for possible bignum
1864      * chunk edges and other word edges (for a broad definition of
1865      * "word", i.e. 1 byte included).
1866      */
1867     /* 1 byte edge */
1868     {"127", "\x7f", 1},
1869     {"-127", "\x81", 1},
1870     {"128", "\x00\x80", 2},
1871     {"-128", "\x80", 1},
1872     {"129", "\x00\x81", 2},
1873     {"-129", "\xff\x7f", 2},
1874     {"255", "\x00\xff", 2},
1875     {"-255", "\xff\x01", 2},
1876     {"256", "\x01\x00", 2},
1877     {"-256", "\xff\x00", 2},
1878     /* 2 byte edge */
1879     {"32767", "\x7f\xff", 2},
1880     {"-32767", "\x80\x01", 2},
1881     {"32768", "\x00\x80\x00", 3},
1882     {"-32768", "\x80\x00", 2},
1883     {"32769", "\x00\x80\x01", 3},
1884     {"-32769", "\xff\x7f\xff", 3},
1885     {"65535", "\x00\xff\xff", 3},
1886     {"-65535", "\xff\x00\x01", 3},
1887     {"65536", "\x01\x00\x00", 3},
1888     {"-65536", "\xff\x00\x00", 3},
1889     /* 4 byte edge */
1890     {"2147483647", "\x7f\xff\xff\xff", 4},
1891     {"-2147483647", "\x80\x00\x00\x01", 4},
1892     {"2147483648", "\x00\x80\x00\x00\x00", 5},
1893     {"-2147483648", "\x80\x00\x00\x00", 4},
1894     {"2147483649", "\x00\x80\x00\x00\x01", 5},
1895     {"-2147483649", "\xff\x7f\xff\xff\xff", 5},
1896     {"4294967295", "\x00\xff\xff\xff\xff", 5},
1897     {"-4294967295", "\xff\x00\x00\x00\x01", 5},
1898     {"4294967296", "\x01\x00\x00\x00\x00", 5},
1899     {"-4294967296", "\xff\x00\x00\x00\x00", 5},
1900     /* 8 byte edge */
1901     {"9223372036854775807", "\x7f\xff\xff\xff\xff\xff\xff\xff", 8},
1902     {"-9223372036854775807", "\x80\x00\x00\x00\x00\x00\x00\x01", 8},
1903     {"9223372036854775808", "\x00\x80\x00\x00\x00\x00\x00\x00\x00", 9},
1904     {"-9223372036854775808", "\x80\x00\x00\x00\x00\x00\x00\x00", 8},
1905     {"9223372036854775809", "\x00\x80\x00\x00\x00\x00\x00\x00\x01", 9},
1906     {"-9223372036854775809", "\xff\x7f\xff\xff\xff\xff\xff\xff\xff", 9},
1907     {"18446744073709551615", "\x00\xff\xff\xff\xff\xff\xff\xff\xff", 9},
1908     {"-18446744073709551615", "\xff\x00\x00\x00\x00\x00\x00\x00\x01", 9},
1909     {"18446744073709551616", "\x01\x00\x00\x00\x00\x00\x00\x00\x00", 9},
1910     {"-18446744073709551616", "\xff\x00\x00\x00\x00\x00\x00\x00\x00", 9},
1911 };
1912
1913 static int copy_reversed(uint8_t *dst, uint8_t *src, size_t len)
1914 {
1915     for (dst += len - 1; len > 0; src++, dst--, len--)
1916         *dst = *src;
1917     return 1;
1918 }
1919
1920 static int test_bn2signed(int i)
1921 {
1922     uint8_t scratch[10], reversed[10];
1923     const MPITEST *test = &kSignedTests_BE[i];
1924     BIGNUM *bn = NULL, *bn2 = NULL;
1925     int st = 0;
1926
1927     if (!TEST_ptr(bn = BN_new())
1928         || !TEST_true(BN_asc2bn(&bn, test->base10)))
1929         goto err;
1930
1931     /*
1932      * Check BN_signed_bn2bin() / BN_signed_bin2bn()
1933      * The interesting stuff happens in the last bytes of the buffers,
1934      * the beginning is just padding (i.e. sign extension).
1935      */
1936     i = sizeof(scratch) - test->mpi_len;
1937     if (!TEST_int_eq(BN_signed_bn2bin(bn, scratch, sizeof(scratch)),
1938                      sizeof(scratch))
1939         || !TEST_true(copy_reversed(reversed, scratch, sizeof(scratch)))
1940         || !TEST_mem_eq(test->mpi, test->mpi_len, scratch + i, test->mpi_len))
1941         goto err;
1942
1943     if (!TEST_ptr(bn2 = BN_signed_bin2bn(scratch, sizeof(scratch), NULL))
1944         || !TEST_BN_eq(bn, bn2))
1945         goto err;
1946
1947     BN_free(bn2);
1948     bn2 = NULL;
1949
1950     /* Check that a parse of the reversed buffer works too */
1951     if (!TEST_ptr(bn2 = BN_signed_lebin2bn(reversed, sizeof(reversed), NULL))
1952         || !TEST_BN_eq(bn, bn2))
1953         goto err;
1954
1955     BN_free(bn2);
1956     bn2 = NULL;
1957
1958     /*
1959      * Check BN_signed_bn2lebin() / BN_signed_lebin2bn()
1960      * The interesting stuff happens in the first bytes of the buffers,
1961      * the end is just padding (i.e. sign extension).
1962      */
1963     i = sizeof(reversed) - test->mpi_len;
1964     if (!TEST_int_eq(BN_signed_bn2lebin(bn, scratch, sizeof(scratch)),
1965                      sizeof(scratch))
1966         || !TEST_true(copy_reversed(reversed, scratch, sizeof(scratch)))
1967         || !TEST_mem_eq(test->mpi, test->mpi_len, reversed + i, test->mpi_len))
1968         goto err;
1969
1970     if (!TEST_ptr(bn2 = BN_signed_lebin2bn(scratch, sizeof(scratch), NULL))
1971         || !TEST_BN_eq(bn, bn2))
1972         goto err;
1973
1974     BN_free(bn2);
1975     bn2 = NULL;
1976
1977     /* Check that a parse of the reversed buffer works too */
1978     if (!TEST_ptr(bn2 = BN_signed_bin2bn(reversed, sizeof(reversed), NULL))
1979         || !TEST_BN_eq(bn, bn2))
1980         goto err;
1981
1982     st = 1;
1983  err:
1984     BN_free(bn2);
1985     BN_free(bn);
1986     return st;
1987 }
1988
1989 static int test_dec2bn(void)
1990 {
1991     BIGNUM *bn = NULL;
1992     int st = 0;
1993
1994     if (!TEST_int_eq(parsedecBN(&bn, "0"), 1)
1995             || !TEST_BN_eq_word(bn, 0)
1996             || !TEST_BN_eq_zero(bn)
1997             || !TEST_BN_le_zero(bn)
1998             || !TEST_BN_ge_zero(bn)
1999             || !TEST_BN_even(bn))
2000         goto err;
2001     BN_free(bn);
2002     bn = NULL;
2003
2004     if (!TEST_int_eq(parsedecBN(&bn, "256"), 3)
2005             || !TEST_BN_eq_word(bn, 256)
2006             || !TEST_BN_ge_zero(bn)
2007             || !TEST_BN_gt_zero(bn)
2008             || !TEST_BN_ne_zero(bn)
2009             || !TEST_BN_even(bn))
2010         goto err;
2011     BN_free(bn);
2012     bn = NULL;
2013
2014     if (!TEST_int_eq(parsedecBN(&bn, "-42"), 3)
2015             || !TEST_BN_abs_eq_word(bn, 42)
2016             || !TEST_BN_lt_zero(bn)
2017             || !TEST_BN_le_zero(bn)
2018             || !TEST_BN_ne_zero(bn)
2019             || !TEST_BN_even(bn))
2020         goto err;
2021     BN_free(bn);
2022     bn = NULL;
2023
2024     if (!TEST_int_eq(parsedecBN(&bn, "1"), 1)
2025             || !TEST_BN_eq_word(bn, 1)
2026             || !TEST_BN_ne_zero(bn)
2027             || !TEST_BN_gt_zero(bn)
2028             || !TEST_BN_ge_zero(bn)
2029             || !TEST_BN_eq_one(bn)
2030             || !TEST_BN_odd(bn))
2031         goto err;
2032     BN_free(bn);
2033     bn = NULL;
2034
2035     if (!TEST_int_eq(parsedecBN(&bn, "-0"), 2)
2036             || !TEST_BN_eq_zero(bn)
2037             || !TEST_BN_ge_zero(bn)
2038             || !TEST_BN_le_zero(bn)
2039             || !TEST_BN_even(bn))
2040         goto err;
2041     BN_free(bn);
2042     bn = NULL;
2043
2044     if (!TEST_int_eq(parsedecBN(&bn, "42trailing garbage is ignored"), 2)
2045             || !TEST_BN_abs_eq_word(bn, 42)
2046             || !TEST_BN_ge_zero(bn)
2047             || !TEST_BN_gt_zero(bn)
2048             || !TEST_BN_ne_zero(bn)
2049             || !TEST_BN_even(bn))
2050         goto err;
2051
2052     st = 1;
2053  err:
2054     BN_free(bn);
2055     return st;
2056 }
2057
2058 static int test_hex2bn(void)
2059 {
2060     BIGNUM *bn = NULL;
2061     int st = 0;
2062
2063     if (!TEST_int_eq(parseBN(&bn, "0"), 1)
2064             || !TEST_BN_eq_zero(bn)
2065             || !TEST_BN_ge_zero(bn)
2066             || !TEST_BN_even(bn))
2067         goto err;
2068     BN_free(bn);
2069     bn = NULL;
2070
2071     if (!TEST_int_eq(parseBN(&bn, "256"), 3)
2072             || !TEST_BN_eq_word(bn, 0x256)
2073             || !TEST_BN_ge_zero(bn)
2074             || !TEST_BN_gt_zero(bn)
2075             || !TEST_BN_ne_zero(bn)
2076             || !TEST_BN_even(bn))
2077         goto err;
2078     BN_free(bn);
2079     bn = NULL;
2080
2081     if (!TEST_int_eq(parseBN(&bn, "-42"), 3)
2082             || !TEST_BN_abs_eq_word(bn, 0x42)
2083             || !TEST_BN_lt_zero(bn)
2084             || !TEST_BN_le_zero(bn)
2085             || !TEST_BN_ne_zero(bn)
2086             || !TEST_BN_even(bn))
2087         goto err;
2088     BN_free(bn);
2089     bn = NULL;
2090
2091     if (!TEST_int_eq(parseBN(&bn, "cb"), 2)
2092             || !TEST_BN_eq_word(bn, 0xCB)
2093             || !TEST_BN_ge_zero(bn)
2094             || !TEST_BN_gt_zero(bn)
2095             || !TEST_BN_ne_zero(bn)
2096             || !TEST_BN_odd(bn))
2097         goto err;
2098     BN_free(bn);
2099     bn = NULL;
2100
2101     if (!TEST_int_eq(parseBN(&bn, "-0"), 2)
2102             || !TEST_BN_eq_zero(bn)
2103             || !TEST_BN_ge_zero(bn)
2104             || !TEST_BN_le_zero(bn)
2105             || !TEST_BN_even(bn))
2106         goto err;
2107     BN_free(bn);
2108     bn = NULL;
2109
2110     if (!TEST_int_eq(parseBN(&bn, "abctrailing garbage is ignored"), 3)
2111             || !TEST_BN_eq_word(bn, 0xabc)
2112             || !TEST_BN_ge_zero(bn)
2113             || !TEST_BN_gt_zero(bn)
2114             || !TEST_BN_ne_zero(bn)
2115             || !TEST_BN_even(bn))
2116         goto err;
2117     st = 1;
2118
2119  err:
2120     BN_free(bn);
2121     return st;
2122 }
2123
2124 static int test_asc2bn(void)
2125 {
2126     BIGNUM *bn = NULL;
2127     int st = 0;
2128
2129     if (!TEST_ptr(bn = BN_new()))
2130         goto err;
2131
2132     if (!TEST_true(BN_asc2bn(&bn, "0"))
2133             || !TEST_BN_eq_zero(bn)
2134             || !TEST_BN_ge_zero(bn))
2135         goto err;
2136
2137     if (!TEST_true(BN_asc2bn(&bn, "256"))
2138             || !TEST_BN_eq_word(bn, 256)
2139             || !TEST_BN_ge_zero(bn))
2140         goto err;
2141
2142     if (!TEST_true(BN_asc2bn(&bn, "-42"))
2143             || !TEST_BN_abs_eq_word(bn, 42)
2144             || !TEST_BN_lt_zero(bn))
2145         goto err;
2146
2147     if (!TEST_true(BN_asc2bn(&bn, "0x1234"))
2148             || !TEST_BN_eq_word(bn, 0x1234)
2149             || !TEST_BN_ge_zero(bn))
2150         goto err;
2151
2152     if (!TEST_true(BN_asc2bn(&bn, "0X1234"))
2153             || !TEST_BN_eq_word(bn, 0x1234)
2154             || !TEST_BN_ge_zero(bn))
2155         goto err;
2156
2157     if (!TEST_true(BN_asc2bn(&bn, "-0xabcd"))
2158             || !TEST_BN_abs_eq_word(bn, 0xabcd)
2159             || !TEST_BN_lt_zero(bn))
2160         goto err;
2161
2162     if (!TEST_true(BN_asc2bn(&bn, "-0"))
2163             || !TEST_BN_eq_zero(bn)
2164             || !TEST_BN_ge_zero(bn))
2165         goto err;
2166
2167     if (!TEST_true(BN_asc2bn(&bn, "123trailing garbage is ignored"))
2168             || !TEST_BN_eq_word(bn, 123)
2169             || !TEST_BN_ge_zero(bn))
2170         goto err;
2171
2172     st = 1;
2173  err:
2174     BN_free(bn);
2175     return st;
2176 }
2177
2178 static const MPITEST kMPITests[] = {
2179     {"0", "\x00\x00\x00\x00", 4},
2180     {"1", "\x00\x00\x00\x01\x01", 5},
2181     {"-1", "\x00\x00\x00\x01\x81", 5},
2182     {"128", "\x00\x00\x00\x02\x00\x80", 6},
2183     {"256", "\x00\x00\x00\x02\x01\x00", 6},
2184     {"-256", "\x00\x00\x00\x02\x81\x00", 6},
2185 };
2186
2187 static int test_mpi(int i)
2188 {
2189     uint8_t scratch[8];
2190     const MPITEST *test = &kMPITests[i];
2191     size_t mpi_len, mpi_len2;
2192     BIGNUM *bn = NULL;
2193     BIGNUM *bn2 = NULL;
2194     int st = 0;
2195
2196     if (!TEST_ptr(bn = BN_new())
2197             || !TEST_true(BN_asc2bn(&bn, test->base10)))
2198         goto err;
2199     mpi_len = BN_bn2mpi(bn, NULL);
2200     if (!TEST_size_t_le(mpi_len, sizeof(scratch)))
2201         goto err;
2202
2203     if (!TEST_size_t_eq(mpi_len2 = BN_bn2mpi(bn, scratch), mpi_len)
2204             || !TEST_mem_eq(test->mpi, test->mpi_len, scratch, mpi_len))
2205         goto err;
2206
2207     if (!TEST_ptr(bn2 = BN_mpi2bn(scratch, mpi_len, NULL)))
2208         goto err;
2209
2210     if (!TEST_BN_eq(bn, bn2)) {
2211         BN_free(bn2);
2212         goto err;
2213     }
2214     BN_free(bn2);
2215
2216     st = 1;
2217  err:
2218     BN_free(bn);
2219     return st;
2220 }
2221
2222 static int test_bin2zero(void)
2223 {
2224     unsigned char input[] = { 0 };
2225     BIGNUM *zbn = NULL;
2226     int ret = 0;
2227
2228     if (!TEST_ptr(zbn = BN_new()))
2229         goto err;
2230
2231 #define zerotest(fn)                           \
2232     if (!TEST_ptr(fn(input, 1, zbn))    \
2233         || !TEST_true(BN_is_zero(zbn))   \
2234         || !TEST_ptr(fn(input, 0, zbn)) \
2235         || !TEST_true(BN_is_zero(zbn))   \
2236         || !TEST_ptr(fn(NULL, 0, zbn))  \
2237         || !TEST_true(BN_is_zero(zbn)))  \
2238         goto err
2239
2240     zerotest(BN_bin2bn);
2241     zerotest(BN_signed_bin2bn);
2242     zerotest(BN_lebin2bn);
2243     zerotest(BN_signed_lebin2bn);
2244 #undef zerotest
2245
2246     ret = 1;
2247  err:
2248     BN_free(zbn);
2249     return ret;
2250 }
2251
2252 static int test_bin2bn_lengths(void)
2253 {
2254     unsigned char input[] = { 1, 2 };
2255     BIGNUM *bn_be = NULL, *bn_expected_be = NULL;
2256     BIGNUM *bn_le = NULL, *bn_expected_le = NULL;
2257     int ret = 0;
2258
2259     if (!TEST_ptr(bn_be = BN_new())
2260         || !TEST_ptr(bn_expected_be = BN_new())
2261         || !TEST_true(BN_set_word(bn_expected_be, 0x102))
2262         || !TEST_ptr(bn_le = BN_new())
2263         || !TEST_ptr(bn_expected_le = BN_new())
2264         || !TEST_true(BN_set_word(bn_expected_le, 0x201)))
2265         goto err;
2266
2267 #define lengthtest(fn, e)                                       \
2268     if (!TEST_ptr_null(fn(input, -1, bn_##e))                   \
2269         || !TEST_ptr(fn(input, 0, bn_##e))                      \
2270         || !TEST_true(BN_is_zero(bn_##e))                       \
2271         || !TEST_ptr(fn(input, 2, bn_##e))                      \
2272         || !TEST_int_eq(BN_cmp(bn_##e, bn_expected_##e), 0))    \
2273         goto err
2274
2275     lengthtest(BN_bin2bn, be);
2276     lengthtest(BN_signed_bin2bn, be);
2277     lengthtest(BN_lebin2bn, le);
2278     lengthtest(BN_signed_lebin2bn, le);
2279 #undef lengthtest
2280
2281     ret = 1;
2282  err:
2283     BN_free(bn_be);
2284     BN_free(bn_expected_be);
2285     BN_free(bn_le);
2286     BN_free(bn_expected_le);
2287     return ret;
2288 }
2289
2290 static int test_rand(void)
2291 {
2292     BIGNUM *bn = NULL;
2293     int st = 0;
2294
2295     if (!TEST_ptr(bn = BN_new()))
2296         return 0;
2297
2298     /* Test BN_rand for degenerate cases with |top| and |bottom| parameters. */
2299     if (!TEST_false(BN_rand(bn, 0, 0 /* top */ , 0 /* bottom */ ))
2300             || !TEST_false(BN_rand(bn, 0, 1 /* top */ , 1 /* bottom */ ))
2301             || !TEST_true(BN_rand(bn, 1, 0 /* top */ , 0 /* bottom */ ))
2302             || !TEST_BN_eq_one(bn)
2303             || !TEST_false(BN_rand(bn, 1, 1 /* top */ , 0 /* bottom */ ))
2304             || !TEST_true(BN_rand(bn, 1, -1 /* top */ , 1 /* bottom */ ))
2305             || !TEST_BN_eq_one(bn)
2306             || !TEST_true(BN_rand(bn, 2, 1 /* top */ , 0 /* bottom */ ))
2307             || !TEST_BN_eq_word(bn, 3))
2308         goto err;
2309
2310     st = 1;
2311  err:
2312     BN_free(bn);
2313     return st;
2314 }
2315
2316 /*
2317  * Run some statistical tests to provide a degree confidence that the
2318  * BN_rand_range() function works as expected.  The test cases and
2319  * critical values are generated by the bn_rand_range script.
2320  *
2321  * Each individual test is a Chi^2 goodness of fit for a specified number
2322  * of samples and range.  The samples are assumed to be independent and
2323  * that they are from a discrete uniform distribution.
2324  *
2325  * Some of these individual tests are expected to fail, the success/failure
2326  * of each is an independent Bernoulli trial.  The number of such successes
2327  * will form a binomial distribution.  The count of the successes is compared
2328  * against a precomputed critical value to determine the overall outcome.
2329  */
2330 struct rand_range_case {
2331     unsigned int range;
2332     unsigned int iterations;
2333     double critical;
2334 };
2335
2336 #include "bn_rand_range.h"
2337
2338 static int test_rand_range_single(size_t n)
2339 {
2340     const unsigned int range = rand_range_cases[n].range;
2341     const unsigned int iterations = rand_range_cases[n].iterations;
2342     const double critical = rand_range_cases[n].critical;
2343     const double expected = iterations / (double)range;
2344     double sum = 0;
2345     BIGNUM *rng = NULL, *val = NULL;
2346     size_t *counts;
2347     unsigned int i, v;
2348     int res = 0;
2349
2350     if (!TEST_ptr(counts = OPENSSL_zalloc(sizeof(*counts) * range))
2351         || !TEST_ptr(rng = BN_new())
2352         || !TEST_ptr(val = BN_new())
2353         || !TEST_true(BN_set_word(rng, range)))
2354         goto err;
2355     for (i = 0; i < iterations; i++) {
2356         if (!TEST_true(BN_rand_range(val, rng))
2357             || !TEST_uint_lt(v = (unsigned int)BN_get_word(val), range))
2358             goto err;
2359         counts[v]++;
2360     }
2361
2362     for (i = 0; i < range; i++) {
2363         const double delta = counts[i] - expected;
2364         sum += delta * delta;
2365     }
2366     sum /= expected;
2367
2368     if (sum > critical) {
2369         TEST_info("Chi^2 test negative %.4f > %4.f", sum, critical);
2370         TEST_note("test case %zu  range %u  iterations %u", n + 1, range,
2371                   iterations);
2372         goto err;
2373     }
2374
2375     res = 1;
2376 err:
2377     BN_free(rng);
2378     BN_free(val);
2379     OPENSSL_free(counts);
2380     return res;
2381 }
2382
2383 static int test_rand_range(void)
2384 {
2385     int n_success = 0;
2386     size_t i;
2387
2388     for (i = 0; i < OSSL_NELEM(rand_range_cases); i++)
2389         n_success += test_rand_range_single(i);
2390     if (TEST_int_ge(n_success, binomial_critical))
2391         return 1;
2392     TEST_note("This test is expected to fail by chance 0.01%% of the time.");
2393     return 0;
2394 }
2395
2396 static int test_negzero(void)
2397 {
2398     BIGNUM *a = NULL, *b = NULL, *c = NULL, *d = NULL;
2399     BIGNUM *numerator = NULL, *denominator = NULL;
2400     int consttime, st = 0;
2401
2402     if (!TEST_ptr(a = BN_new())
2403             || !TEST_ptr(b = BN_new())
2404             || !TEST_ptr(c = BN_new())
2405             || !TEST_ptr(d = BN_new()))
2406         goto err;
2407
2408     /* Test that BN_mul never gives negative zero. */
2409     if (!TEST_true(BN_set_word(a, 1)))
2410         goto err;
2411     BN_set_negative(a, 1);
2412     BN_zero(b);
2413     if (!TEST_true(BN_mul(c, a, b, ctx)))
2414         goto err;
2415     if (!TEST_BN_eq_zero(c)
2416             || !TEST_BN_ge_zero(c))
2417         goto err;
2418
2419     for (consttime = 0; consttime < 2; consttime++) {
2420         if (!TEST_ptr(numerator = BN_new())
2421                 || !TEST_ptr(denominator = BN_new()))
2422             goto err;
2423         if (consttime) {
2424             BN_set_flags(numerator, BN_FLG_CONSTTIME);
2425             BN_set_flags(denominator, BN_FLG_CONSTTIME);
2426         }
2427         /* Test that BN_div never gives negative zero in the quotient. */
2428         if (!TEST_true(BN_set_word(numerator, 1))
2429                 || !TEST_true(BN_set_word(denominator, 2)))
2430             goto err;
2431         BN_set_negative(numerator, 1);
2432         if (!TEST_true(BN_div(a, b, numerator, denominator, ctx))
2433                 || !TEST_BN_eq_zero(a)
2434                 || !TEST_BN_ge_zero(a))
2435             goto err;
2436
2437         /* Test that BN_div never gives negative zero in the remainder. */
2438         if (!TEST_true(BN_set_word(denominator, 1))
2439                 || !TEST_true(BN_div(a, b, numerator, denominator, ctx))
2440                 || !TEST_BN_eq_zero(b)
2441                 || !TEST_BN_ge_zero(b))
2442             goto err;
2443         BN_free(numerator);
2444         BN_free(denominator);
2445         numerator = denominator = NULL;
2446     }
2447
2448     /* Test that BN_set_negative will not produce a negative zero. */
2449     BN_zero(a);
2450     BN_set_negative(a, 1);
2451     if (BN_is_negative(a))
2452         goto err;
2453     st = 1;
2454
2455  err:
2456     BN_free(a);
2457     BN_free(b);
2458     BN_free(c);
2459     BN_free(d);
2460     BN_free(numerator);
2461     BN_free(denominator);
2462     return st;
2463 }
2464
2465 static int test_badmod(void)
2466 {
2467     BIGNUM *a = NULL, *b = NULL, *zero = NULL;
2468     BN_MONT_CTX *mont = NULL;
2469     int st = 0;
2470
2471     if (!TEST_ptr(a = BN_new())
2472             || !TEST_ptr(b = BN_new())
2473             || !TEST_ptr(zero = BN_new())
2474             || !TEST_ptr(mont = BN_MONT_CTX_new()))
2475         goto err;
2476     BN_zero(zero);
2477
2478     if (!TEST_false(BN_div(a, b, BN_value_one(), zero, ctx)))
2479         goto err;
2480     ERR_clear_error();
2481
2482     if (!TEST_false(BN_mod_mul(a, BN_value_one(), BN_value_one(), zero, ctx)))
2483         goto err;
2484     ERR_clear_error();
2485
2486     if (!TEST_false(BN_mod_exp(a, BN_value_one(), BN_value_one(), zero, ctx)))
2487         goto err;
2488     ERR_clear_error();
2489
2490     if (!TEST_false(BN_mod_exp_mont(a, BN_value_one(), BN_value_one(),
2491                                     zero, ctx, NULL)))
2492         goto err;
2493     ERR_clear_error();
2494
2495     if (!TEST_false(BN_mod_exp_mont_consttime(a, BN_value_one(), BN_value_one(),
2496                                               zero, ctx, NULL)))
2497         goto err;
2498     ERR_clear_error();
2499
2500     if (!TEST_false(BN_MONT_CTX_set(mont, zero, ctx)))
2501         goto err;
2502     ERR_clear_error();
2503
2504     /* Some operations also may not be used with an even modulus. */
2505     if (!TEST_true(BN_set_word(b, 16)))
2506         goto err;
2507
2508     if (!TEST_false(BN_MONT_CTX_set(mont, b, ctx)))
2509         goto err;
2510     ERR_clear_error();
2511
2512     if (!TEST_false(BN_mod_exp_mont(a, BN_value_one(), BN_value_one(),
2513                                     b, ctx, NULL)))
2514         goto err;
2515     ERR_clear_error();
2516
2517     if (!TEST_false(BN_mod_exp_mont_consttime(a, BN_value_one(), BN_value_one(),
2518                                               b, ctx, NULL)))
2519         goto err;
2520     ERR_clear_error();
2521
2522     st = 1;
2523  err:
2524     BN_free(a);
2525     BN_free(b);
2526     BN_free(zero);
2527     BN_MONT_CTX_free(mont);
2528     return st;
2529 }
2530
2531 static int test_expmodzero(void)
2532 {
2533     BIGNUM *a = NULL, *r = NULL, *zero = NULL;
2534     int st = 0;
2535
2536     if (!TEST_ptr(zero = BN_new())
2537             || !TEST_ptr(a = BN_new())
2538             || !TEST_ptr(r = BN_new()))
2539         goto err;
2540     BN_zero(zero);
2541
2542     if (!TEST_true(BN_mod_exp(r, a, zero, BN_value_one(), NULL))
2543             || !TEST_BN_eq_zero(r)
2544             || !TEST_true(BN_mod_exp_mont(r, a, zero, BN_value_one(),
2545                                           NULL, NULL))
2546             || !TEST_BN_eq_zero(r)
2547             || !TEST_true(BN_mod_exp_mont_consttime(r, a, zero,
2548                                                     BN_value_one(),
2549                                                     NULL, NULL))
2550             || !TEST_BN_eq_zero(r)
2551             || !TEST_true(BN_mod_exp_mont_word(r, 42, zero,
2552                                                BN_value_one(), NULL, NULL))
2553             || !TEST_BN_eq_zero(r))
2554         goto err;
2555
2556     st = 1;
2557  err:
2558     BN_free(zero);
2559     BN_free(a);
2560     BN_free(r);
2561     return st;
2562 }
2563
2564 static int test_expmodone(void)
2565 {
2566     int ret = 0, i;
2567     BIGNUM *r = BN_new();
2568     BIGNUM *a = BN_new();
2569     BIGNUM *p = BN_new();
2570     BIGNUM *m = BN_new();
2571
2572     if (!TEST_ptr(r)
2573             || !TEST_ptr(a)
2574             || !TEST_ptr(p)
2575             || !TEST_ptr(p)
2576             || !TEST_ptr(m)
2577             || !TEST_true(BN_set_word(a, 1))
2578             || !TEST_true(BN_set_word(p, 0))
2579             || !TEST_true(BN_set_word(m, 1)))
2580         goto err;
2581
2582     /* Calculate r = 1 ^ 0 mod 1, and check the result is always 0 */
2583     for (i = 0; i < 2; i++) {
2584         if (!TEST_true(BN_mod_exp(r, a, p, m, NULL))
2585                 || !TEST_BN_eq_zero(r)
2586                 || !TEST_true(BN_mod_exp_mont(r, a, p, m, NULL, NULL))
2587                 || !TEST_BN_eq_zero(r)
2588                 || !TEST_true(BN_mod_exp_mont_consttime(r, a, p, m, NULL, NULL))
2589                 || !TEST_BN_eq_zero(r)
2590                 || !TEST_true(BN_mod_exp_mont_word(r, 1, p, m, NULL, NULL))
2591                 || !TEST_BN_eq_zero(r)
2592                 || !TEST_true(BN_mod_exp_simple(r, a, p, m, NULL))
2593                 || !TEST_BN_eq_zero(r)
2594                 || !TEST_true(BN_mod_exp_recp(r, a, p, m, NULL))
2595                 || !TEST_BN_eq_zero(r))
2596             goto err;
2597         /* Repeat for r = 1 ^ 0 mod -1 */
2598         if (i == 0)
2599             BN_set_negative(m, 1);
2600     }
2601
2602     ret = 1;
2603  err:
2604     BN_free(r);
2605     BN_free(a);
2606     BN_free(p);
2607     BN_free(m);
2608     return ret;
2609 }
2610
2611 static int test_smallprime(int kBits)
2612 {
2613     BIGNUM *r;
2614     int st = 0;
2615
2616     if (!TEST_ptr(r = BN_new()))
2617         goto err;
2618
2619     if (kBits <= 1) {
2620         if (!TEST_false(BN_generate_prime_ex(r, kBits, 0,
2621                                              NULL, NULL, NULL)))
2622             goto err;
2623     } else {
2624         if (!TEST_true(BN_generate_prime_ex(r, kBits, 0,
2625                                             NULL, NULL, NULL))
2626                 || !TEST_int_eq(BN_num_bits(r), kBits))
2627             goto err;
2628     }
2629
2630     st = 1;
2631  err:
2632     BN_free(r);
2633     return st;
2634 }
2635
2636 static int test_smallsafeprime(int kBits)
2637 {
2638     BIGNUM *r;
2639     int st = 0;
2640
2641     if (!TEST_ptr(r = BN_new()))
2642         goto err;
2643
2644     if (kBits <= 5 && kBits != 3) {
2645         if (!TEST_false(BN_generate_prime_ex(r, kBits, 1,
2646                                              NULL, NULL, NULL)))
2647             goto err;
2648     } else {
2649         if (!TEST_true(BN_generate_prime_ex(r, kBits, 1,
2650                                             NULL, NULL, NULL))
2651                 || !TEST_int_eq(BN_num_bits(r), kBits))
2652             goto err;
2653     }
2654
2655     st = 1;
2656  err:
2657     BN_free(r);
2658     return st;
2659 }
2660
2661 static int primes[] = { 2, 3, 5, 7, 17863 };
2662
2663 static int test_is_prime(int i)
2664 {
2665     int ret = 0;
2666     BIGNUM *r = NULL;
2667     int trial;
2668
2669     if (!TEST_ptr(r = BN_new()))
2670         goto err;
2671
2672     for (trial = 0; trial <= 1; ++trial) {
2673         if (!TEST_true(BN_set_word(r, primes[i]))
2674                 || !TEST_int_eq(BN_check_prime(r, ctx, NULL),
2675                                 1))
2676             goto err;
2677     }
2678
2679     ret = 1;
2680  err:
2681     BN_free(r);
2682     return ret;
2683 }
2684
2685 static int not_primes[] = { -1, 0, 1, 4 };
2686
2687 static int test_not_prime(int i)
2688 {
2689     int ret = 0;
2690     BIGNUM *r = NULL;
2691     int trial;
2692
2693     if (!TEST_ptr(r = BN_new()))
2694         goto err;
2695
2696     for (trial = 0; trial <= 1; ++trial) {
2697         if (!TEST_true(BN_set_word(r, not_primes[i]))
2698                 || !TEST_false(BN_check_prime(r, ctx, NULL)))
2699             goto err;
2700     }
2701
2702     ret = 1;
2703  err:
2704     BN_free(r);
2705     return ret;
2706 }
2707
2708 static int test_ctx_set_ct_flag(BN_CTX *c)
2709 {
2710     int st = 0;
2711     size_t i;
2712     BIGNUM *b[15];
2713
2714     BN_CTX_start(c);
2715     for (i = 0; i < OSSL_NELEM(b); i++) {
2716         if (!TEST_ptr(b[i] = BN_CTX_get(c)))
2717             goto err;
2718         if (i % 2 == 1)
2719             BN_set_flags(b[i], BN_FLG_CONSTTIME);
2720     }
2721
2722     st = 1;
2723  err:
2724     BN_CTX_end(c);
2725     return st;
2726 }
2727
2728 static int test_ctx_check_ct_flag(BN_CTX *c)
2729 {
2730     int st = 0;
2731     size_t i;
2732     BIGNUM *b[30];
2733
2734     BN_CTX_start(c);
2735     for (i = 0; i < OSSL_NELEM(b); i++) {
2736         if (!TEST_ptr(b[i] = BN_CTX_get(c)))
2737             goto err;
2738         if (!TEST_false(BN_get_flags(b[i], BN_FLG_CONSTTIME)))
2739             goto err;
2740     }
2741
2742     st = 1;
2743  err:
2744     BN_CTX_end(c);
2745     return st;
2746 }
2747
2748 static int test_ctx_consttime_flag(void)
2749 {
2750     /*-
2751      * The constant-time flag should not "leak" among BN_CTX frames:
2752      *
2753      * - test_ctx_set_ct_flag() starts a frame in the given BN_CTX and
2754      *   sets the BN_FLG_CONSTTIME flag on some of the BIGNUMs obtained
2755      *   from the frame before ending it.
2756      * - test_ctx_check_ct_flag() then starts a new frame and gets a
2757      *   number of BIGNUMs from it. In absence of leaks, none of the
2758      *   BIGNUMs in the new frame should have BN_FLG_CONSTTIME set.
2759      *
2760      * In actual BN_CTX usage inside libcrypto the leak could happen at
2761      * any depth level in the BN_CTX stack, with varying results
2762      * depending on the patterns of sibling trees of nested function
2763      * calls sharing the same BN_CTX object, and the effect of
2764      * unintended BN_FLG_CONSTTIME on the called BN_* functions.
2765      *
2766      * This simple unit test abstracts away this complexity and verifies
2767      * that the leak does not happen between two sibling functions
2768      * sharing the same BN_CTX object at the same level of nesting.
2769      *
2770      */
2771     BN_CTX *nctx = NULL;
2772     BN_CTX *sctx = NULL;
2773     size_t i = 0;
2774     int st = 0;
2775
2776     if (!TEST_ptr(nctx = BN_CTX_new())
2777             || !TEST_ptr(sctx = BN_CTX_secure_new()))
2778         goto err;
2779
2780     for (i = 0; i < 2; i++) {
2781         BN_CTX *c = i == 0 ? nctx : sctx;
2782         if (!TEST_true(test_ctx_set_ct_flag(c))
2783                 || !TEST_true(test_ctx_check_ct_flag(c)))
2784             goto err;
2785     }
2786
2787     st = 1;
2788  err:
2789     BN_CTX_free(nctx);
2790     BN_CTX_free(sctx);
2791     return st;
2792 }
2793
2794 static int test_coprime(void)
2795 {
2796     BIGNUM *a = NULL, *b = NULL;
2797     int ret = 0;
2798
2799     ret = TEST_ptr(a = BN_new())
2800           && TEST_ptr(b = BN_new())
2801           && TEST_true(BN_set_word(a, 66))
2802           && TEST_true(BN_set_word(b, 99))
2803           && TEST_int_eq(BN_are_coprime(a, b, ctx), 0)
2804           && TEST_int_eq(BN_are_coprime(b, a, ctx), 0)
2805           && TEST_true(BN_set_word(a, 67))
2806           && TEST_int_eq(BN_are_coprime(a, b, ctx), 1)
2807           && TEST_int_eq(BN_are_coprime(b, a, ctx), 1);
2808     BN_free(a);
2809     BN_free(b);
2810     return ret;
2811 }
2812
2813 static int test_gcd_prime(void)
2814 {
2815     BIGNUM *a = NULL, *b = NULL, *gcd = NULL;
2816     int i, st = 0;
2817
2818     if (!TEST_ptr(a = BN_new())
2819             || !TEST_ptr(b = BN_new())
2820             || !TEST_ptr(gcd = BN_new()))
2821         goto err;
2822
2823     if (!TEST_true(BN_generate_prime_ex(a, 1024, 0, NULL, NULL, NULL)))
2824             goto err;
2825     for (i = 0; i < NUM_PRIME_TESTS; i++) {
2826         if (!TEST_true(BN_generate_prime_ex(b, 1024, 0,
2827                                             NULL, NULL, NULL))
2828                 || !TEST_true(BN_gcd(gcd, a, b, ctx))
2829                 || !TEST_true(BN_is_one(gcd))
2830                 || !TEST_true(BN_are_coprime(a, b, ctx)))
2831             goto err;
2832     }
2833
2834     st = 1;
2835  err:
2836     BN_free(a);
2837     BN_free(b);
2838     BN_free(gcd);
2839     return st;
2840 }
2841
2842 typedef struct mod_exp_test_st
2843 {
2844   const char *base;
2845   const char *exp;
2846   const char *mod;
2847   const char *res;
2848 } MOD_EXP_TEST;
2849
2850 static const MOD_EXP_TEST ModExpTests[] = {
2851    /* original test vectors for rsaz_512_sqr bug, by OSS-Fuzz */
2852    {
2853        "1166180238001879113042182292626169621106255558914000595999312084"
2854        "4627946820899490684928760491249738643524880720584249698100907201"
2855        "002086675047927600340800371",
2856        "8000000000000000000000000000000000000000000000000000000000000000"
2857        "0000000000000000000000000000000000000000000000000000000000000000"
2858        "00000000",
2859        "1340780792684523720980737645613191762604395855615117867483316354"
2860        "3294276330515137663421134775482798690129946803802212663956180562"
2861        "088664022929883876655300863",
2862        "8243904058268085430037326628480645845409758077568738532059032482"
2863        "8294114415890603594730158120426756266457928475330450251339773498"
2864        "26758407619521544102068438"
2865    },
2866    {
2867        "4974270041410803822078866696159586946995877618987010219312844726"
2868        "0284386121835740784990869050050504348861513337232530490826340663"
2869        "197278031692737429054",
2870        "4974270041410803822078866696159586946995877428188754995041148539"
2871        "1663243362592271353668158565195557417149981094324650322556843202"
2872        "946445882670777892608",
2873        "1340780716511420227215592830971452482815377482627251725537099028"
2874        "4429769497230131760206012644403029349547320953206103351725462999"
2875        "947509743623340557059752191",
2876        "5296244594780707015616522701706118082963369547253192207884519362"
2877        "1767869984947542695665420219028522815539559194793619684334900442"
2878        "49304558011362360473525933"
2879    },
2880    /* test vectors for rsaz_512_srq bug, with rcx/rbx=1 */
2881    {   /* between first and second iteration */
2882        "5148719036160389201525610950887605325980251964889646556085286545"
2883        "3931548809178823413169359635978762036512397113080988070677858033"
2884        "36463909753993540214027190",
2885        "6703903964971298549787012499102923063739682910296196688861780721"
2886        "8608820150367734884009371490834517138450159290932430254268769414"
2887        "05973284973216824503042158",
2888        "6703903964971298549787012499102923063739682910296196688861780721"
2889        "8608820150367734884009371490834517138450159290932430254268769414"
2890        "05973284973216824503042159",
2891        "1"
2892    },
2893    {   /* between second and third iteration */
2894        "8908340854353752577419678771330460827942371434853054158622636544"
2895        "8151360109722890949471912566649465436296659601091730745087014189"
2896        "2672764191218875181826063",
2897        "6703903964971298549787012499102923063739682910296196688861780721"
2898        "8608820150367734884009371490834517138450159290932430254268769414"
2899        "05973284973216824503042158",
2900        "6703903964971298549787012499102923063739682910296196688861780721"
2901        "8608820150367734884009371490834517138450159290932430254268769414"
2902        "05973284973216824503042159",
2903        "1"
2904    },
2905    {   /* between third and fourth iteration */
2906        "3427446396505596330634350984901719674479522569002785244080234738"
2907        "4288743635435746136297299366444548736533053717416735379073185344"
2908        "26985272974404612945608761",
2909        "6703903964971298549787012499102923063739682910296196688861780721"
2910        "8608820150367734884009371490834517138450159290932430254268769414"
2911        "05973284973216824503042158",
2912        "6703903964971298549787012499102923063739682910296196688861780721"
2913        "8608820150367734884009371490834517138450159290932430254268769414"
2914        "05973284973216824503042159",
2915        "1"
2916    },
2917    {   /* between fourth and fifth iteration */
2918        "3472743044917564564078857826111874560045331237315597383869652985"
2919        "6919870028890895988478351133601517365908445058405433832718206902"
2920        "4088133164805266956353542",
2921        "6703903964971298549787012499102923063739682910296196688861780721"
2922        "8608820150367734884009371490834517138450159290932430254268769414"
2923        "05973284973216824503042158",
2924        "6703903964971298549787012499102923063739682910296196688861780721"
2925        "8608820150367734884009371490834517138450159290932430254268769414"
2926        "05973284973216824503042159",
2927        "1"
2928    },
2929    {   /* between fifth and sixth iteration */
2930        "3608632990153469264412378349742339216742409743898601587274768025"
2931        "0110772032985643555192767717344946174122842255204082586753499651"
2932        "14483434992887431333675068",
2933        "6703903964971298549787012499102923063739682910296196688861780721"
2934        "8608820150367734884009371490834517138450159290932430254268769414"
2935        "05973284973216824503042158",
2936        "6703903964971298549787012499102923063739682910296196688861780721"
2937        "8608820150367734884009371490834517138450159290932430254268769414"
2938        "05973284973216824503042159",
2939        "1"
2940    },
2941    {   /* between sixth and seventh iteration */
2942        "8455374370234070242910508226941981520235709767260723212165264877"
2943        "8689064388017521524568434328264431772644802567028663962962025746"
2944        "9283458217850119569539086",
2945        "6703903964971298549787012499102923063739682910296196688861780721"
2946        "8608820150367734884009371490834517138450159290932430254268769414"
2947        "05973284973216824503042158",
2948        "6703903964971298549787012499102923063739682910296196688861780721"
2949        "8608820150367734884009371490834517138450159290932430254268769414"
2950        "05973284973216824503042159",
2951        "1"
2952    },
2953    {   /* between seventh and eighth iteration */
2954        "5155371529688532178421209781159131443543419764974688878527112131"
2955        "7446518205609427412336183157918981038066636807317733319323257603"
2956        "04416292040754017461076359",
2957        "1005585594745694782468051874865438459560952436544429503329267108"
2958        "2791323022555160232601405723625177570767523893639864538140315412"
2959        "108959927459825236754563832",
2960        "1005585594745694782468051874865438459560952436544429503329267108"
2961        "2791323022555160232601405723625177570767523893639864538140315412"
2962        "108959927459825236754563833",
2963        "1"
2964    },
2965    /* test vectors for rsaz_512_srq bug, with rcx/rbx=2 */
2966    {   /* between first and second iteration */
2967        "3155666506033786929967309937640790361084670559125912405342594979"
2968        "4345142818528956285490897841406338022378565972533508820577760065"
2969        "58494345853302083699912572",
2970        "6703903964971298549787012499102923063739682910296196688861780721"
2971        "8608820150367734884009371490834517138450159290932430254268769414"
2972        "05973284973216824503042158",
2973        "6703903964971298549787012499102923063739682910296196688861780721"
2974        "8608820150367734884009371490834517138450159290932430254268769414"
2975        "05973284973216824503042159",
2976        "1"
2977    },
2978    {   /* between second and third iteration */
2979        "3789819583801342198190405714582958759005991915505282362397087750"
2980        "4213544724644823098843135685133927198668818185338794377239590049"
2981        "41019388529192775771488319",
2982        "6703903964971298549787012499102923063739682910296196688861780721"
2983        "8608820150367734884009371490834517138450159290932430254268769414"
2984        "05973284973216824503042158",
2985        "6703903964971298549787012499102923063739682910296196688861780721"
2986        "8608820150367734884009371490834517138450159290932430254268769414"
2987        "05973284973216824503042159",
2988        "1"
2989    },
2990    {   /* between third and forth iteration */
2991        "4695752552040706867080542538786056470322165281761525158189220280"
2992        "4025547447667484759200742764246905647644662050122968912279199065"
2993        "48065034299166336940507214",
2994        "6703903964971298549787012499102923063739682910296196688861780721"
2995        "8608820150367734884009371490834517138450159290932430254268769414"
2996        "05973284973216824503042158",
2997        "6703903964971298549787012499102923063739682910296196688861780721"
2998        "8608820150367734884009371490834517138450159290932430254268769414"
2999        "05973284973216824503042159",
3000        "1"
3001    },
3002    {   /* between forth and fifth iteration */
3003        "2159140240970485794188159431017382878636879856244045329971239574"
3004        "8919691133560661162828034323196457386059819832804593989740268964"
3005        "74502911811812651475927076",
3006        "6703903964971298549787012499102923063739682910296196688861780721"
3007        "8608820150367734884009371490834517138450159290932430254268769414"
3008        "05973284973216824503042158",
3009        "6703903964971298549787012499102923063739682910296196688861780721"
3010        "8608820150367734884009371490834517138450159290932430254268769414"
3011        "05973284973216824503042159",
3012        "1"
3013    },
3014    {   /* between fifth and sixth iteration */
3015        "5239312332984325668414624633307915097111691815000872662334695514"
3016        "5436533521392362443557163429336808208137221322444780490437871903"
3017        "99972784701334569424519255",
3018        "6703903964971298549787012499102923063739682910296196688861780721"
3019        "8608820150367734884009371490834517138450159290932430254268769414"
3020        "05973284973216824503042158",
3021        "6703903964971298549787012499102923063739682910296196688861780721"
3022        "8608820150367734884009371490834517138450159290932430254268769414"
3023        "05973284973216824503042159",
3024        "1"
3025    },
3026    {   /* between sixth and seventh iteration */
3027        "1977953647322612860406858017869125467496941904523063466791308891"
3028        "1172796739058531929470539758361774569875505293428856181093904091"
3029        "33788264851714311303725089",
3030        "6703903964971298549787012499102923063739682910296196688861780721"
3031        "8608820150367734884009371490834517138450159290932430254268769414"
3032        "05973284973216824503042158",
3033        "6703903964971298549787012499102923063739682910296196688861780721"
3034        "8608820150367734884009371490834517138450159290932430254268769414"
3035        "05973284973216824503042159",
3036        "1"
3037    },
3038    {   /* between seventh and eighth iteration */
3039        "6456987954117763835533395796948878140715006860263624787492985786"
3040        "8514630216966738305923915688821526449499763719943997120302368211"
3041        "04813318117996225041943964",
3042        "1340780792994259709957402499820584612747936582059239337772356144"
3043        "3721764030073546976801874298166903427690031858186486050853753882"
3044        "811946551499689575296532556",
3045        "1340780792994259709957402499820584612747936582059239337772356144"
3046        "3721764030073546976801874298166903427690031858186486050853753882"
3047        "811946551499689575296532557",
3048        "1"
3049    }
3050 };
3051
3052 static int test_mod_exp(int i)
3053 {
3054     const MOD_EXP_TEST *test = &ModExpTests[i];
3055     int res = 0;
3056     BIGNUM* result = NULL;
3057     BIGNUM *base = NULL, *exponent = NULL, *modulo = NULL;
3058     char *s = NULL;
3059
3060     if (!TEST_ptr(result = BN_new())
3061             || !TEST_true(BN_dec2bn(&base, test->base))
3062             || !TEST_true(BN_dec2bn(&exponent, test->exp))
3063             || !TEST_true(BN_dec2bn(&modulo, test->mod)))
3064         goto err;
3065
3066     if (!TEST_int_eq(BN_mod_exp(result, base, exponent, modulo, ctx), 1))
3067         goto err;
3068
3069     if (!TEST_ptr(s = BN_bn2dec(result)))
3070         goto err;
3071
3072     if (!TEST_mem_eq(s, strlen(s), test->res, strlen(test->res)))
3073         goto err;
3074
3075     res = 1;
3076
3077  err:
3078     OPENSSL_free(s);
3079     BN_free(result);
3080     BN_free(base);
3081     BN_free(exponent);
3082     BN_free(modulo);
3083     return res;
3084 }
3085
3086 static int test_mod_exp_consttime(int i)
3087 {
3088     const MOD_EXP_TEST *test = &ModExpTests[i];
3089     int res = 0;
3090     BIGNUM* result = NULL;
3091     BIGNUM *base = NULL, *exponent = NULL, *modulo = NULL;
3092     char *s = NULL;
3093
3094     if (!TEST_ptr(result = BN_new())
3095             || !TEST_true(BN_dec2bn(&base, test->base))
3096             || !TEST_true(BN_dec2bn(&exponent, test->exp))
3097             || !TEST_true(BN_dec2bn(&modulo, test->mod)))
3098         goto err;
3099
3100     BN_set_flags(base, BN_FLG_CONSTTIME);
3101     BN_set_flags(exponent, BN_FLG_CONSTTIME);
3102     BN_set_flags(modulo, BN_FLG_CONSTTIME);
3103
3104     if (!TEST_int_eq(BN_mod_exp(result, base, exponent, modulo, ctx), 1))
3105         goto err;
3106
3107     if (!TEST_ptr(s = BN_bn2dec(result)))
3108         goto err;
3109
3110     if (!TEST_mem_eq(s, strlen(s), test->res, strlen(test->res)))
3111         goto err;
3112
3113     res = 1;
3114
3115  err:
3116     OPENSSL_free(s);
3117     BN_free(result);
3118     BN_free(base);
3119     BN_free(exponent);
3120     BN_free(modulo);
3121     return res;
3122 }
3123
3124 /*
3125  * Regression test to ensure BN_mod_exp2_mont fails safely if argument m is
3126  * zero.
3127  */
3128 static int test_mod_exp2_mont(void)
3129 {
3130     int res = 0;
3131     BIGNUM *exp_result = NULL;
3132     BIGNUM *exp_a1 = NULL, *exp_p1 = NULL, *exp_a2 = NULL, *exp_p2 = NULL,
3133            *exp_m = NULL;
3134
3135     if (!TEST_ptr(exp_result = BN_new())
3136             || !TEST_ptr(exp_a1 = BN_new())
3137             || !TEST_ptr(exp_p1 = BN_new())
3138             || !TEST_ptr(exp_a2 = BN_new())
3139             || !TEST_ptr(exp_p2 = BN_new())
3140             || !TEST_ptr(exp_m = BN_new()))
3141         goto err;
3142
3143     if (!TEST_true(BN_one(exp_a1))
3144             || !TEST_true(BN_one(exp_p1))
3145             || !TEST_true(BN_one(exp_a2))
3146             || !TEST_true(BN_one(exp_p2)))
3147         goto err;
3148
3149     BN_zero(exp_m);
3150
3151     /* input of 0 is even, so must fail */
3152     if (!TEST_int_eq(BN_mod_exp2_mont(exp_result, exp_a1, exp_p1, exp_a2,
3153                 exp_p2, exp_m, ctx, NULL), 0))
3154         goto err;
3155
3156     res = 1;
3157
3158 err:
3159     BN_free(exp_result);
3160     BN_free(exp_a1);
3161     BN_free(exp_p1);
3162     BN_free(exp_a2);
3163     BN_free(exp_p2);
3164     BN_free(exp_m);
3165     return res;
3166 }
3167
3168 static int file_test_run(STANZA *s)
3169 {
3170     static const FILETEST filetests[] = {
3171         {"Sum", file_sum},
3172         {"LShift1", file_lshift1},
3173         {"LShift", file_lshift},
3174         {"RShift", file_rshift},
3175         {"Square", file_square},
3176         {"Product", file_product},
3177         {"Quotient", file_quotient},
3178         {"ModMul", file_modmul},
3179         {"ModExp", file_modexp},
3180         {"Exp", file_exp},
3181         {"ModSqrt", file_modsqrt},
3182         {"GCD", file_gcd},
3183     };
3184     int numtests = OSSL_NELEM(filetests);
3185     const FILETEST *tp = filetests;
3186
3187     for ( ; --numtests >= 0; tp++) {
3188         if (findattr(s, tp->name) != NULL) {
3189             if (!tp->func(s)) {
3190                 TEST_info("%s:%d: Failed %s test",
3191                           s->test_file, s->start, tp->name);
3192                 return 0;
3193             }
3194             return 1;
3195         }
3196     }
3197     TEST_info("%s:%d: Unknown test", s->test_file, s->start);
3198     return 0;
3199 }
3200
3201 static int run_file_tests(int i)
3202 {
3203     STANZA *s = NULL;
3204     char *testfile = test_get_argument(i);
3205     int c;
3206
3207     if (!TEST_ptr(s = OPENSSL_zalloc(sizeof(*s))))
3208         return 0;
3209     if (!test_start_file(s, testfile)) {
3210         OPENSSL_free(s);
3211         return 0;
3212     }
3213
3214     /* Read test file. */
3215     while (!BIO_eof(s->fp) && test_readstanza(s)) {
3216         if (s->numpairs == 0)
3217             continue;
3218         if (!file_test_run(s))
3219             s->errors++;
3220         s->numtests++;
3221         test_clearstanza(s);
3222     }
3223     test_end_file(s);
3224     c = s->errors;
3225     OPENSSL_free(s);
3226
3227     return c == 0;
3228 }
3229
3230 typedef enum OPTION_choice {
3231     OPT_ERR = -1,
3232     OPT_EOF = 0,
3233     OPT_STOCHASTIC_TESTS,
3234     OPT_TEST_ENUM
3235 } OPTION_CHOICE;
3236
3237 const OPTIONS *test_get_options(void)
3238 {
3239     static const OPTIONS test_options[] = {
3240         OPT_TEST_OPTIONS_WITH_EXTRA_USAGE("[file...]\n"),
3241         { "stochastic", OPT_STOCHASTIC_TESTS, '-', "Run stochastic tests" },
3242         { OPT_HELP_STR, 1, '-',
3243           "file\tFile to run tests on. Normal tests are not run\n" },
3244         { NULL }
3245     };
3246     return test_options;
3247 }
3248
3249 int setup_tests(void)
3250 {
3251     OPTION_CHOICE o;
3252     int n, stochastic = 0;
3253
3254     while ((o = opt_next()) != OPT_EOF) {
3255         switch (o) {
3256         case OPT_STOCHASTIC_TESTS:
3257             stochastic = 1;
3258             break;
3259         case OPT_TEST_CASES:
3260            break;
3261         default:
3262         case OPT_ERR:
3263             return 0;
3264         }
3265     }
3266     n  = test_get_argument_count();
3267
3268     if (!TEST_ptr(ctx = BN_CTX_new()))
3269         return 0;
3270
3271     if (n == 0) {
3272         ADD_TEST(test_sub);
3273         ADD_TEST(test_div_recip);
3274         ADD_ALL_TESTS(test_signed_mod_replace_ab, OSSL_NELEM(signed_mod_tests));
3275         ADD_ALL_TESTS(test_signed_mod_replace_ba, OSSL_NELEM(signed_mod_tests));
3276         ADD_TEST(test_mod);
3277         ADD_TEST(test_modexp_mont5);
3278         ADD_TEST(test_kronecker);
3279         ADD_TEST(test_rand);
3280         ADD_TEST(test_bn2padded);
3281         ADD_TEST(test_dec2bn);
3282         ADD_TEST(test_hex2bn);
3283         ADD_TEST(test_asc2bn);
3284         ADD_TEST(test_bin2zero);
3285         ADD_TEST(test_bin2bn_lengths);
3286         ADD_ALL_TESTS(test_mpi, (int)OSSL_NELEM(kMPITests));
3287         ADD_ALL_TESTS(test_bn2signed, (int)OSSL_NELEM(kSignedTests_BE));
3288         ADD_TEST(test_negzero);
3289         ADD_TEST(test_badmod);
3290         ADD_TEST(test_expmodzero);
3291         ADD_TEST(test_expmodone);
3292         ADD_ALL_TESTS(test_smallprime, 16);
3293         ADD_ALL_TESTS(test_smallsafeprime, 16);
3294         ADD_TEST(test_swap);
3295         ADD_TEST(test_ctx_consttime_flag);
3296 #ifndef OPENSSL_NO_EC2M
3297         ADD_TEST(test_gf2m_add);
3298         ADD_TEST(test_gf2m_mod);
3299         ADD_TEST(test_gf2m_mul);
3300         ADD_TEST(test_gf2m_sqr);
3301         ADD_TEST(test_gf2m_modinv);
3302         ADD_TEST(test_gf2m_moddiv);
3303         ADD_TEST(test_gf2m_modexp);
3304         ADD_TEST(test_gf2m_modsqrt);
3305         ADD_TEST(test_gf2m_modsolvequad);
3306 #endif
3307         ADD_ALL_TESTS(test_is_prime, (int)OSSL_NELEM(primes));
3308         ADD_ALL_TESTS(test_not_prime, (int)OSSL_NELEM(not_primes));
3309         ADD_TEST(test_gcd_prime);
3310         ADD_TEST(test_coprime);
3311         ADD_ALL_TESTS(test_mod_exp, (int)OSSL_NELEM(ModExpTests));
3312         ADD_ALL_TESTS(test_mod_exp_consttime, (int)OSSL_NELEM(ModExpTests));
3313         ADD_TEST(test_mod_exp2_mont);
3314         if (stochastic)
3315             ADD_TEST(test_rand_range);
3316     } else {
3317         ADD_ALL_TESTS(run_file_tests, n);
3318     }
3319     return 1;
3320 }
3321
3322 void cleanup_tests(void)
3323 {
3324     BN_CTX_free(ctx);
3325 }