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