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