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