Add comment about X509_print
[openssl.git] / fuzz / bignum.c
1 /*
2  * Copyright 2016 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the OpenSSL licenses, (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  * https://www.openssl.org/source/license.html
8  * or in the file LICENSE in the source distribution.
9  */
10
11 /*
12  * Confirm that a^b mod c agrees when calculated cleverly vs naively, for
13  * random a, b and c.
14  */
15
16 #include <stdio.h>
17 #include <openssl/bn.h>
18 #include "fuzzer.h"
19
20 int FuzzerTestOneInput(const uint8_t *buf, size_t len) {
21     int success = 0;
22     static BN_CTX *ctx;
23     static BN_MONT_CTX *mont;
24     static BIGNUM *b1;
25     static BIGNUM *b2;
26     static BIGNUM *b3;
27     static BIGNUM *b4;
28     static BIGNUM *b5;
29
30     if (ctx == NULL) {
31         b1 = BN_new();
32         b2 = BN_new();
33         b3 = BN_new();
34         b4 = BN_new();
35         b5 = BN_new();
36         ctx = BN_CTX_new();
37         mont = BN_MONT_CTX_new();
38     }
39     // Divide the input into three parts, using the values of the first two
40     // bytes to choose lengths, which generate b1, b2 and b3. Use three bits
41     // of the third byte to choose signs for the three numbers.
42     size_t l1 = 0, l2 = 0, l3 = 0;
43     int s1 = 0, s2 = 0, s3 = 0;
44     if (len > 2) {
45         len -= 3;
46         l1 = (buf[0] * len) / 255;
47         ++buf;
48         l2 = (buf[0] * (len - l1)) / 255;
49         ++buf;
50         l3 = len - l1 - l2;
51
52         s1 = buf[0] & 1;
53         s2 = buf[0] & 2;
54         s3 = buf[0] & 4;
55         ++buf;
56     }
57     OPENSSL_assert(BN_bin2bn(buf, l1, b1) == b1);
58     BN_set_negative(b1, s1);
59     OPENSSL_assert(BN_bin2bn(buf + l1, l2, b2) == b2);
60     BN_set_negative(b2, s2);
61     OPENSSL_assert(BN_bin2bn(buf + l1 + l2, l3, b3) == b3);
62     BN_set_negative(b3, s3);
63
64     // mod 0 is undefined
65     if (BN_is_zero(b3)) {
66         success = 1;
67         goto done;
68     }
69
70     OPENSSL_assert(BN_mod_exp(b4, b1, b2, b3, ctx));
71     OPENSSL_assert(BN_mod_exp_simple(b5, b1, b2, b3, ctx));
72
73     success = BN_cmp(b4, b5) == 0;
74     if (!success) {
75         BN_print_fp(stdout, b1);
76         putchar('\n');
77         BN_print_fp(stdout, b2);
78         putchar('\n');
79         BN_print_fp(stdout, b3);
80         putchar('\n');
81         BN_print_fp(stdout, b4);
82         putchar('\n');
83         BN_print_fp(stdout, b5);
84         putchar('\n');
85     }
86
87  done:
88     OPENSSL_assert(success);
89
90     return 0;
91 }