Providers: for the digest_final operation, pass a output buffer size
[openssl.git] / test / bn_internal_test.c
1 /*
2  * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the OpenSSL license (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9 #include <assert.h>
10 #include <errno.h>
11 #include <stdio.h>
12 #include <string.h>
13 #include <ctype.h>
14
15 #include <openssl/bn.h>
16 #include <openssl/crypto.h>
17 #include <openssl/err.h>
18 #include <openssl/rand.h>
19 #include "internal/nelem.h"
20 #include "internal/numbers.h"
21 #include "testutil.h"
22 #include "bn_prime.h"
23 #include "internal/bn_int.h"
24
25 static BN_CTX *ctx;
26
27 static int test_is_prime_enhanced(void)
28 {
29     int ret;
30     int status = 0;
31     BIGNUM *bn = NULL;
32
33     ret = TEST_ptr(bn = BN_new())
34           /* test passing a prime returns the correct status */
35           && TEST_true(BN_set_word(bn, 11))
36           /* return extra parameters related to composite */
37           && TEST_true(bn_miller_rabin_is_prime(bn, 10, ctx, NULL, 1, &status))
38           && TEST_int_eq(status, BN_PRIMETEST_PROBABLY_PRIME);
39     BN_free(bn);
40     return ret;
41 }
42
43 static int composites[] = {
44     9, 21, 77, 81, 265
45 };
46
47 static int test_is_composite_enhanced(int id)
48 {
49     int ret;
50     int status = 0;
51     BIGNUM *bn = NULL;
52
53     ret = TEST_ptr(bn = BN_new())
54           /* negative tests for different composite numbers */
55           && TEST_true(BN_set_word(bn, composites[id]))
56           && TEST_true(bn_miller_rabin_is_prime(bn, 10, ctx, NULL, 1, &status))
57           && TEST_int_ne(status, BN_PRIMETEST_PROBABLY_PRIME);
58
59     BN_free(bn);
60     return ret;
61 }
62
63 /* Test that multiplying all the small primes from 3 to 751 equals a constant.
64  * This test is mainly used to test that both 32 and 64 bit are correct.
65  */
66 static int test_bn_small_factors(void)
67 {
68     int ret = 0, i;
69     BIGNUM *b = NULL;
70
71     if (!(TEST_ptr(b = BN_new()) && TEST_true(BN_set_word(b, 3))))
72         goto err;
73
74     for (i = 1; i < NUMPRIMES; i++) {
75         prime_t p = primes[i];
76         if (p > 3 && p <= 751 && !BN_mul_word(b, p))
77             goto err;
78         if (p > 751)
79             break;
80     }
81     ret = TEST_BN_eq(bn_get0_small_factors(), b);
82 err:
83     BN_free(b);
84     return ret;
85 }
86
87 int setup_tests(void)
88 {
89     if (!TEST_ptr(ctx = BN_CTX_new()))
90         return 0;
91
92     ADD_TEST(test_is_prime_enhanced);
93     ADD_ALL_TESTS(test_is_composite_enhanced, (int)OSSL_NELEM(composites));
94     ADD_TEST(test_bn_small_factors);
95
96     return 1;
97 }
98
99 void cleanup_tests(void)
100 {
101     BN_CTX_free(ctx);
102 }
103