Coverage Report

Created: 2020-11-21 08:34

/src/botan/src/fuzzer/invert.cpp
Line
Count
Source (jump to first uncovered line)
1
/*
2
* (C) 2015,2016,2020 Jack Lloyd
3
*
4
* Botan is released under the Simplified BSD License (see license.txt)
5
*/
6
#include "fuzzers.h"
7
#include <botan/numthry.h>
8
9
namespace {
10
11
Botan::BigInt ref_inverse_mod(const Botan::BigInt& n, const Botan::BigInt& mod)
12
927
   {
13
927
   if(n == 0 || mod < 2)
14
3
      return 0;
15
924
   if(n.is_even() && mod.is_even())
16
5
      return 0;
17
919
   Botan::BigInt u = mod, v = n;
18
919
   Botan::BigInt A = 1, B = 0, C = 0, D = 1;
19
20
421k
   while(u.is_nonzero())
21
420k
      {
22
420k
      const size_t u_zero_bits = Botan::low_zero_bits(u);
23
420k
      u >>= u_zero_bits;
24
1.01M
      for(size_t i = 0; i != u_zero_bits; ++i)
25
597k
         {
26
597k
         if(A.is_odd() || B.is_odd())
27
276k
            { A += n; B -= mod; }
28
597k
         A >>= 1; B >>= 1;
29
597k
         }
30
31
420k
      const size_t v_zero_bits = Botan::low_zero_bits(v);
32
420k
      v >>= v_zero_bits;
33
1.00M
      for(size_t i = 0; i != v_zero_bits; ++i)
34
586k
         {
35
586k
         if(C.is_odd() || D.is_odd())
36
281k
            { C += n; D -= mod; }
37
586k
         C >>= 1; D >>= 1;
38
586k
         }
39
40
420k
      if(u >= v) { u -= v; A -= C; B -= D; }
41
280k
      else       { v -= u; C -= A; D -= B; }
42
420k
      }
43
44
919
   if(v != 1)
45
138
      return 0; // no modular inverse
46
47
1.57k
   while(D.is_negative()) D += mod;
48
993
   while(D >= mod) D -= mod;
49
50
781
   return D;
51
781
   }
52
53
}
54
55
void fuzz(const uint8_t in[], size_t len)
56
947
   {
57
947
   static const size_t max_bits = 4096;
58
59
947
   if(len > 2*max_bits/8)
60
17
      return;
61
62
930
   const Botan::BigInt x = Botan::BigInt::decode(in, len / 2);
63
930
   Botan::BigInt mod = Botan::BigInt::decode(in + len / 2, len - len / 2);
64
65
930
   if(mod < 2)
66
3
      return;
67
68
927
   const Botan::BigInt lib = Botan::inverse_mod(x, mod);
69
927
   const Botan::BigInt ref = ref_inverse_mod(x, mod);
70
71
927
   if(ref != lib)
72
0
      {
73
0
      FUZZER_WRITE_AND_CRASH("X = " << x << "\n"
74
0
                             << "Mod = " << mod << "\n"
75
0
                             << "GCD(X,Mod) = " << gcd(x, mod) << "\n"
76
0
                             << "RefInv(X,Mod) = " << ref << "\n"
77
0
                             << "LibInv(X,Mod)  = " << lib << "\n"
78
0
                             << "RefCheck = " << (x*ref)%mod << "\n"
79
0
                             << "LibCheck  = " << (x*lib)%mod << "\n");
80
0
      }
81
927
   }
82