xref: /netbsd-src/tests/crypto/libcrypto/bn/div/divtest.c (revision e1f413f949b9d2bf31beff6f35f2ea32286de027)
1 #include <openssl/bn.h>
2 #include <openssl/rand.h>
3 
Rand(void)4 static int Rand(void)
5 {
6     unsigned char x[2];
7     RAND_bytes(x, 2);
8     return (x[0] + 2 * x[1]);
9 }
10 
bug(const char * m,BIGNUM * a,BIGNUM * b)11 static void bug(const char *m, BIGNUM *a, BIGNUM *b)
12 {
13     printf("%s!\na=", m);
14     BN_print_fp(stdout, a);
15     printf("\nb=");
16     BN_print_fp(stdout, b);
17     printf("\n");
18     fflush(stdout);
19     exit(1);
20 }
21 
22 int
main(int argc,char * argv[])23 main(int argc, char *argv[])
24 {
25     BIGNUM *a = BN_new(), *b = BN_new(), *c = BN_new(), *d = BN_new(),
26         *C = BN_new(), *D = BN_new();
27     BN_RECP_CTX *recp = BN_RECP_CTX_new();
28     BN_CTX *ctx = BN_CTX_new();
29     int i = 0;
30 
31     for (i = 0; i < 10000; i++) {
32         BN_pseudo_rand(a, Rand(), 0, 0);
33         BN_pseudo_rand(b, Rand(), 0, 0);
34         if (BN_is_zero(b))
35             continue;
36 
37         BN_RECP_CTX_set(recp, b, ctx);
38         if (BN_div(C, D, a, b, ctx) != 1)
39             bug("BN_div failed", a, b);
40         if (BN_div_recp(c, d, a, recp, ctx) != 1)
41             bug("BN_div_recp failed", a, b);
42         else if (BN_cmp(c, C) != 0 || BN_cmp(c, C) != 0)
43             bug("mismatch", a, b);
44     }
45     exit(0);
46 }
47