ARM64 assembly pack: make it Windows-friendly.
[openssl.git] / test / bntest.c
1 /*
2  * Copyright 1995-2018 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 #include <ctype.h>
14
15 #include <openssl/bn.h>
16 #include <openssl/crypto.h>
17 #include <openssl/err.h>
18 #include <openssl/rand.h>
19 #include "internal/nelem.h"
20 #include "internal/numbers.h"
21 #include "testutil.h"
22
23 #ifdef OPENSSL_SYS_WINDOWS
24 # define strcasecmp _stricmp
25 #endif
26
27 /*
28  * Things in boring, not in openssl.  TODO we should add them.
29  */
30 #define HAVE_BN_PADDED 0
31 #define HAVE_BN_SQRT 0
32
33 typedef struct filetest_st {
34     const char *name;
35     int (*func)(STANZA *s);
36 } FILETEST;
37
38 typedef struct mpitest_st {
39     const char *base10;
40     const char *mpi;
41     size_t mpi_len;
42 } MPITEST;
43
44 static const int NUM0 = 100;           /* number of tests */
45 static const int NUM1 = 50;            /* additional tests for some functions */
46 static BN_CTX *ctx;
47
48 /*
49  * Polynomial coefficients used in GFM tests.
50  */
51 #ifndef OPENSSL_NO_EC2M
52 static int p0[] = { 163, 7, 6, 3, 0, -1 };
53 static int p1[] = { 193, 15, 0, -1 };
54 #endif
55
56 /*
57  * Look for |key| in the stanza and return it or NULL if not found.
58  */
59 static const char *findattr(STANZA *s, const char *key)
60 {
61     int i = s->numpairs;
62     PAIR *pp = s->pairs;
63
64     for ( ; --i >= 0; pp++)
65         if (strcasecmp(pp->key, key) == 0)
66             return pp->value;
67     return NULL;
68 }
69
70 /*
71  * Parse BIGNUM from sparse hex-strings, return |BN_hex2bn| result.
72  */
73 static int parse_bigBN(BIGNUM **out, const char *bn_strings[])
74 {
75     char *bigstring = glue_strings(bn_strings, NULL);
76     int ret = BN_hex2bn(out, bigstring);
77
78     OPENSSL_free(bigstring);
79     return ret;
80 }
81
82 /*
83  * Parse BIGNUM, return number of bytes parsed.
84  */
85 static int parseBN(BIGNUM **out, const char *in)
86 {
87     *out = NULL;
88     return BN_hex2bn(out, in);
89 }
90
91 static int parsedecBN(BIGNUM **out, const char *in)
92 {
93     *out = NULL;
94     return BN_dec2bn(out, in);
95 }
96
97 static BIGNUM *getBN(STANZA *s, const char *attribute)
98 {
99     const char *hex;
100     BIGNUM *ret = NULL;
101
102     if ((hex = findattr(s, attribute)) == NULL) {
103         TEST_error("%s:%d: Can't find %s", s->test_file, s->start, attribute);
104         return NULL;
105     }
106
107     if (parseBN(&ret, hex) != (int)strlen(hex)) {
108         TEST_error("Could not decode '%s'", hex);
109         return NULL;
110     }
111     return ret;
112 }
113
114 static int getint(STANZA *s, int *out, const char *attribute)
115 {
116     BIGNUM *ret;
117     BN_ULONG word;
118     int st = 0;
119
120     if (!TEST_ptr(ret = getBN(s, attribute))
121             || !TEST_ulong_le(word = BN_get_word(ret), INT_MAX))
122         goto err;
123
124     *out = (int)word;
125     st = 1;
126 err:
127     BN_free(ret);
128     return st;
129 }
130
131 static int equalBN(const char *op, const BIGNUM *expected, const BIGNUM *actual)
132 {
133     if (BN_cmp(expected, actual) == 0)
134         return 1;
135
136     TEST_error("unexpected %s value", op);
137     TEST_BN_eq(expected, actual);
138     return 0;
139 }
140
141
142 /*
143  * Return a "random" flag for if a BN should be negated.
144  */
145 static int rand_neg(void)
146 {
147     static unsigned int neg = 0;
148     static int sign[8] = { 0, 0, 0, 1, 1, 0, 1, 1 };
149
150     return sign[(neg++) % 8];
151 }
152
153
154 static int test_swap(void)
155 {
156     BIGNUM *a = NULL, *b = NULL, *c = NULL, *d = NULL;
157     int top, cond, st = 0;
158
159     if (!TEST_ptr(a = BN_new())
160             || !TEST_ptr(b = BN_new())
161             || !TEST_ptr(c = BN_new())
162             || !TEST_ptr(d = BN_new()))
163         goto err;
164
165     BN_bntest_rand(a, 1024, 1, 0);
166     BN_bntest_rand(b, 1024, 1, 0);
167     BN_copy(c, a);
168     BN_copy(d, b);
169     top = BN_num_bits(a)/BN_BITS2;
170
171     /* regular swap */
172     BN_swap(a, b);
173     if (!equalBN("swap", a, d)
174             || !equalBN("swap", b, c))
175         goto err;
176
177     /* conditional swap: true */
178     cond = 1;
179     BN_consttime_swap(cond, a, b, top);
180     if (!equalBN("cswap true", a, c)
181             || !equalBN("cswap true", b, d))
182         goto err;
183
184     /* conditional swap: false */
185     cond = 0;
186     BN_consttime_swap(cond, a, b, top);
187     if (!equalBN("cswap false", a, c)
188             || !equalBN("cswap false", b, d))
189         goto err;
190
191     /* same tests but checking flag swap */
192     BN_set_flags(a, BN_FLG_CONSTTIME);
193
194     BN_swap(a, b);
195     if (!equalBN("swap, flags", a, d)
196             || !equalBN("swap, flags", b, c)
197             || !TEST_true(BN_get_flags(b, BN_FLG_CONSTTIME))
198             || !TEST_false(BN_get_flags(a, BN_FLG_CONSTTIME)))
199         goto err;
200
201     cond = 1;
202     BN_consttime_swap(cond, a, b, top);
203     if (!equalBN("cswap true, flags", a, c)
204             || !equalBN("cswap true, flags", b, d)
205             || !TEST_true(BN_get_flags(a, BN_FLG_CONSTTIME))
206             || !TEST_false(BN_get_flags(b, BN_FLG_CONSTTIME)))
207         goto err;
208
209     cond = 0;
210     BN_consttime_swap(cond, a, b, top);
211     if (!equalBN("cswap false, flags", a, c)
212             || !equalBN("cswap false, flags", b, d)
213             || !TEST_true(BN_get_flags(a, BN_FLG_CONSTTIME))
214             || !TEST_false(BN_get_flags(b, BN_FLG_CONSTTIME)))
215         goto err;
216
217     st = 1;
218  err:
219     BN_free(a);
220     BN_free(b);
221     BN_free(c);
222     BN_free(d);
223     return st;
224 }
225
226 static int test_sub(void)
227 {
228     BIGNUM *a = NULL, *b = NULL, *c = NULL;
229     int i, st = 0;
230
231     if (!TEST_ptr(a = BN_new())
232             || !TEST_ptr(b = BN_new())
233             || !TEST_ptr(c = BN_new()))
234         goto err;
235
236     for (i = 0; i < NUM0 + NUM1; i++) {
237         if (i < NUM1) {
238             BN_bntest_rand(a, 512, 0, 0);
239             BN_copy(b, a);
240             if (!TEST_int_ne(BN_set_bit(a, i), 0))
241                 goto err;
242             BN_add_word(b, i);
243         } else {
244             BN_bntest_rand(b, 400 + i - NUM1, 0, 0);
245             BN_set_negative(a, rand_neg());
246             BN_set_negative(b, rand_neg());
247         }
248         BN_sub(c, a, b);
249         BN_add(c, c, b);
250         BN_sub(c, c, a);
251         if (!TEST_BN_eq_zero(c))
252             goto err;
253     }
254     st = 1;
255 err:
256     BN_free(a);
257     BN_free(b);
258     BN_free(c);
259     return st;
260 }
261
262
263 static int test_div_recip(void)
264 {
265     BIGNUM *a = NULL, *b = NULL, *c = NULL, *d = NULL, *e = NULL;
266     BN_RECP_CTX *recp = NULL;
267     int st = 0, i;
268
269     if (!TEST_ptr(a = BN_new())
270             || !TEST_ptr(b = BN_new())
271             || !TEST_ptr(c = BN_new())
272             || !TEST_ptr(d = BN_new())
273             || !TEST_ptr(e = BN_new())
274             || !TEST_ptr(recp = BN_RECP_CTX_new()))
275         goto err;
276
277     for (i = 0; i < NUM0 + NUM1; i++) {
278         if (i < NUM1) {
279             BN_bntest_rand(a, 400, 0, 0);
280             BN_copy(b, a);
281             BN_lshift(a, a, i);
282             BN_add_word(a, i);
283         } else
284             BN_bntest_rand(b, 50 + 3 * (i - NUM1), 0, 0);
285         BN_set_negative(a, rand_neg());
286         BN_set_negative(b, rand_neg());
287         BN_RECP_CTX_set(recp, b, ctx);
288         BN_div_recp(d, c, a, recp, ctx);
289         BN_mul(e, d, b, ctx);
290         BN_add(d, e, c);
291         BN_sub(d, d, a);
292         if (!TEST_BN_eq_zero(d))
293             goto err;
294     }
295     st = 1;
296 err:
297     BN_free(a);
298     BN_free(b);
299     BN_free(c);
300     BN_free(d);
301     BN_free(e);
302     BN_RECP_CTX_free(recp);
303     return st;
304 }
305
306
307 static int test_mod(void)
308 {
309     BIGNUM *a = NULL, *b = NULL, *c = NULL, *d = NULL, *e = NULL;
310     int st = 0, i;
311
312     if (!TEST_ptr(a = BN_new())
313             || !TEST_ptr(b = BN_new())
314             || !TEST_ptr(c = BN_new())
315             || !TEST_ptr(d = BN_new())
316             || !TEST_ptr(e = BN_new()))
317         goto err;
318
319     BN_bntest_rand(a, 1024, 0, 0);
320     for (i = 0; i < NUM0; i++) {
321         BN_bntest_rand(b, 450 + i * 10, 0, 0);
322         BN_set_negative(a, rand_neg());
323         BN_set_negative(b, rand_neg());
324         BN_mod(c, a, b, ctx);
325         BN_div(d, e, a, b, ctx);
326         BN_sub(e, e, c);
327         if (!TEST_BN_eq_zero(e))
328             goto err;
329     }
330     st = 1;
331 err:
332     BN_free(a);
333     BN_free(b);
334     BN_free(c);
335     BN_free(d);
336     BN_free(e);
337     return st;
338 }
339
340 static const char *bn1strings[] = {
341     "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
342     "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
343     "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
344     "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
345     "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
346     "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
347     "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
348     "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000000000FFFFFFFF00",
349     "0000000000000000000000000000000000000000000000000000000000000000",
350     "0000000000000000000000000000000000000000000000000000000000000000",
351     "0000000000000000000000000000000000000000000000000000000000000000",
352     "0000000000000000000000000000000000000000000000000000000000000000",
353     "0000000000000000000000000000000000000000000000000000000000000000",
354     "0000000000000000000000000000000000000000000000000000000000000000",
355     "0000000000000000000000000000000000000000000000000000000000000000",
356     "00000000000000000000000000000000000000000000000000FFFFFFFFFFFFFF",
357     NULL
358 };
359
360 static const char *bn2strings[] = {
361     "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
362     "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
363     "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
364     "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
365     "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
366     "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
367     "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
368     "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000000000FFFFFFFF0000000000",
369     "0000000000000000000000000000000000000000000000000000000000000000",
370     "0000000000000000000000000000000000000000000000000000000000000000",
371     "0000000000000000000000000000000000000000000000000000000000000000",
372     "0000000000000000000000000000000000000000000000000000000000000000",
373     "0000000000000000000000000000000000000000000000000000000000000000",
374     "0000000000000000000000000000000000000000000000000000000000000000",
375     "0000000000000000000000000000000000000000000000000000000000000000",
376     "000000000000000000000000000000000000000000FFFFFFFFFFFFFF00000000",
377     NULL
378 };
379
380 /*
381  * Test constant-time modular exponentiation with 1024-bit inputs, which on
382  * x86_64 cause a different code branch to be taken.
383  */
384 static int test_modexp_mont5(void)
385 {
386     BIGNUM *a = NULL, *p = NULL, *m = NULL, *d = NULL, *e = NULL;
387     BIGNUM *b = NULL, *n = NULL, *c = NULL;
388     BN_MONT_CTX *mont = NULL;
389     int st = 0;
390
391     if (!TEST_ptr(a = BN_new())
392             || !TEST_ptr(p = BN_new())
393             || !TEST_ptr(m = BN_new())
394             || !TEST_ptr(d = BN_new())
395             || !TEST_ptr(e = BN_new())
396             || !TEST_ptr(b = BN_new())
397             || !TEST_ptr(n = BN_new())
398             || !TEST_ptr(c = BN_new())
399             || !TEST_ptr(mont = BN_MONT_CTX_new()))
400         goto err;
401
402     BN_bntest_rand(m, 1024, 0, 1); /* must be odd for montgomery */
403     /* Zero exponent */
404     BN_bntest_rand(a, 1024, 0, 0);
405     BN_zero(p);
406     if (!TEST_true(BN_mod_exp_mont_consttime(d, a, p, m, ctx, NULL)))
407         goto err;
408     if (!TEST_BN_eq_one(d))
409         goto err;
410
411     /* Regression test for carry bug in mulx4x_mont */
412     BN_hex2bn(&a,
413         "7878787878787878787878787878787878787878787878787878787878787878"
414         "7878787878787878787878787878787878787878787878787878787878787878"
415         "7878787878787878787878787878787878787878787878787878787878787878"
416         "7878787878787878787878787878787878787878787878787878787878787878");
417     BN_hex2bn(&b,
418         "095D72C08C097BA488C5E439C655A192EAFB6380073D8C2664668EDDB4060744"
419         "E16E57FB4EDB9AE10A0CEFCDC28A894F689A128379DB279D48A2E20849D68593"
420         "9B7803BCF46CEBF5C533FB0DD35B080593DE5472E3FE5DB951B8BFF9B4CB8F03"
421         "9CC638A5EE8CDD703719F8000E6A9F63BEED5F2FCD52FF293EA05A251BB4AB81");
422     BN_hex2bn(&n,
423         "D78AF684E71DB0C39CFF4E64FB9DB567132CB9C50CC98009FEB820B26F2DED9B"
424         "91B9B5E2B83AE0AE4EB4E0523CA726BFBE969B89FD754F674CE99118C3F2D1C5"
425         "D81FDC7C54E02B60262B241D53C040E99E45826ECA37A804668E690E1AFC1CA4"
426         "2C9A15D84D4954425F0B7642FC0BD9D7B24E2618D2DCC9B729D944BADACFDDAF");
427     BN_MONT_CTX_set(mont, n, ctx);
428     BN_mod_mul_montgomery(c, a, b, mont, ctx);
429     BN_mod_mul_montgomery(d, b, a, mont, ctx);
430     if (!TEST_BN_eq(c, d))
431         goto err;
432
433     /* Regression test for carry bug in sqr[x]8x_mont */
434     parse_bigBN(&n, bn1strings);
435     parse_bigBN(&a, bn2strings);
436     BN_free(b);
437     b = BN_dup(a);
438     BN_MONT_CTX_set(mont, n, ctx);
439     BN_mod_mul_montgomery(c, a, a, mont, ctx);
440     BN_mod_mul_montgomery(d, a, b, mont, ctx);
441     if (!TEST_BN_eq(c, d))
442         goto err;
443
444     /* Regression test for carry bug in bn_sqrx8x_internal */
445     {
446         static const char *ahex[] = {
447                       "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
448             "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
449             "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
450             "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
451             "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF8FFEADBCFC4DAE7FFF908E92820306B",
452             "9544D954000000006C0000000000000000000000000000000000000000000000",
453             "00000000000000000000FF030202FFFFF8FFEBDBCFC4DAE7FFF908E92820306B",
454             "9544D954000000006C000000FF0302030000000000FFFFFFFFFFFFFFFFFFFFFF",
455             "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF01FC00FF02FFFFFFFF",
456             "00FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00FCFD",
457             "FCFFFFFFFFFF000000000000000000FF0302030000000000FFFFFFFFFFFFFFFF",
458             "FF00FCFDFDFF030202FF00000000FFFFFFFFFFFFFFFFFF00FCFDFCFFFFFFFFFF",
459             NULL
460         };
461         static const char *nhex[] = {
462                       "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
463             "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
464             "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
465             "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
466             "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF8F8F8F8000000",
467             "00000010000000006C0000000000000000000000000000000000000000000000",
468             "00000000000000000000000000000000000000FFFFFFFFFFFFF8F8F8F8000000",
469             "00000010000000006C000000000000000000000000FFFFFFFFFFFFFFFFFFFFFF",
470             "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
471             "00FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
472             "FFFFFFFFFFFF000000000000000000000000000000000000FFFFFFFFFFFFFFFF",
473             "FFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
474             NULL
475         };
476
477         parse_bigBN(&a, ahex);
478         parse_bigBN(&n, nhex);
479     }
480     BN_free(b);
481     b = BN_dup(a);
482     BN_MONT_CTX_set(mont, n, ctx);
483     if (!TEST_true(BN_mod_mul_montgomery(c, a, a, mont, ctx))
484             || !TEST_true(BN_mod_mul_montgomery(d, a, b, mont, ctx))
485             || !TEST_BN_eq(c, d))
486         goto err;
487
488     /* Regression test for bug in BN_from_montgomery_word */
489     BN_hex2bn(&a,
490         "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
491         "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
492         "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF");
493     BN_hex2bn(&n,
494         "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
495         "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF");
496     BN_MONT_CTX_set(mont, n, ctx);
497     if (!TEST_false(BN_mod_mul_montgomery(d, a, a, mont, ctx)))
498         goto err;
499
500     /* Regression test for bug in rsaz_1024_mul_avx2 */
501     BN_hex2bn(&a,
502         "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
503         "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
504         "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
505         "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF2020202020DF");
506     BN_hex2bn(&b,
507         "2020202020202020202020202020202020202020202020202020202020202020"
508         "2020202020202020202020202020202020202020202020202020202020202020"
509         "20202020202020FF202020202020202020202020202020202020202020202020"
510         "2020202020202020202020202020202020202020202020202020202020202020");
511     BN_hex2bn(&n,
512         "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
513         "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
514         "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
515         "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF2020202020FF");
516     BN_MONT_CTX_set(mont, n, ctx);
517     BN_mod_exp_mont_consttime(c, a, b, n, ctx, mont);
518     BN_mod_exp_mont(d, a, b, n, ctx, mont);
519     if (!TEST_BN_eq(c, d))
520         goto err;
521
522     /*
523      * rsaz_1024_mul_avx2 expects fully-reduced inputs.
524      * BN_mod_exp_mont_consttime should reduce the input first.
525      */
526     BN_hex2bn(&a,
527         "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
528         "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
529         "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
530         "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF2020202020DF");
531     BN_hex2bn(&b,
532         "1FA53F26F8811C58BE0357897AA5E165693230BC9DF5F01DFA6A2D59229EC69D"
533         "9DE6A89C36E3B6957B22D6FAAD5A3C73AE587B710DBE92E83D3A9A3339A085CB"
534         "B58F508CA4F837924BB52CC1698B7FDC2FD74362456A595A5B58E38E38E38E38"
535         "E38E38E38E38E38E38E38E38E38E38E38E38E38E38E38E38E38E38E38E38E38E");
536     BN_hex2bn(&n,
537         "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
538         "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
539         "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
540         "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF2020202020DF");
541     BN_MONT_CTX_set(mont, n, ctx);
542     BN_mod_exp_mont_consttime(c, a, b, n, ctx, mont);
543     BN_zero(d);
544     if (!TEST_BN_eq(c, d))
545         goto err;
546
547     /* Zero input */
548     BN_bntest_rand(p, 1024, 0, 0);
549     BN_zero(a);
550     if (!TEST_true(BN_mod_exp_mont_consttime(d, a, p, m, ctx, NULL))
551             || !TEST_BN_eq_zero(d))
552         goto err;
553
554     /*
555      * Craft an input whose Montgomery representation is 1, i.e., shorter
556      * than the modulus m, in order to test the const time precomputation
557      * scattering/gathering.
558      */
559     BN_one(a);
560     BN_MONT_CTX_set(mont, m, ctx);
561     if (!TEST_true(BN_from_montgomery(e, a, mont, ctx))
562             || !TEST_true(BN_mod_exp_mont_consttime(d, e, p, m, ctx, NULL))
563             || !TEST_true(BN_mod_exp_simple(a, e, p, m, ctx))
564             || !TEST_BN_eq(a, d))
565         goto err;
566
567     /* Finally, some regular test vectors. */
568     BN_bntest_rand(e, 1024, 0, 0);
569     if (!TEST_true(BN_mod_exp_mont_consttime(d, e, p, m, ctx, NULL))
570             || !TEST_true(BN_mod_exp_simple(a, e, p, m, ctx))
571             || !TEST_BN_eq(a, d))
572         goto err;
573
574     st = 1;
575
576 err:
577     BN_MONT_CTX_free(mont);
578     BN_free(a);
579     BN_free(p);
580     BN_free(m);
581     BN_free(d);
582     BN_free(e);
583     BN_free(b);
584     BN_free(n);
585     BN_free(c);
586     return st;
587 }
588
589 #ifndef OPENSSL_NO_EC2M
590 static int test_gf2m_add(void)
591 {
592     BIGNUM *a = NULL, *b = NULL, *c = NULL;
593     int i, st = 0;
594
595     if (!TEST_ptr(a = BN_new())
596             || !TEST_ptr(b = BN_new())
597             || !TEST_ptr(c = BN_new()))
598         goto err;
599
600     for (i = 0; i < NUM0; i++) {
601         BN_rand(a, 512, 0, 0);
602         BN_copy(b, BN_value_one());
603         BN_set_negative(a, rand_neg());
604         BN_set_negative(b, rand_neg());
605         BN_GF2m_add(c, a, b);
606         /* Test that two added values have the correct parity. */
607         if (!TEST_false((BN_is_odd(a) && BN_is_odd(c))
608                         || (!BN_is_odd(a) && !BN_is_odd(c))))
609             goto err;
610         BN_GF2m_add(c, c, c);
611         /* Test that c + c = 0. */
612         if (!TEST_BN_eq_zero(c))
613             goto err;
614     }
615     st = 1;
616  err:
617     BN_free(a);
618     BN_free(b);
619     BN_free(c);
620     return st;
621 }
622
623 static int test_gf2m_mod(void)
624 {
625     BIGNUM *a = NULL, *b[2] = {NULL,NULL}, *c = NULL, *d = NULL, *e = NULL;
626     int i, j, st = 0;
627
628     if (!TEST_ptr(a = BN_new())
629             || !TEST_ptr(b[0] = BN_new())
630             || !TEST_ptr(b[1] = BN_new())
631             || !TEST_ptr(c = BN_new())
632             || !TEST_ptr(d = BN_new())
633             || !TEST_ptr(e = BN_new()))
634         goto err;
635
636     BN_GF2m_arr2poly(p0, b[0]);
637     BN_GF2m_arr2poly(p1, b[1]);
638
639     for (i = 0; i < NUM0; i++) {
640         BN_bntest_rand(a, 1024, 0, 0);
641         for (j = 0; j < 2; j++) {
642             BN_GF2m_mod(c, a, b[j]);
643             BN_GF2m_add(d, a, c);
644             BN_GF2m_mod(e, d, b[j]);
645             /* Test that a + (a mod p) mod p == 0. */
646             if (!TEST_BN_eq_zero(e))
647                 goto err;
648         }
649     }
650     st = 1;
651  err:
652     BN_free(a);
653     BN_free(b[0]);
654     BN_free(b[1]);
655     BN_free(c);
656     BN_free(d);
657     BN_free(e);
658     return st;
659 }
660
661 static int test_gf2m_mul(void)
662 {
663     BIGNUM *a, *b[2] = {NULL, NULL}, *c = NULL, *d = NULL;
664     BIGNUM *e = NULL, *f = NULL, *g = NULL, *h = NULL;
665     int i, j, st = 0;
666
667     if (!TEST_ptr(a = BN_new())
668             || !TEST_ptr(b[0] = BN_new())
669             || !TEST_ptr(b[1] = BN_new())
670             || !TEST_ptr(c = BN_new())
671             || !TEST_ptr(d = BN_new())
672             || !TEST_ptr(e = BN_new())
673             || !TEST_ptr(f = BN_new())
674             || !TEST_ptr(g = BN_new())
675             || !TEST_ptr(h = BN_new()))
676         goto err;
677
678     BN_GF2m_arr2poly(p0, b[0]);
679     BN_GF2m_arr2poly(p1, b[1]);
680
681     for (i = 0; i < NUM0; i++) {
682         BN_bntest_rand(a, 1024, 0, 0);
683         BN_bntest_rand(c, 1024, 0, 0);
684         BN_bntest_rand(d, 1024, 0, 0);
685         for (j = 0; j < 2; j++) {
686             BN_GF2m_mod_mul(e, a, c, b[j], ctx);
687             BN_GF2m_add(f, a, d);
688             BN_GF2m_mod_mul(g, f, c, b[j], ctx);
689             BN_GF2m_mod_mul(h, d, c, b[j], ctx);
690             BN_GF2m_add(f, e, g);
691             BN_GF2m_add(f, f, h);
692             /* Test that (a+d)*c = a*c + d*c. */
693             if (!TEST_BN_eq_zero(f))
694                 goto err;
695         }
696     }
697     st = 1;
698
699  err:
700     BN_free(a);
701     BN_free(b[0]);
702     BN_free(b[1]);
703     BN_free(c);
704     BN_free(d);
705     BN_free(e);
706     BN_free(f);
707     BN_free(g);
708     BN_free(h);
709     return st;
710 }
711
712 static int test_gf2m_sqr(void)
713 {
714     BIGNUM *a = NULL, *b[2] = {NULL,NULL}, *c = NULL, *d = NULL;
715     int i, j, st = 0;
716
717     if (!TEST_ptr(a = BN_new())
718             || !TEST_ptr(b[0] = BN_new())
719             || !TEST_ptr(b[1] = BN_new())
720             || !TEST_ptr(c = BN_new())
721             || !TEST_ptr(d = BN_new()))
722         goto err;
723
724     BN_GF2m_arr2poly(p0, b[0]);
725     BN_GF2m_arr2poly(p1, b[1]);
726
727     for (i = 0; i < NUM0; i++) {
728         BN_bntest_rand(a, 1024, 0, 0);
729         for (j = 0; j < 2; j++) {
730             BN_GF2m_mod_sqr(c, a, b[j], ctx);
731             BN_copy(d, a);
732             BN_GF2m_mod_mul(d, a, d, b[j], ctx);
733             BN_GF2m_add(d, c, d);
734             /* Test that a*a = a^2. */
735             if (!TEST_BN_eq_zero(d))
736                 goto err;
737         }
738     }
739     st = 1;
740  err:
741     BN_free(a);
742     BN_free(b[0]);
743     BN_free(b[1]);
744     BN_free(c);
745     BN_free(d);
746     return st;
747 }
748
749 static int test_gf2m_modinv(void)
750 {
751     BIGNUM *a = NULL, *b[2] = {NULL,NULL}, *c = NULL, *d = NULL;
752     int i, j, st = 0;
753
754     if (!TEST_ptr(a = BN_new())
755             || !TEST_ptr(b[0] = BN_new())
756             || !TEST_ptr(b[1] = BN_new())
757             || !TEST_ptr(c = BN_new())
758             || !TEST_ptr(d = BN_new()))
759         goto err;
760
761     BN_GF2m_arr2poly(p0, b[0]);
762     BN_GF2m_arr2poly(p1, b[1]);
763
764     for (i = 0; i < NUM0; i++) {
765         BN_bntest_rand(a, 512, 0, 0);
766         for (j = 0; j < 2; j++) {
767             BN_GF2m_mod_inv(c, a, b[j], ctx);
768             BN_GF2m_mod_mul(d, a, c, b[j], ctx);
769             /* Test that ((1/a)*a) = 1. */
770             if (!TEST_BN_eq_one(d))
771                 goto err;
772         }
773     }
774     st = 1;
775  err:
776     BN_free(a);
777     BN_free(b[0]);
778     BN_free(b[1]);
779     BN_free(c);
780     BN_free(d);
781     return st;
782 }
783
784 static int test_gf2m_moddiv(void)
785 {
786     BIGNUM *a = NULL, *b[2] = {NULL,NULL}, *c = NULL, *d = NULL;
787     BIGNUM *e = NULL, *f = NULL;
788     int i, j, st = 0;
789
790     if (!TEST_ptr(a = BN_new())
791             || !TEST_ptr(b[0] = BN_new())
792             || !TEST_ptr(b[1] = BN_new())
793             || !TEST_ptr(c = BN_new())
794             || !TEST_ptr(d = BN_new())
795             || !TEST_ptr(e = BN_new())
796             || !TEST_ptr(f = BN_new()))
797         goto err;
798
799     BN_GF2m_arr2poly(p0, b[0]);
800     BN_GF2m_arr2poly(p1, b[1]);
801
802     for (i = 0; i < NUM0; i++) {
803         BN_bntest_rand(a, 512, 0, 0);
804         BN_bntest_rand(c, 512, 0, 0);
805         for (j = 0; j < 2; j++) {
806             BN_GF2m_mod_div(d, a, c, b[j], ctx);
807             BN_GF2m_mod_mul(e, d, c, b[j], ctx);
808             BN_GF2m_mod_div(f, a, e, b[j], ctx);
809             /* Test that ((a/c)*c)/a = 1. */
810             if (!TEST_BN_eq_one(f))
811                 goto err;
812         }
813     }
814     st = 1;
815  err:
816     BN_free(a);
817     BN_free(b[0]);
818     BN_free(b[1]);
819     BN_free(c);
820     BN_free(d);
821     BN_free(e);
822     BN_free(f);
823     return st;
824 }
825
826 static int test_gf2m_modexp(void)
827 {
828     BIGNUM *a = NULL, *b[2] = {NULL,NULL}, *c = NULL, *d = NULL;
829     BIGNUM *e = NULL, *f = NULL;
830     int i, j, st = 0;
831
832     if (!TEST_ptr(a = BN_new())
833             || !TEST_ptr(b[0] = BN_new())
834             || !TEST_ptr(b[1] = BN_new())
835             || !TEST_ptr(c = BN_new())
836             || !TEST_ptr(d = BN_new())
837             || !TEST_ptr(e = BN_new())
838             || !TEST_ptr(f = BN_new()))
839         goto err;
840
841     BN_GF2m_arr2poly(p0, b[0]);
842     BN_GF2m_arr2poly(p1, b[1]);
843
844     for (i = 0; i < NUM0; i++) {
845         BN_bntest_rand(a, 512, 0, 0);
846         BN_bntest_rand(c, 512, 0, 0);
847         BN_bntest_rand(d, 512, 0, 0);
848         for (j = 0; j < 2; j++) {
849             BN_GF2m_mod_exp(e, a, c, b[j], ctx);
850             BN_GF2m_mod_exp(f, a, d, b[j], ctx);
851             BN_GF2m_mod_mul(e, e, f, b[j], ctx);
852             BN_add(f, c, d);
853             BN_GF2m_mod_exp(f, a, f, b[j], ctx);
854             BN_GF2m_add(f, e, f);
855             /* Test that a^(c+d)=a^c*a^d. */
856             if (!TEST_BN_eq_zero(f))
857                 goto err;
858         }
859     }
860     st = 1;
861  err:
862     BN_free(a);
863     BN_free(b[0]);
864     BN_free(b[1]);
865     BN_free(c);
866     BN_free(d);
867     BN_free(e);
868     BN_free(f);
869     return st;
870 }
871
872 static int test_gf2m_modsqrt(void)
873 {
874     BIGNUM *a = NULL, *b[2] = {NULL,NULL}, *c = NULL, *d = NULL;
875     BIGNUM *e = NULL, *f = NULL;
876     int i, j, st = 0;
877
878     if (!TEST_ptr(a = BN_new())
879             || !TEST_ptr(b[0] = BN_new())
880             || !TEST_ptr(b[1] = BN_new())
881             || !TEST_ptr(c = BN_new())
882             || !TEST_ptr(d = BN_new())
883             || !TEST_ptr(e = BN_new())
884             || !TEST_ptr(f = BN_new()))
885         goto err;
886
887     BN_GF2m_arr2poly(p0, b[0]);
888     BN_GF2m_arr2poly(p1, b[1]);
889
890     for (i = 0; i < NUM0; i++) {
891         BN_bntest_rand(a, 512, 0, 0);
892         for (j = 0; j < 2; j++) {
893             BN_GF2m_mod(c, a, b[j]);
894             BN_GF2m_mod_sqrt(d, a, b[j], ctx);
895             BN_GF2m_mod_sqr(e, d, b[j], ctx);
896             BN_GF2m_add(f, c, e);
897             /* Test that d^2 = a, where d = sqrt(a). */
898             if (!TEST_BN_eq_zero(f))
899                 goto err;
900         }
901     }
902     st = 1;
903  err:
904     BN_free(a);
905     BN_free(b[0]);
906     BN_free(b[1]);
907     BN_free(c);
908     BN_free(d);
909     BN_free(e);
910     BN_free(f);
911     return st;
912 }
913
914 static int test_gf2m_modsolvequad(void)
915 {
916     BIGNUM *a = NULL, *b[2] = {NULL,NULL}, *c = NULL, *d = NULL;
917     BIGNUM *e = NULL;
918     int i, j, s = 0, t, st = 0;
919
920     if (!TEST_ptr(a = BN_new())
921             || !TEST_ptr(b[0] = BN_new())
922             || !TEST_ptr(b[1] = BN_new())
923             || !TEST_ptr(c = BN_new())
924             || !TEST_ptr(d = BN_new())
925             || !TEST_ptr(e = BN_new()))
926         goto err;
927
928     BN_GF2m_arr2poly(p0, b[0]);
929     BN_GF2m_arr2poly(p1, b[1]);
930
931     for (i = 0; i < NUM0; i++) {
932         BN_bntest_rand(a, 512, 0, 0);
933         for (j = 0; j < 2; j++) {
934             t = BN_GF2m_mod_solve_quad(c, a, b[j], ctx);
935             if (t) {
936                 s++;
937                 BN_GF2m_mod_sqr(d, c, b[j], ctx);
938                 BN_GF2m_add(d, c, d);
939                 BN_GF2m_mod(e, a, b[j]);
940                 BN_GF2m_add(e, e, d);
941                 /*
942                  * Test that solution of quadratic c satisfies c^2 + c = a.
943                  */
944                 if (!TEST_BN_eq_zero(e))
945                     goto err;
946             }
947         }
948     }
949     if (!TEST_int_ge(s, 0)) {
950         TEST_info("%d tests found no roots; probably an error", NUM0);
951         goto err;
952     }
953     st = 1;
954  err:
955     BN_free(a);
956     BN_free(b[0]);
957     BN_free(b[1]);
958     BN_free(c);
959     BN_free(d);
960     BN_free(e);
961     return st;
962 }
963 #endif
964
965 static int test_kronecker(void)
966 {
967     BIGNUM *a = NULL, *b = NULL, *r = NULL, *t = NULL;
968     int i, legendre, kronecker, st = 0;
969
970     if (!TEST_ptr(a = BN_new())
971             || !TEST_ptr(b = BN_new())
972             || !TEST_ptr(r = BN_new())
973             || !TEST_ptr(t = BN_new()))
974         goto err;
975
976     /*
977      * We test BN_kronecker(a, b, ctx) just for b odd (Jacobi symbol). In
978      * this case we know that if b is prime, then BN_kronecker(a, b, ctx) is
979      * congruent to $a^{(b-1)/2}$, modulo $b$ (Legendre symbol). So we
980      * generate a random prime b and compare these values for a number of
981      * random a's.  (That is, we run the Solovay-Strassen primality test to
982      * confirm that b is prime, except that we don't want to test whether b
983      * is prime but whether BN_kronecker works.)
984      */
985
986     if (!TEST_true(BN_generate_prime_ex(b, 512, 0, NULL, NULL, NULL)))
987         goto err;
988     BN_set_negative(b, rand_neg());
989
990     for (i = 0; i < NUM0; i++) {
991         if (!TEST_true(BN_bntest_rand(a, 512, 0, 0)))
992             goto err;
993         BN_set_negative(a, rand_neg());
994
995         /* t := (|b|-1)/2  (note that b is odd) */
996         if (!TEST_true(BN_copy(t, b)))
997             goto err;
998         BN_set_negative(t, 0);
999         if (!TEST_true(BN_sub_word(t, 1)))
1000             goto err;
1001         if (!TEST_true(BN_rshift1(t, t)))
1002             goto err;
1003         /* r := a^t mod b */
1004         BN_set_negative(b, 0);
1005
1006         if (!TEST_true(BN_mod_exp_recp(r, a, t, b, ctx)))
1007             goto err;
1008         BN_set_negative(b, 1);
1009
1010         if (BN_is_word(r, 1))
1011             legendre = 1;
1012         else if (BN_is_zero(r))
1013             legendre = 0;
1014         else {
1015             if (!TEST_true(BN_add_word(r, 1)))
1016                 goto err;
1017             if (!TEST_int_eq(BN_ucmp(r, b), 0)) {
1018                 TEST_info("Legendre symbol computation failed");
1019                 goto err;
1020             }
1021             legendre = -1;
1022         }
1023
1024         if (!TEST_int_ge(kronecker = BN_kronecker(a, b, ctx), -1))
1025             goto err;
1026         /* we actually need BN_kronecker(a, |b|) */
1027         if (BN_is_negative(a) && BN_is_negative(b))
1028             kronecker = -kronecker;
1029
1030         if (!TEST_int_eq(legendre, kronecker))
1031             goto err;
1032     }
1033
1034     st = 1;
1035  err:
1036     BN_free(a);
1037     BN_free(b);
1038     BN_free(r);
1039     BN_free(t);
1040     return st;
1041 }
1042
1043 static int file_sum(STANZA *s)
1044 {
1045     BIGNUM *a = NULL, *b = NULL, *sum = NULL, *ret = NULL;
1046     BN_ULONG b_word;
1047     int st = 0;
1048
1049     if (!TEST_ptr(a = getBN(s, "A"))
1050             || !TEST_ptr(b = getBN(s, "B"))
1051             || !TEST_ptr(sum = getBN(s, "Sum"))
1052             || !TEST_ptr(ret = BN_new()))
1053         goto err;
1054
1055     if (!TEST_true(BN_add(ret, a, b))
1056             || !equalBN("A + B", sum, ret)
1057             || !TEST_true(BN_sub(ret, sum, a))
1058             || !equalBN("Sum - A", b, ret)
1059             || !TEST_true(BN_sub(ret, sum, b))
1060             || !equalBN("Sum - B", a, ret))
1061         goto err;
1062
1063     /*
1064      * Test that the functions work when |r| and |a| point to the same BIGNUM,
1065      * or when |r| and |b| point to the same BIGNUM.
1066      * TODO: Test where all of |r|, |a|, and |b| point to the same BIGNUM.
1067      */
1068     if (!TEST_true(BN_copy(ret, a))
1069             || !TEST_true(BN_add(ret, ret, b))
1070             || !equalBN("A + B (r is a)", sum, ret)
1071             || !TEST_true(BN_copy(ret, b))
1072             || !TEST_true(BN_add(ret, a, ret))
1073             || !equalBN("A + B (r is b)", sum, ret)
1074             || !TEST_true(BN_copy(ret, sum))
1075             || !TEST_true(BN_sub(ret, ret, a))
1076             || !equalBN("Sum - A (r is a)", b, ret)
1077             || !TEST_true(BN_copy(ret, a))
1078             || !TEST_true(BN_sub(ret, sum, ret))
1079             || !equalBN("Sum - A (r is b)", b, ret)
1080             || !TEST_true(BN_copy(ret, sum))
1081             || !TEST_true(BN_sub(ret, ret, b))
1082             || !equalBN("Sum - B (r is a)", a, ret)
1083             || !TEST_true(BN_copy(ret, b))
1084             || !TEST_true(BN_sub(ret, sum, ret))
1085             || !equalBN("Sum - B (r is b)", a, ret))
1086         goto err;
1087
1088     /*
1089      * Test BN_uadd() and BN_usub() with the prerequisites they are
1090      * documented as having. Note that these functions are frequently used
1091      * when the prerequisites don't hold. In those cases, they are supposed
1092      * to work as if the prerequisite hold, but we don't test that yet.
1093      * TODO: test that.
1094      */
1095     if (!BN_is_negative(a) && !BN_is_negative(b) && BN_cmp(a, b) >= 0) {
1096         if (!TEST_true(BN_uadd(ret, a, b))
1097                 || !equalBN("A +u B", sum, ret)
1098                 || !TEST_true(BN_usub(ret, sum, a))
1099                 || !equalBN("Sum -u A", b, ret)
1100                 || !TEST_true(BN_usub(ret, sum, b))
1101                 || !equalBN("Sum -u B", a, ret))
1102             goto err;
1103         /*
1104          * Test that the functions work when |r| and |a| point to the same
1105          * BIGNUM, or when |r| and |b| point to the same BIGNUM.
1106          * TODO: Test where all of |r|, |a|, and |b| point to the same BIGNUM.
1107          */
1108         if (!TEST_true(BN_copy(ret, a))
1109                 || !TEST_true(BN_uadd(ret, ret, b))
1110                 || !equalBN("A +u B (r is a)", sum, ret)
1111                 || !TEST_true(BN_copy(ret, b))
1112                 || !TEST_true(BN_uadd(ret, a, ret))
1113                 || !equalBN("A +u B (r is b)", sum, ret)
1114                 || !TEST_true(BN_copy(ret, sum))
1115                 || !TEST_true(BN_usub(ret, ret, a))
1116                 || !equalBN("Sum -u A (r is a)", b, ret)
1117                 || !TEST_true(BN_copy(ret, a))
1118                 || !TEST_true(BN_usub(ret, sum, ret))
1119                 || !equalBN("Sum -u A (r is b)", b, ret)
1120                 || !TEST_true(BN_copy(ret, sum))
1121                 || !TEST_true(BN_usub(ret, ret, b))
1122                 || !equalBN("Sum -u B (r is a)", a, ret)
1123                 || !TEST_true(BN_copy(ret, b))
1124                 || !TEST_true(BN_usub(ret, sum, ret))
1125                 || !equalBN("Sum -u B (r is b)", a, ret))
1126             goto err;
1127     }
1128
1129     /*
1130      * Test with BN_add_word() and BN_sub_word() if |b| is small enough.
1131      */
1132     b_word = BN_get_word(b);
1133     if (!BN_is_negative(b) && b_word != (BN_ULONG)-1) {
1134         if (!TEST_true(BN_copy(ret, a))
1135                 || !TEST_true(BN_add_word(ret, b_word))
1136                 || !equalBN("A + B (word)", sum, ret)
1137                 || !TEST_true(BN_copy(ret, sum))
1138                 || !TEST_true(BN_sub_word(ret, b_word))
1139                 || !equalBN("Sum - B (word)", a, ret))
1140             goto err;
1141     }
1142     st = 1;
1143
1144 err:
1145     BN_free(a);
1146     BN_free(b);
1147     BN_free(sum);
1148     BN_free(ret);
1149     return st;
1150 }
1151
1152 static int file_lshift1(STANZA *s)
1153 {
1154     BIGNUM *a = NULL, *lshift1 = NULL, *zero = NULL, *ret = NULL;
1155     BIGNUM *two = NULL, *remainder = NULL;
1156     int st = 0;
1157
1158     if (!TEST_ptr(a = getBN(s, "A"))
1159             || !TEST_ptr(lshift1 = getBN(s, "LShift1"))
1160             || !TEST_ptr(zero = BN_new())
1161             || !TEST_ptr(ret = BN_new())
1162             || !TEST_ptr(two = BN_new())
1163             || !TEST_ptr(remainder = BN_new()))
1164         goto err;
1165
1166     BN_zero(zero);
1167
1168     if (!TEST_true(BN_set_word(two, 2))
1169             || !TEST_true(BN_add(ret, a, a))
1170             || !equalBN("A + A", lshift1, ret)
1171             || !TEST_true(BN_mul(ret, a, two, ctx))
1172             || !equalBN("A * 2", lshift1, ret)
1173             || !TEST_true(BN_div(ret, remainder, lshift1, two, ctx))
1174             || !equalBN("LShift1 / 2", a, ret)
1175             || !equalBN("LShift1 % 2", zero, remainder)
1176             || !TEST_true(BN_lshift1(ret, a))
1177             || !equalBN("A << 1", lshift1, ret)
1178             || !TEST_true(BN_rshift1(ret, lshift1))
1179             || !equalBN("LShift >> 1", a, ret)
1180             || !TEST_true(BN_rshift1(ret, lshift1))
1181             || !equalBN("LShift >> 1", a, ret))
1182         goto err;
1183
1184     /* Set the LSB to 1 and test rshift1 again. */
1185     if (!TEST_true(BN_set_bit(lshift1, 0))
1186             || !TEST_true(BN_div(ret, NULL /* rem */ , lshift1, two, ctx))
1187             || !equalBN("(LShift1 | 1) / 2", a, ret)
1188             || !TEST_true(BN_rshift1(ret, lshift1))
1189             || !equalBN("(LShift | 1) >> 1", a, ret))
1190         goto err;
1191
1192     st = 1;
1193 err:
1194     BN_free(a);
1195     BN_free(lshift1);
1196     BN_free(zero);
1197     BN_free(ret);
1198     BN_free(two);
1199     BN_free(remainder);
1200
1201     return st;
1202 }
1203
1204 static int file_lshift(STANZA *s)
1205 {
1206     BIGNUM *a = NULL, *lshift = NULL, *ret = NULL;
1207     int n = 0, st = 0;
1208
1209     if (!TEST_ptr(a = getBN(s, "A"))
1210             || !TEST_ptr(lshift = getBN(s, "LShift"))
1211             || !TEST_ptr(ret = BN_new())
1212             || !getint(s, &n, "N"))
1213         goto err;
1214
1215     if (!TEST_true(BN_lshift(ret, a, n))
1216             || !equalBN("A << N", lshift, ret)
1217             || !TEST_true(BN_rshift(ret, lshift, n))
1218             || !equalBN("A >> N", a, ret))
1219         goto err;
1220
1221     st = 1;
1222 err:
1223     BN_free(a);
1224     BN_free(lshift);
1225     BN_free(ret);
1226     return st;
1227 }
1228
1229 static int file_rshift(STANZA *s)
1230 {
1231     BIGNUM *a = NULL, *rshift = NULL, *ret = NULL;
1232     int n = 0, st = 0;
1233
1234     if (!TEST_ptr(a = getBN(s, "A"))
1235             || !TEST_ptr(rshift = getBN(s, "RShift"))
1236             || !TEST_ptr(ret = BN_new())
1237             || !getint(s, &n, "N"))
1238         goto err;
1239
1240     if (!TEST_true(BN_rshift(ret, a, n))
1241             || !equalBN("A >> N", rshift, ret))
1242         goto err;
1243
1244     /* If N == 1, try with rshift1 as well */
1245     if (n == 1) {
1246         if (!TEST_true(BN_rshift1(ret, a))
1247                 || !equalBN("A >> 1 (rshift1)", rshift, ret))
1248             goto err;
1249     }
1250     st = 1;
1251
1252 err:
1253     BN_free(a);
1254     BN_free(rshift);
1255     BN_free(ret);
1256     return st;
1257 }
1258
1259 static int file_square(STANZA *s)
1260 {
1261     BIGNUM *a = NULL, *square = NULL, *zero = NULL, *ret = NULL;
1262     BIGNUM *remainder = NULL, *tmp = NULL;
1263     int st = 0;
1264
1265     if (!TEST_ptr(a = getBN(s, "A"))
1266             || !TEST_ptr(square = getBN(s, "Square"))
1267             || !TEST_ptr(zero = BN_new())
1268             || !TEST_ptr(ret = BN_new())
1269             || !TEST_ptr(remainder = BN_new()))
1270         goto err;
1271
1272     BN_zero(zero);
1273     if (!TEST_true(BN_sqr(ret, a, ctx))
1274             || !equalBN("A^2", square, ret)
1275             || !TEST_true(BN_mul(ret, a, a, ctx))
1276             || !equalBN("A * A", square, ret)
1277             || !TEST_true(BN_div(ret, remainder, square, a, ctx))
1278             || !equalBN("Square / A", a, ret)
1279             || !equalBN("Square % A", zero, remainder))
1280         goto err;
1281
1282 #if HAVE_BN_SQRT
1283     BN_set_negative(a, 0);
1284     if (!TEST_true(BN_sqrt(ret, square, ctx))
1285             || !equalBN("sqrt(Square)", a, ret))
1286         goto err;
1287
1288     /* BN_sqrt should fail on non-squares and negative numbers. */
1289     if (!TEST_BN_eq_zero(square)) {
1290         if (!TEST_ptr(tmp = BN_new())
1291                 || !TEST_true(BN_copy(tmp, square)))
1292             goto err;
1293         BN_set_negative(tmp, 1);
1294
1295         if (!TEST_int_eq(BN_sqrt(ret, tmp, ctx), 0))
1296             goto err;
1297         ERR_clear_error();
1298
1299         BN_set_negative(tmp, 0);
1300         if (BN_add(tmp, tmp, BN_value_one()))
1301             goto err;
1302         if (!TEST_int_eq(BN_sqrt(ret, tmp, ctx)))
1303             goto err;
1304         ERR_clear_error();
1305     }
1306 #endif
1307
1308     st = 1;
1309 err:
1310     BN_free(a);
1311     BN_free(square);
1312     BN_free(zero);
1313     BN_free(ret);
1314     BN_free(remainder);
1315     BN_free(tmp);
1316     return st;
1317 }
1318
1319 static int file_product(STANZA *s)
1320 {
1321     BIGNUM *a = NULL, *b = NULL, *product = NULL, *ret = NULL;
1322     BIGNUM *remainder = NULL, *zero = NULL;
1323     int st = 0;
1324
1325     if (!TEST_ptr(a = getBN(s, "A"))
1326             || !TEST_ptr(b = getBN(s, "B"))
1327             || !TEST_ptr(product = getBN(s, "Product"))
1328             || !TEST_ptr(ret = BN_new())
1329             || !TEST_ptr(remainder = BN_new())
1330             || !TEST_ptr(zero = BN_new()))
1331         goto err;
1332
1333     BN_zero(zero);
1334
1335     if (!TEST_true(BN_mul(ret, a, b, ctx))
1336             || !equalBN("A * B", product, ret)
1337             || !TEST_true(BN_div(ret, remainder, product, a, ctx))
1338             || !equalBN("Product / A", b, ret)
1339             || !equalBN("Product % A", zero, remainder)
1340             || !TEST_true(BN_div(ret, remainder, product, b, ctx))
1341             || !equalBN("Product / B", a, ret)
1342             || !equalBN("Product % B", zero, remainder))
1343         goto err;
1344
1345     st = 1;
1346 err:
1347     BN_free(a);
1348     BN_free(b);
1349     BN_free(product);
1350     BN_free(ret);
1351     BN_free(remainder);
1352     BN_free(zero);
1353     return st;
1354 }
1355
1356 static int file_quotient(STANZA *s)
1357 {
1358     BIGNUM *a = NULL, *b = NULL, *quotient = NULL, *remainder = NULL;
1359     BIGNUM *ret = NULL, *ret2 = NULL, *nnmod = NULL;
1360     BN_ULONG b_word, ret_word;
1361     int st = 0;
1362
1363     if (!TEST_ptr(a = getBN(s, "A"))
1364             || !TEST_ptr(b = getBN(s, "B"))
1365             || !TEST_ptr(quotient = getBN(s, "Quotient"))
1366             || !TEST_ptr(remainder = getBN(s, "Remainder"))
1367             || !TEST_ptr(ret = BN_new())
1368             || !TEST_ptr(ret2 = BN_new())
1369             || !TEST_ptr(nnmod = BN_new()))
1370         goto err;
1371
1372     if (!TEST_true(BN_div(ret, ret2, a, b, ctx))
1373             || !equalBN("A / B", quotient, ret)
1374             || !equalBN("A % B", remainder, ret2)
1375             || !TEST_true(BN_mul(ret, quotient, b, ctx))
1376             || !TEST_true(BN_add(ret, ret, remainder))
1377             || !equalBN("Quotient * B + Remainder", a, ret))
1378         goto err;
1379
1380     /*
1381      * Test with BN_mod_word() and BN_div_word() if the divisor is
1382      * small enough.
1383      */
1384     b_word = BN_get_word(b);
1385     if (!BN_is_negative(b) && b_word != (BN_ULONG)-1) {
1386         BN_ULONG remainder_word = BN_get_word(remainder);
1387
1388         assert(remainder_word != (BN_ULONG)-1);
1389         if (!TEST_ptr(BN_copy(ret, a)))
1390             goto err;
1391         ret_word = BN_div_word(ret, b_word);
1392         if (ret_word != remainder_word) {
1393 #ifdef BN_DEC_FMT1
1394             TEST_error(
1395                     "Got A %% B (word) = " BN_DEC_FMT1 ", wanted " BN_DEC_FMT1,
1396                     ret_word, remainder_word);
1397 #else
1398             TEST_error("Got A %% B (word) mismatch");
1399 #endif
1400             goto err;
1401         }
1402         if (!equalBN ("A / B (word)", quotient, ret))
1403             goto err;
1404
1405         ret_word = BN_mod_word(a, b_word);
1406         if (ret_word != remainder_word) {
1407 #ifdef BN_DEC_FMT1
1408             TEST_error(
1409                     "Got A %% B (word) = " BN_DEC_FMT1 ", wanted " BN_DEC_FMT1 "",
1410                     ret_word, remainder_word);
1411 #else
1412             TEST_error("Got A %% B (word) mismatch");
1413 #endif
1414             goto err;
1415         }
1416     }
1417
1418     /* Test BN_nnmod. */
1419     if (!BN_is_negative(b)) {
1420         if (!TEST_true(BN_copy(nnmod, remainder))
1421                 || (BN_is_negative(nnmod)
1422                         && !TEST_true(BN_add(nnmod, nnmod, b)))
1423                 || !TEST_true(BN_nnmod(ret, a, b, ctx))
1424                 || !equalBN("A % B (non-negative)", nnmod, ret))
1425             goto err;
1426     }
1427
1428     st = 1;
1429 err:
1430     BN_free(a);
1431     BN_free(b);
1432     BN_free(quotient);
1433     BN_free(remainder);
1434     BN_free(ret);
1435     BN_free(ret2);
1436     BN_free(nnmod);
1437     return st;
1438 }
1439
1440 static int file_modmul(STANZA *s)
1441 {
1442     BIGNUM *a = NULL, *b = NULL, *m = NULL, *mod_mul = NULL, *ret = NULL;
1443     int st = 0;
1444
1445     if (!TEST_ptr(a = getBN(s, "A"))
1446             || !TEST_ptr(b = getBN(s, "B"))
1447             || !TEST_ptr(m = getBN(s, "M"))
1448             || !TEST_ptr(mod_mul = getBN(s, "ModMul"))
1449             || !TEST_ptr(ret = BN_new()))
1450         goto err;
1451
1452     if (!TEST_true(BN_mod_mul(ret, a, b, m, ctx))
1453             || !equalBN("A * B (mod M)", mod_mul, ret))
1454         goto err;
1455
1456     if (BN_is_odd(m)) {
1457         /* Reduce |a| and |b| and test the Montgomery version. */
1458         BN_MONT_CTX *mont = BN_MONT_CTX_new();
1459         BIGNUM *a_tmp = BN_new();
1460         BIGNUM *b_tmp = BN_new();
1461
1462         if (mont == NULL || a_tmp == NULL || b_tmp == NULL
1463                 || !TEST_true(BN_MONT_CTX_set(mont, m, ctx))
1464                 || !TEST_true(BN_nnmod(a_tmp, a, m, ctx))
1465                 || !TEST_true(BN_nnmod(b_tmp, b, m, ctx))
1466                 || !TEST_true(BN_to_montgomery(a_tmp, a_tmp, mont, ctx))
1467                 || !TEST_true(BN_to_montgomery(b_tmp, b_tmp, mont, ctx))
1468                 || !TEST_true(BN_mod_mul_montgomery(ret, a_tmp, b_tmp,
1469                                                     mont, ctx))
1470                 || !TEST_true(BN_from_montgomery(ret, ret, mont, ctx))
1471                 || !equalBN("A * B (mod M) (mont)", mod_mul, ret))
1472             st = 0;
1473         else
1474             st = 1;
1475         BN_MONT_CTX_free(mont);
1476         BN_free(a_tmp);
1477         BN_free(b_tmp);
1478         if (st == 0)
1479             goto err;
1480     }
1481
1482     st = 1;
1483 err:
1484     BN_free(a);
1485     BN_free(b);
1486     BN_free(m);
1487     BN_free(mod_mul);
1488     BN_free(ret);
1489     return st;
1490 }
1491
1492 static int file_modexp(STANZA *s)
1493 {
1494     BIGNUM *a = NULL, *e = NULL, *m = NULL, *mod_exp = NULL, *ret = NULL;
1495     BIGNUM *b = NULL, *c = NULL, *d = NULL;
1496     int st = 0;
1497
1498     if (!TEST_ptr(a = getBN(s, "A"))
1499             || !TEST_ptr(e = getBN(s, "E"))
1500             || !TEST_ptr(m = getBN(s, "M"))
1501             || !TEST_ptr(mod_exp = getBN(s, "ModExp"))
1502             || !TEST_ptr(ret = BN_new())
1503             || !TEST_ptr(d = BN_new()))
1504         goto err;
1505
1506     if (!TEST_true(BN_mod_exp(ret, a, e, m, ctx))
1507             || !equalBN("A ^ E (mod M)", mod_exp, ret))
1508         goto err;
1509
1510     if (BN_is_odd(m)) {
1511         if (!TEST_true(BN_mod_exp_mont(ret, a, e, m, ctx, NULL))
1512                 || !equalBN("A ^ E (mod M) (mont)", mod_exp, ret)
1513                 || !TEST_true(BN_mod_exp_mont_consttime(ret, a, e, m,
1514                                                         ctx, NULL))
1515                 || !equalBN("A ^ E (mod M) (mont const", mod_exp, ret))
1516             goto err;
1517     }
1518
1519     /* Regression test for carry propagation bug in sqr8x_reduction */
1520     BN_hex2bn(&a, "050505050505");
1521     BN_hex2bn(&b, "02");
1522     BN_hex2bn(&c,
1523         "4141414141414141414141274141414141414141414141414141414141414141"
1524         "4141414141414141414141414141414141414141414141414141414141414141"
1525         "4141414141414141414141800000000000000000000000000000000000000000"
1526         "0000000000000000000000000000000000000000000000000000000000000000"
1527         "0000000000000000000000000000000000000000000000000000000000000000"
1528         "0000000000000000000000000000000000000000000000000000000001");
1529     if (!TEST_true(BN_mod_exp(d, a, b, c, ctx))
1530         || !TEST_true(BN_mul(e, a, a, ctx))
1531         || !TEST_BN_eq(d, e))
1532         goto err;
1533
1534     st = 1;
1535 err:
1536     BN_free(a);
1537     BN_free(b);
1538     BN_free(c);
1539     BN_free(d);
1540     BN_free(e);
1541     BN_free(m);
1542     BN_free(mod_exp);
1543     BN_free(ret);
1544     return st;
1545 }
1546
1547 static int file_exp(STANZA *s)
1548 {
1549     BIGNUM *a = NULL, *e = NULL, *exp = NULL, *ret = NULL;
1550     int st = 0;
1551
1552     if (!TEST_ptr(a = getBN(s, "A"))
1553             || !TEST_ptr(e = getBN(s, "E"))
1554             || !TEST_ptr(exp = getBN(s, "Exp"))
1555             || !TEST_ptr(ret = BN_new()))
1556         goto err;
1557
1558     if (!TEST_true(BN_exp(ret, a, e, ctx))
1559             || !equalBN("A ^ E", exp, ret))
1560         goto err;
1561
1562     st = 1;
1563 err:
1564     BN_free(a);
1565     BN_free(e);
1566     BN_free(exp);
1567     BN_free(ret);
1568     return st;
1569 }
1570
1571 static int file_modsqrt(STANZA *s)
1572 {
1573     BIGNUM *a = NULL, *p = NULL, *mod_sqrt = NULL, *ret = NULL, *ret2 = NULL;
1574     int st = 0;
1575
1576     if (!TEST_ptr(a = getBN(s, "A"))
1577             || !TEST_ptr(p = getBN(s, "P"))
1578             || !TEST_ptr(mod_sqrt = getBN(s, "ModSqrt"))
1579             || !TEST_ptr(ret = BN_new())
1580             || !TEST_ptr(ret2 = BN_new()))
1581         goto err;
1582
1583     /* There are two possible answers. */
1584     if (!TEST_true(BN_mod_sqrt(ret, a, p, ctx))
1585             || !TEST_true(BN_sub(ret2, p, ret)))
1586         goto err;
1587
1588     /* The first condition should NOT be a test. */
1589     if (BN_cmp(ret2, mod_sqrt) != 0
1590             && !equalBN("sqrt(A) (mod P)", mod_sqrt, ret))
1591         goto err;
1592
1593     st = 1;
1594 err:
1595     BN_free(a);
1596     BN_free(p);
1597     BN_free(mod_sqrt);
1598     BN_free(ret);
1599     BN_free(ret2);
1600     return st;
1601 }
1602
1603 static int test_bn2padded(void)
1604 {
1605 #if HAVE_BN_PADDED
1606     uint8_t zeros[256], out[256], reference[128];
1607     BIGNUM *n = BN_new();
1608     int st = 0;
1609
1610     /* Test edge case at 0. */
1611     if (n == NULL)
1612         goto err;
1613     if (!TEST_true(BN_bn2bin_padded(NULL, 0, n)))
1614         goto err;
1615     memset(out, -1, sizeof(out));
1616     if (!TEST_true(BN_bn2bin_padded(out, sizeof(out)), n))
1617         goto err;
1618     memset(zeros, 0, sizeof(zeros));
1619     if (!TEST_mem_eq(zeros, sizeof(zeros), out, sizeof(out)))
1620         goto err;
1621
1622     /* Test a random numbers at various byte lengths. */
1623     for (size_t bytes = 128 - 7; bytes <= 128; bytes++) {
1624 #define TOP_BIT_ON 0
1625 #define BOTTOM_BIT_NOTOUCH 0
1626         if (!TEST_true(BN_rand(n, bytes * 8, TOP_BIT_ON, BOTTOM_BIT_NOTOUCH)))
1627             goto err;
1628         if (!TEST_int_eq(BN_num_bytes(n),A) bytes
1629                 || TEST_int_eq(BN_bn2bin(n, reference), bytes))
1630             goto err;
1631         /* Empty buffer should fail. */
1632         if (!TEST_int_eq(BN_bn2bin_padded(NULL, 0, n)), 0)
1633             goto err;
1634         /* One byte short should fail. */
1635         if (BN_bn2bin_padded(out, bytes - 1, n))
1636             goto err;
1637         /* Exactly right size should encode. */
1638         if (!TEST_true(BN_bn2bin_padded(out, bytes, n))
1639                 || TEST_mem_eq(out, bytes, reference, bytes))
1640             goto err;
1641         /* Pad up one byte extra. */
1642         if (!TEST_true(BN_bn2bin_padded(out, bytes + 1, n))
1643                 || !TEST_mem_eq(out + 1, bytes, reference, bytes)
1644                 || !TEST_mem_eq(out, 1, zeros, 1))
1645             goto err;
1646         /* Pad up to 256. */
1647         if (!TEST_true(BN_bn2bin_padded(out, sizeof(out)), n)
1648                 || !TEST_mem_eq(out + sizeof(out) - bytes, bytes,
1649                                 reference, bytes)
1650                 || !TEST_mem_eq(out, sizseof(out) - bytes,
1651                                 zeros, sizeof(out) - bytes))
1652             goto err;
1653     }
1654
1655     st = 1;
1656 err:
1657     BN_free(n);
1658     return st;
1659 #else
1660     return ctx != NULL;
1661 #endif
1662 }
1663
1664 static int test_dec2bn(void)
1665 {
1666     BIGNUM *bn = NULL;
1667     int st = 0;
1668
1669     if (!TEST_int_eq(parsedecBN(&bn, "0"), 1)
1670             || !TEST_BN_eq_word(bn, 0)
1671             || !TEST_BN_eq_zero(bn)
1672             || !TEST_BN_le_zero(bn)
1673             || !TEST_BN_ge_zero(bn)
1674             || !TEST_BN_even(bn))
1675         goto err;
1676     BN_free(bn);
1677     bn = NULL;
1678
1679     if (!TEST_int_eq(parsedecBN(&bn, "256"), 3)
1680             || !TEST_BN_eq_word(bn, 256)
1681             || !TEST_BN_ge_zero(bn)
1682             || !TEST_BN_gt_zero(bn)
1683             || !TEST_BN_ne_zero(bn)
1684             || !TEST_BN_even(bn))
1685         goto err;
1686     BN_free(bn);
1687     bn = NULL;
1688
1689     if (!TEST_int_eq(parsedecBN(&bn, "-42"), 3)
1690             || !TEST_BN_abs_eq_word(bn, 42)
1691             || !TEST_BN_lt_zero(bn)
1692             || !TEST_BN_le_zero(bn)
1693             || !TEST_BN_ne_zero(bn)
1694             || !TEST_BN_even(bn))
1695         goto err;
1696     BN_free(bn);
1697     bn = NULL;
1698
1699     if (!TEST_int_eq(parsedecBN(&bn, "1"), 1)
1700             || !TEST_BN_eq_word(bn, 1)
1701             || !TEST_BN_ne_zero(bn)
1702             || !TEST_BN_gt_zero(bn)
1703             || !TEST_BN_ge_zero(bn)
1704             || !TEST_BN_eq_one(bn)
1705             || !TEST_BN_odd(bn))
1706         goto err;
1707     BN_free(bn);
1708     bn = NULL;
1709
1710     if (!TEST_int_eq(parsedecBN(&bn, "-0"), 2)
1711             || !TEST_BN_eq_zero(bn)
1712             || !TEST_BN_ge_zero(bn)
1713             || !TEST_BN_le_zero(bn)
1714             || !TEST_BN_even(bn))
1715         goto err;
1716     BN_free(bn);
1717     bn = NULL;
1718
1719     if (!TEST_int_eq(parsedecBN(&bn, "42trailing garbage is ignored"), 2)
1720             || !TEST_BN_abs_eq_word(bn, 42)
1721             || !TEST_BN_ge_zero(bn)
1722             || !TEST_BN_gt_zero(bn)
1723             || !TEST_BN_ne_zero(bn)
1724             || !TEST_BN_even(bn))
1725         goto err;
1726
1727     st = 1;
1728 err:
1729     BN_free(bn);
1730     return st;
1731 }
1732
1733 static int test_hex2bn(void)
1734 {
1735     BIGNUM *bn = NULL;
1736     int st = 0;
1737
1738     if (!TEST_int_eq(parseBN(&bn, "0"), 1)
1739             || !TEST_BN_eq_zero(bn)
1740             || !TEST_BN_ge_zero(bn)
1741             || !TEST_BN_even(bn))
1742         goto err;
1743     BN_free(bn);
1744     bn = NULL;
1745
1746     if (!TEST_int_eq(parseBN(&bn, "256"), 3)
1747             || !TEST_BN_eq_word(bn, 0x256)
1748             || !TEST_BN_ge_zero(bn)
1749             || !TEST_BN_gt_zero(bn)
1750             || !TEST_BN_ne_zero(bn)
1751             || !TEST_BN_even(bn))
1752         goto err;
1753     BN_free(bn);
1754     bn = NULL;
1755
1756     if (!TEST_int_eq(parseBN(&bn, "-42"), 3)
1757             || !TEST_BN_abs_eq_word(bn, 0x42)
1758             || !TEST_BN_lt_zero(bn)
1759             || !TEST_BN_le_zero(bn)
1760             || !TEST_BN_ne_zero(bn)
1761             || !TEST_BN_even(bn))
1762         goto err;
1763     BN_free(bn);
1764     bn = NULL;
1765
1766     if (!TEST_int_eq(parseBN(&bn, "cb"), 2)
1767             || !TEST_BN_eq_word(bn, 0xCB)
1768             || !TEST_BN_ge_zero(bn)
1769             || !TEST_BN_gt_zero(bn)
1770             || !TEST_BN_ne_zero(bn)
1771             || !TEST_BN_odd(bn))
1772         goto err;
1773     BN_free(bn);
1774     bn = NULL;
1775
1776     if (!TEST_int_eq(parseBN(&bn, "-0"), 2)
1777             || !TEST_BN_eq_zero(bn)
1778             || !TEST_BN_ge_zero(bn)
1779             || !TEST_BN_le_zero(bn)
1780             || !TEST_BN_even(bn))
1781         goto err;
1782     BN_free(bn);
1783     bn = NULL;
1784
1785     if (!TEST_int_eq(parseBN(&bn, "abctrailing garbage is ignored"), 3)
1786             || !TEST_BN_eq_word(bn, 0xabc)
1787             || !TEST_BN_ge_zero(bn)
1788             || !TEST_BN_gt_zero(bn)
1789             || !TEST_BN_ne_zero(bn)
1790             || !TEST_BN_even(bn))
1791         goto err;
1792     st = 1;
1793
1794 err:
1795     BN_free(bn);
1796     return st;
1797 }
1798
1799 static int test_asc2bn(void)
1800 {
1801     BIGNUM *bn = NULL;
1802     int st = 0;
1803
1804     if (!TEST_ptr(bn = BN_new()))
1805         goto err;
1806
1807     if (!TEST_true(BN_asc2bn(&bn, "0"))
1808             || !TEST_BN_eq_zero(bn)
1809             || !TEST_BN_ge_zero(bn))
1810         goto err;
1811
1812     if (!TEST_true(BN_asc2bn(&bn, "256"))
1813             || !TEST_BN_eq_word(bn, 256)
1814             || !TEST_BN_ge_zero(bn))
1815         goto err;
1816
1817     if (!TEST_true(BN_asc2bn(&bn, "-42"))
1818             || !TEST_BN_abs_eq_word(bn, 42)
1819             || !TEST_BN_lt_zero(bn))
1820         goto err;
1821
1822     if (!TEST_true(BN_asc2bn(&bn, "0x1234"))
1823             || !TEST_BN_eq_word(bn, 0x1234)
1824             || !TEST_BN_ge_zero(bn))
1825         goto err;
1826
1827     if (!TEST_true(BN_asc2bn(&bn, "0X1234"))
1828             || !TEST_BN_eq_word(bn, 0x1234)
1829             || !TEST_BN_ge_zero(bn))
1830         goto err;
1831
1832     if (!TEST_true(BN_asc2bn(&bn, "-0xabcd"))
1833             || !TEST_BN_abs_eq_word(bn, 0xabcd)
1834             || !TEST_BN_lt_zero(bn))
1835         goto err;
1836
1837     if (!TEST_true(BN_asc2bn(&bn, "-0"))
1838             || !TEST_BN_eq_zero(bn)
1839             || !TEST_BN_ge_zero(bn))
1840         goto err;
1841
1842     if (!TEST_true(BN_asc2bn(&bn, "123trailing garbage is ignored"))
1843             || !TEST_BN_eq_word(bn, 123)
1844             || !TEST_BN_ge_zero(bn))
1845         goto err;
1846
1847     st = 1;
1848 err:
1849     BN_free(bn);
1850     return st;
1851 }
1852
1853 static const MPITEST kMPITests[] = {
1854     {"0", "\x00\x00\x00\x00", 4},
1855     {"1", "\x00\x00\x00\x01\x01", 5},
1856     {"-1", "\x00\x00\x00\x01\x81", 5},
1857     {"128", "\x00\x00\x00\x02\x00\x80", 6},
1858     {"256", "\x00\x00\x00\x02\x01\x00", 6},
1859     {"-256", "\x00\x00\x00\x02\x81\x00", 6},
1860 };
1861
1862 static int test_mpi(int i)
1863 {
1864     uint8_t scratch[8];
1865     const MPITEST *test = &kMPITests[i];
1866     size_t mpi_len, mpi_len2;
1867     BIGNUM *bn = NULL;
1868     BIGNUM *bn2 = NULL;
1869     int st = 0;
1870
1871     if (!TEST_ptr(bn = BN_new())
1872             || !TEST_true(BN_asc2bn(&bn, test->base10)))
1873         goto err;
1874     mpi_len = BN_bn2mpi(bn, NULL);
1875     if (!TEST_size_t_le(mpi_len, sizeof(scratch)))
1876         goto err;
1877
1878     if (!TEST_size_t_eq(mpi_len2 = BN_bn2mpi(bn, scratch), mpi_len)
1879             || !TEST_mem_eq(test->mpi, test->mpi_len, scratch, mpi_len))
1880         goto err;
1881
1882     if (!TEST_ptr(bn2 = BN_mpi2bn(scratch, mpi_len, NULL)))
1883         goto err;
1884
1885     if (!TEST_BN_eq(bn, bn2)) {
1886         BN_free(bn2);
1887         goto err;
1888     }
1889     BN_free(bn2);
1890
1891     st = 1;
1892 err:
1893     BN_free(bn);
1894     return st;
1895 }
1896
1897 static int test_rand(void)
1898 {
1899     BIGNUM *bn = NULL;
1900     int st = 0;
1901
1902     if (!TEST_ptr(bn = BN_new()))
1903         return 0;
1904
1905     /* Test BN_rand for degenerate cases with |top| and |bottom| parameters. */
1906     if (!TEST_false(BN_rand(bn, 0, 0 /* top */ , 0 /* bottom */ ))
1907             || !TEST_false(BN_rand(bn, 0, 1 /* top */ , 1 /* bottom */ ))
1908             || !TEST_true(BN_rand(bn, 1, 0 /* top */ , 0 /* bottom */ ))
1909             || !TEST_BN_eq_one(bn)
1910             || !TEST_false(BN_rand(bn, 1, 1 /* top */ , 0 /* bottom */ ))
1911             || !TEST_true(BN_rand(bn, 1, -1 /* top */ , 1 /* bottom */ ))
1912             || !TEST_BN_eq_one(bn)
1913             || !TEST_true(BN_rand(bn, 2, 1 /* top */ , 0 /* bottom */ ))
1914             || !TEST_BN_eq_word(bn, 3))
1915         goto err;
1916
1917     st = 1;
1918 err:
1919     BN_free(bn);
1920     return st;
1921 }
1922
1923 static int test_negzero(void)
1924 {
1925     BIGNUM *a = NULL, *b = NULL, *c = NULL, *d = NULL;
1926     BIGNUM *numerator = NULL, *denominator = NULL;
1927     int consttime, st = 0;
1928
1929     if (!TEST_ptr(a = BN_new())
1930             || !TEST_ptr(b = BN_new())
1931             || !TEST_ptr(c = BN_new())
1932             || !TEST_ptr(d = BN_new()))
1933         goto err;
1934
1935     /* Test that BN_mul never gives negative zero. */
1936     if (!TEST_true(BN_set_word(a, 1)))
1937         goto err;
1938     BN_set_negative(a, 1);
1939     BN_zero(b);
1940     if (!TEST_true(BN_mul(c, a, b, ctx)))
1941         goto err;
1942     if (!TEST_BN_eq_zero(c)
1943             || !TEST_BN_ge_zero(c))
1944         goto err;
1945
1946     for (consttime = 0; consttime < 2; consttime++) {
1947         if (!TEST_ptr(numerator = BN_new())
1948                 || !TEST_ptr(denominator = BN_new()))
1949             goto err;
1950         if (consttime) {
1951             BN_set_flags(numerator, BN_FLG_CONSTTIME);
1952             BN_set_flags(denominator, BN_FLG_CONSTTIME);
1953         }
1954         /* Test that BN_div never gives negative zero in the quotient. */
1955         if (!TEST_true(BN_set_word(numerator, 1))
1956                 || !TEST_true(BN_set_word(denominator, 2)))
1957             goto err;
1958         BN_set_negative(numerator, 1);
1959         if (!TEST_true(BN_div(a, b, numerator, denominator, ctx))
1960                 || !TEST_BN_eq_zero(a)
1961                 || !TEST_BN_ge_zero(a))
1962             goto err;
1963
1964         /* Test that BN_div never gives negative zero in the remainder. */
1965         if (!TEST_true(BN_set_word(denominator, 1))
1966                 || !TEST_true(BN_div(a, b, numerator, denominator, ctx))
1967                 || !TEST_BN_eq_zero(b)
1968                 || !TEST_BN_ge_zero(b))
1969             goto err;
1970         BN_free(numerator);
1971         BN_free(denominator);
1972         numerator = denominator = NULL;
1973     }
1974
1975     /* Test that BN_set_negative will not produce a negative zero. */
1976     BN_zero(a);
1977     BN_set_negative(a, 1);
1978     if (BN_is_negative(a))
1979         goto err;
1980     st = 1;
1981
1982 err:
1983     BN_free(a);
1984     BN_free(b);
1985     BN_free(c);
1986     BN_free(d);
1987     BN_free(numerator);
1988     BN_free(denominator);
1989     return st;
1990 }
1991
1992 static int test_badmod(void)
1993 {
1994     BIGNUM *a = NULL, *b = NULL, *zero = NULL;
1995     BN_MONT_CTX *mont = NULL;
1996     int st = 0;
1997
1998     if (!TEST_ptr(a = BN_new())
1999             || !TEST_ptr(b = BN_new())
2000             || !TEST_ptr(zero = BN_new())
2001             || !TEST_ptr(mont = BN_MONT_CTX_new()))
2002         goto err;
2003     BN_zero(zero);
2004
2005     if (!TEST_false(BN_div(a, b, BN_value_one(), zero, ctx)))
2006         goto err;
2007     ERR_clear_error();
2008
2009     if (!TEST_false(BN_mod_mul(a, BN_value_one(), BN_value_one(), zero, ctx)))
2010         goto err;
2011     ERR_clear_error();
2012
2013     if (!TEST_false(BN_mod_exp(a, BN_value_one(), BN_value_one(), zero, ctx)))
2014         goto err;
2015     ERR_clear_error();
2016
2017     if (!TEST_false(BN_mod_exp_mont(a, BN_value_one(), BN_value_one(),
2018                                     zero, ctx, NULL)))
2019         goto err;
2020     ERR_clear_error();
2021
2022     if (!TEST_false(BN_mod_exp_mont_consttime(a, BN_value_one(), BN_value_one(),
2023                                              zero, ctx, NULL)))
2024         goto err;
2025     ERR_clear_error();
2026
2027     if (!TEST_false(BN_MONT_CTX_set(mont, zero, ctx)))
2028         goto err;
2029     ERR_clear_error();
2030
2031     /* Some operations also may not be used with an even modulus. */
2032     if (!TEST_true(BN_set_word(b, 16)))
2033         goto err;
2034
2035     if (!TEST_false(BN_MONT_CTX_set(mont, b, ctx)))
2036         goto err;
2037     ERR_clear_error();
2038
2039     if (!TEST_false(BN_mod_exp_mont(a, BN_value_one(), BN_value_one(),
2040                                     b, ctx, NULL)))
2041         goto err;
2042     ERR_clear_error();
2043
2044     if (!TEST_false(BN_mod_exp_mont_consttime(a, BN_value_one(), BN_value_one(),
2045                                   b, ctx, NULL)))
2046         goto err;
2047     ERR_clear_error();
2048
2049     st = 1;
2050 err:
2051     BN_free(a);
2052     BN_free(b);
2053     BN_free(zero);
2054     BN_MONT_CTX_free(mont);
2055     return st;
2056 }
2057
2058 static int test_expmodzero(void)
2059 {
2060     BIGNUM *a = NULL, *r = NULL, *zero = NULL;
2061     int st = 0;
2062
2063     if (!TEST_ptr(zero = BN_new())
2064             || !TEST_ptr(a = BN_new())
2065             || !TEST_ptr(r = BN_new()))
2066         goto err;
2067     BN_zero(zero);
2068
2069     if (!TEST_true(BN_mod_exp(r, a, zero, BN_value_one(), NULL))
2070             || !TEST_BN_eq_zero(r)
2071             || !TEST_true(BN_mod_exp_mont(r, a, zero, BN_value_one(),
2072                                           NULL, NULL))
2073             || !TEST_BN_eq_zero(r)
2074             || !TEST_true(BN_mod_exp_mont_consttime(r, a, zero,
2075                                                     BN_value_one(),
2076                                                     NULL, NULL))
2077             || !TEST_BN_eq_zero(r)
2078             || !TEST_true(BN_mod_exp_mont_word(r, 42, zero,
2079                                                BN_value_one(), NULL, NULL))
2080             || !TEST_BN_eq_zero(r))
2081         goto err;
2082
2083     st = 1;
2084 err:
2085     BN_free(zero);
2086     BN_free(a);
2087     BN_free(r);
2088     return st;
2089 }
2090
2091 static int test_expmodone(void)
2092 {
2093     int ret = 0, i;
2094     BIGNUM *r = BN_new();
2095     BIGNUM *a = BN_new();
2096     BIGNUM *p = BN_new();
2097     BIGNUM *m = BN_new();
2098
2099     if (!TEST_ptr(r)
2100             || !TEST_ptr(a)
2101             || !TEST_ptr(p)
2102             || !TEST_ptr(p)
2103             || !TEST_ptr(m)
2104             || !TEST_true(BN_set_word(a, 1))
2105             || !TEST_true(BN_set_word(p, 0))
2106             || !TEST_true(BN_set_word(m, 1)))
2107         goto err;
2108
2109     /* Calculate r = 1 ^ 0 mod 1, and check the result is always 0 */
2110     for (i = 0; i < 2; i++) {
2111         if (!TEST_true(BN_mod_exp(r, a, p, m, NULL))
2112                 || !TEST_BN_eq_zero(r)
2113                 || !TEST_true(BN_mod_exp_mont(r, a, p, m, NULL, NULL))
2114                 || !TEST_BN_eq_zero(r)
2115                 || !TEST_true(BN_mod_exp_mont_consttime(r, a, p, m, NULL, NULL))
2116                 || !TEST_BN_eq_zero(r)
2117                 || !TEST_true(BN_mod_exp_mont_word(r, 1, p, m, NULL, NULL))
2118                 || !TEST_BN_eq_zero(r)
2119                 || !TEST_true(BN_mod_exp_simple(r, a, p, m, NULL))
2120                 || !TEST_BN_eq_zero(r)
2121                 || !TEST_true(BN_mod_exp_recp(r, a, p, m, NULL))
2122                 || !TEST_BN_eq_zero(r))
2123             goto err;
2124         /* Repeat for r = 1 ^ 0 mod -1 */
2125         if (i == 0)
2126             BN_set_negative(m, 1);
2127     }
2128
2129     ret = 1;
2130 err:
2131     BN_free(r);
2132     BN_free(a);
2133     BN_free(p);
2134     BN_free(m);
2135     return ret;
2136 }
2137
2138 static int test_smallprime(void)
2139 {
2140     static const int kBits = 10;
2141     BIGNUM *r;
2142     int st = 0;
2143
2144     if (!TEST_ptr(r = BN_new())
2145             || !TEST_true(BN_generate_prime_ex(r, (int)kBits, 0,
2146                                                NULL, NULL, NULL))
2147             || !TEST_int_eq(BN_num_bits(r), kBits))
2148         goto err;
2149
2150     st = 1;
2151 err:
2152     BN_free(r);
2153     return st;
2154 }
2155
2156 static int primes[] = { 2, 3, 5, 7, 17863 };
2157
2158 static int test_is_prime(int i)
2159 {
2160     int ret = 0;
2161     BIGNUM *r = NULL;
2162     int trial;
2163
2164     if (!TEST_ptr(r = BN_new()))
2165         goto err;
2166
2167     for (trial = 0; trial <= 1; ++trial) {
2168         if (!TEST_true(BN_set_word(r, primes[i]))
2169                 || !TEST_int_eq(BN_is_prime_fasttest_ex(r, 1, ctx, trial, NULL),
2170                                 1))
2171             goto err;
2172     }
2173
2174     ret = 1;
2175 err:
2176     BN_free(r);
2177     return ret;
2178 }
2179
2180 static int not_primes[] = { -1, 0, 1, 4 };
2181
2182 static int test_not_prime(int i)
2183 {
2184     int ret = 0;
2185     BIGNUM *r = NULL;
2186     int trial;
2187
2188     if (!TEST_ptr(r = BN_new()))
2189         goto err;
2190
2191     for (trial = 0; trial <= 1; ++trial) {
2192         if (!TEST_true(BN_set_word(r, not_primes[i]))
2193                 || !TEST_false(BN_is_prime_fasttest_ex(r, 1, ctx, trial, NULL)))
2194             goto err;
2195     }
2196
2197     ret = 1;
2198 err:
2199     BN_free(r);
2200     return ret;
2201 }
2202
2203 static int file_test_run(STANZA *s)
2204 {
2205     static const FILETEST filetests[] = {
2206         {"Sum", file_sum},
2207         {"LShift1", file_lshift1},
2208         {"LShift", file_lshift},
2209         {"RShift", file_rshift},
2210         {"Square", file_square},
2211         {"Product", file_product},
2212         {"Quotient", file_quotient},
2213         {"ModMul", file_modmul},
2214         {"ModExp", file_modexp},
2215         {"Exp", file_exp},
2216         {"ModSqrt", file_modsqrt},
2217     };
2218     int numtests = OSSL_NELEM(filetests);
2219     const FILETEST *tp = filetests;
2220
2221     for ( ; --numtests >= 0; tp++) {
2222         if (findattr(s, tp->name) != NULL) {
2223             if (!tp->func(s)) {
2224                 TEST_info("%s:%d: Failed %s test",
2225                           s->test_file, s->start, tp->name);
2226                 return 0;
2227             }
2228             return 1;
2229         }
2230     }
2231     TEST_info("%s:%d: Unknown test", s->test_file, s->start);
2232     return 0;
2233 }
2234
2235 static int run_file_tests(int i)
2236 {
2237     STANZA *s = NULL;
2238     char *testfile = test_get_argument(i);
2239     int c;
2240
2241     if (!TEST_ptr(s = OPENSSL_zalloc(sizeof(*s))))
2242         return 0;
2243     if (!test_start_file(s, testfile)) {
2244         OPENSSL_free(s);
2245         return 0;
2246     }
2247
2248     /* Read test file. */
2249     while (!BIO_eof(s->fp) && test_readstanza(s)) {
2250         if (s->numpairs == 0)
2251             continue;
2252         if (!file_test_run(s))
2253             s->errors++;
2254         s->numtests++;
2255         test_clearstanza(s);
2256     }
2257     test_end_file(s);
2258     c = s->errors;
2259     OPENSSL_free(s);
2260
2261     return c == 0;
2262 }
2263
2264 const OPTIONS *test_get_options(void)
2265 {
2266     enum { OPT_TEST_ENUM };
2267     static const OPTIONS test_options[] = {
2268         OPT_TEST_OPTIONS_WITH_EXTRA_USAGE("[file...]\n"),
2269         { OPT_HELP_STR, 1, '-',
2270           "file\tFile to run tests on. Normal tests are not run\n" },
2271         { NULL }
2272     };
2273     return test_options;
2274 }
2275
2276 int setup_tests(void)
2277 {
2278     int n = test_get_argument_count();
2279
2280     if (!TEST_ptr(ctx = BN_CTX_new()))
2281         return 0;
2282
2283     if (n == 0) {
2284         ADD_TEST(test_sub);
2285         ADD_TEST(test_div_recip);
2286         ADD_TEST(test_mod);
2287         ADD_TEST(test_modexp_mont5);
2288         ADD_TEST(test_kronecker);
2289         ADD_TEST(test_rand);
2290         ADD_TEST(test_bn2padded);
2291         ADD_TEST(test_dec2bn);
2292         ADD_TEST(test_hex2bn);
2293         ADD_TEST(test_asc2bn);
2294         ADD_ALL_TESTS(test_mpi, (int)OSSL_NELEM(kMPITests));
2295         ADD_TEST(test_negzero);
2296         ADD_TEST(test_badmod);
2297         ADD_TEST(test_expmodzero);
2298         ADD_TEST(test_expmodone);
2299         ADD_TEST(test_smallprime);
2300         ADD_TEST(test_swap);
2301 #ifndef OPENSSL_NO_EC2M
2302         ADD_TEST(test_gf2m_add);
2303         ADD_TEST(test_gf2m_mod);
2304         ADD_TEST(test_gf2m_mul);
2305         ADD_TEST(test_gf2m_sqr);
2306         ADD_TEST(test_gf2m_modinv);
2307         ADD_TEST(test_gf2m_moddiv);
2308         ADD_TEST(test_gf2m_modexp);
2309         ADD_TEST(test_gf2m_modsqrt);
2310         ADD_TEST(test_gf2m_modsolvequad);
2311 #endif
2312         ADD_ALL_TESTS(test_is_prime, (int)OSSL_NELEM(primes));
2313         ADD_ALL_TESTS(test_not_prime, (int)OSSL_NELEM(not_primes));
2314     } else {
2315         ADD_ALL_TESTS(run_file_tests, n);
2316     }
2317     return 1;
2318 }
2319
2320 void cleanup_tests(void)
2321 {
2322     BN_CTX_free(ctx);
2323 }