1 /* 2 * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved. 3 * 4 * Licensed under the Apache License 2.0 (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 "crypto/bn.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(ossl_bn_miller_rabin_is_prime(bn, 10, ctx, NULL, 1, 38 &status)) 39 && TEST_int_eq(status, BN_PRIMETEST_PROBABLY_PRIME); 40 BN_free(bn); 41 return ret; 42 } 43 44 static int composites[] = { 45 9, 21, 77, 81, 265 46 }; 47 48 static int test_is_composite_enhanced(int id) 49 { 50 int ret; 51 int status = 0; 52 BIGNUM *bn = NULL; 53 54 ret = TEST_ptr(bn = BN_new()) 55 /* negative tests for different composite numbers */ 56 && TEST_true(BN_set_word(bn, composites[id])) 57 && TEST_true(ossl_bn_miller_rabin_is_prime(bn, 10, ctx, NULL, 1, 58 &status)) 59 && TEST_int_ne(status, BN_PRIMETEST_PROBABLY_PRIME); 60 61 BN_free(bn); 62 return ret; 63 } 64 65 /* Test that multiplying all the small primes from 3 to 751 equals a constant. 66 * This test is mainly used to test that both 32 and 64 bit are correct. 67 */ 68 static int test_bn_small_factors(void) 69 { 70 int ret = 0, i; 71 BIGNUM *b = NULL; 72 73 if (!(TEST_ptr(b = BN_new()) && TEST_true(BN_set_word(b, 3)))) 74 goto err; 75 76 for (i = 1; i < NUMPRIMES; i++) { 77 prime_t p = primes[i]; 78 if (p > 3 && p <= 751 && !BN_mul_word(b, p)) 79 goto err; 80 if (p > 751) 81 break; 82 } 83 ret = TEST_BN_eq(ossl_bn_get0_small_factors(), b); 84 err: 85 BN_free(b); 86 return ret; 87 } 88 89 int setup_tests(void) 90 { 91 if (!TEST_ptr(ctx = BN_CTX_new())) 92 return 0; 93 94 ADD_TEST(test_is_prime_enhanced); 95 ADD_ALL_TESTS(test_is_composite_enhanced, (int)OSSL_NELEM(composites)); 96 ADD_TEST(test_bn_small_factors); 97 98 return 1; 99 } 100 101 void cleanup_tests(void) 102 { 103 BN_CTX_free(ctx); 104 } 105 106