Coverage Report

Created: 2026-12-01 06:40

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/Botan-3.13.0/src/lib/math/bigint/big_code.cpp
Line
Count
Source
1
/*
2
* BigInt Encoding/Decoding
3
* (C) 1999-2010,2012,2019,2021 Jack Lloyd
4
*
5
* Botan is released under the Simplified BSD License (see license.txt)
6
*/
7
8
#include <botan/bigint.h>
9
10
#include <botan/assert.h>
11
#include <botan/exceptn.h>
12
#include <botan/hex.h>
13
#include <botan/mem_ops.h>
14
#include <botan/internal/buffer_stuffer.h>
15
#include <botan/internal/divide.h>
16
#include <botan/internal/mp_core.h>
17
18
namespace Botan {
19
20
namespace {
21
22
consteval word decimal_conversion_radix() {
23
   if constexpr(sizeof(word) == 8) {
24
      return 10000000000000000000U;
25
   } else {
26
      return 1000000000U;
27
   }
28
}
29
30
consteval size_t decimal_conversion_radix_digits() {
31
   if constexpr(sizeof(word) == 8) {
32
      return 19;
33
   } else {
34
      return 9;
35
   }
36
}
37
38
}  // namespace
39
40
0
std::string BigInt::to_dec_string() const {
41
   // Use the largest power of 10 that fits in a word
42
0
   constexpr word conversion_radix = decimal_conversion_radix();
43
0
   constexpr size_t radix_digits = decimal_conversion_radix_digits();
44
45
   // (over-)estimate of the number of digits needed; log2(10) ~ 3.3219
46
0
   const size_t digit_estimate = static_cast<size_t>(1 + (static_cast<double>(this->bits()) / 3.32));
47
48
   // (over-)estimate of db such that conversion_radix^db > *this
49
0
   const size_t digit_blocks = (digit_estimate + radix_digits - 1) / radix_digits;
50
51
0
   BigInt value = *this;
52
0
   value.set_sign(Positive);
53
54
   // Extract groups of digits into words
55
0
   std::vector<word> digit_groups(digit_blocks);
56
57
0
   for(size_t i = 0; i != digit_blocks; ++i) {
58
0
      word remainder = 0;
59
0
      ct_divide_word(value, conversion_radix, value, remainder);
60
0
      digit_groups[i] = remainder;
61
0
   }
62
63
0
   BOTAN_ASSERT_NOMSG(value.is_zero());
64
65
   // Extract digits from the groups
66
0
   std::vector<uint8_t> digits(digit_blocks * radix_digits);
67
68
0
   for(size_t i = 0; i != digit_blocks; ++i) {
69
0
      word remainder = digit_groups[i];
70
0
      for(size_t j = 0; j != radix_digits; ++j) {
71
0
         const word new_remainder = divide_10(remainder);
72
0
         const word digit = remainder - new_remainder * 10;
73
0
         digits[radix_digits * i + j] = static_cast<uint8_t>(digit);
74
0
         remainder = new_remainder;
75
0
      }
76
0
   }
77
78
   // remove leading zeros
79
0
   while(!digits.empty() && digits.back() == 0) {
80
0
      digits.pop_back();
81
0
   }
82
83
0
   BOTAN_ASSERT_NOMSG(digit_estimate >= digits.size());
84
85
   // Reverse the digits to big-endian and format to text
86
0
   std::string s;
87
0
   s.reserve(1 + digits.size());
88
89
0
   if(signum() < 0) {
90
0
      s += "-";
91
0
   }
92
93
   // Reverse and convert to textual digits
94
   // TODO(Botan4) use std::ranges::reverse_view here once available (need newer Clang)
95
   // NOLINTNEXTLINE(modernize-loop-convert)
96
0
   for(auto i = digits.rbegin(); i != digits.rend(); ++i) {
97
0
      s.push_back(*i + '0');  // assumes ASCII
98
0
   }
99
100
0
   if(s.empty()) {
101
0
      s += "0";
102
0
   }
103
104
0
   return s;
105
0
}
106
107
0
std::string BigInt::to_hex_string() const {
108
0
   const size_t this_bytes = this->bytes();
109
0
   std::vector<uint8_t> bits(std::max<size_t>(1, this_bytes));
110
111
0
   if(this_bytes > 0) {
112
0
      this->serialize_to(bits);
113
0
   }
114
115
0
   std::string hrep;
116
0
   if(signum() < 0) {
117
0
      hrep += "-";
118
0
   }
119
0
   hrep += "0x";
120
0
   hrep += hex_encode(bits);
121
0
   return hrep;
122
0
}
123
124
//static
125
162
BigInt BigInt::from_radix_digits(std::string_view digits, size_t radix) {
126
162
   if(radix == 16) {
127
162
      secure_vector<uint8_t> binary;
128
129
162
      if(digits.size() % 2 == 1) {
130
         // Handle lack of leading 0
131
24
         const char buf0_with_leading_0[2] = {'0', digits[0]};
132
133
24
         binary = hex_decode_locked(buf0_with_leading_0, 2);
134
135
24
         if(digits.size() > 1) {
136
14
            binary += hex_decode_locked(&digits[1], digits.size() - 1, false);
137
14
         }
138
138
      } else {
139
138
         binary = hex_decode_locked(digits, false);
140
138
      }
141
142
162
      return BigInt::from_bytes(binary);
143
162
   } else if(radix == 10) {
144
      // Use the largest power of 10 that fits in a word, accumulating
145
      // groups of digits into word-sized chunks to minimize the number
146
      // of multiprecision multiplications.
147
0
      constexpr word conversion_radix = decimal_conversion_radix();
148
0
      constexpr size_t radix_digits = decimal_conversion_radix_digits();
149
150
0
      BigInt r;
151
152
      // Handle the initial partial block (if digit count is not a multiple of radix_digits)
153
0
      const size_t partial_block = digits.size() % radix_digits;
154
155
0
      if(partial_block > 0) {
156
0
         word acc = 0;
157
0
         for(size_t i = 0; i < partial_block; ++i) {
158
0
            const char c = digits[i];
159
0
            BOTAN_ARG_CHECK(c >= '0' && c <= '9', "Invalid decimal character");
160
0
            acc = acc * 10 + static_cast<word>(c - '0');
161
0
         }
162
0
         r += acc;
163
0
      }
164
165
      // Process full blocks of radix_digits
166
0
      for(size_t i = partial_block; i != digits.size(); i += radix_digits) {
167
0
         word acc = 0;
168
0
         for(size_t j = 0; j < radix_digits; ++j) {
169
0
            const char c = digits[i + j];
170
0
            BOTAN_ARG_CHECK(c >= '0' && c <= '9', "Invalid decimal character");
171
0
            acc = acc * 10 + static_cast<word>(c - '0');
172
0
         }
173
0
         r *= conversion_radix;
174
0
         r += acc;
175
0
      }
176
177
0
      return r;
178
0
   } else {
179
0
      throw Invalid_Argument("BigInt::from_radix_digits unknown radix");
180
0
   }
181
162
}
182
183
/*
184
* Encode two BigInt, with leading 0s if needed, and concatenate
185
*/
186
0
secure_vector<uint8_t> BigInt::encode_fixed_length_int_pair(const BigInt& n1, const BigInt& n2, size_t bytes) {
187
0
   if(n1.signum() < 0 || n2.signum() < 0) {
188
0
      throw Encoding_Error("encode_fixed_length_int_pair: values must be positive");
189
0
   }
190
0
   if(n1.bytes() > bytes || n2.bytes() > bytes) {
191
0
      throw Encoding_Error("encode_fixed_length_int_pair: values too large to encode properly");
192
0
   }
193
0
   secure_vector<uint8_t> output(2 * bytes);
194
0
   BufferStuffer stuffer(output);
195
0
   n1.serialize_to(stuffer.next(bytes));
196
0
   n2.serialize_to(stuffer.next(bytes));
197
0
   return output;
198
0
}
199
200
0
BigInt BigInt::decode(std::span<const uint8_t> buf, Base base) {
201
0
   if(base == Binary) {
202
0
      return BigInt::from_bytes(buf);
203
0
   }
204
0
   return BigInt::decode(buf.data(), buf.size(), base);
205
0
}
206
207
/*
208
* Decode a BigInt
209
*/
210
0
BigInt BigInt::decode(const uint8_t buf[], size_t length, Base base) {
211
0
   if(base == Binary) {
212
0
      return BigInt::from_bytes(std::span{buf, length});
213
0
   } else if(base == Hexadecimal) {
214
0
      const std::string_view sv{cast_uint8_ptr_to_char(buf), length};
215
0
      return BigInt::from_radix_digits(sv, 16);
216
0
   } else if(base == Decimal) {
217
0
      const std::string_view sv{cast_uint8_ptr_to_char(buf), length};
218
0
      return BigInt::from_radix_digits(sv, 10);
219
0
   } else {
220
0
      throw Invalid_Argument("Unknown BigInt decoding method");
221
0
   }
222
0
}
223
224
}  // namespace Botan