Test the division functions.
[openssl.git] / crypto / bn / divtest.c
1 #include <openssl/bn.h>
2
3 int rand(n)
4 {
5     unsigned char x[2];
6     RAND_bytes(&x,2);
7     return (x[0] + 2*x[1]);
8 }
9
10 void bug(char *m, BIGNUM *a, BIGNUM *b)
11 {
12     printf("%s!\na=",m);
13     BN_print_fp(stdout, a);
14     printf("\nb=");
15     BN_print_fp(stdout, b);
16     printf("\n");
17 }
18
19 main()
20 {
21     BIGNUM *a=BN_new(), *b=BN_new(), *c=BN_new(), *d=BN_new(),
22         *C=BN_new(), *D=BN_new();
23     BN_RECP_CTX *recp=BN_RECP_CTX_new();
24     BN_CTX *ctx=BN_CTX_new();
25
26     for(;;) {
27         BN_rand(a,rand(),0,0);
28         BN_rand(b,rand(),0,0);
29         if (BN_is_zero(b)) continue;
30
31         BN_RECP_CTX_set(recp,b,ctx);
32         if (BN_div(C,D,a,b,ctx) != 1)
33             bug("BN_div failed",a,b);
34         if (BN_div_recp(c,d,a,recp,ctx) != 1)
35             bug("BN_div_recp failed",a,b);
36         else if (BN_cmp(c,C) != 0 || BN_cmp(c,C) != 0)
37             bug("mismatch",a,b);
38     }
39 }