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