• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

randombit / botan / 44666972694

20 Nov 2026 02:15AM UTC coverage: 92.49% (+0.007%) from 92.483%
44666972694

push

github

web-flow
Merge pull request #6146 from randombit/jack/prime-gen-opt

Some optimizations for prime generation and for Montgomery exp with a base of 2

145716 of 157548 relevant lines covered (92.49%)

8605234.7 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

95.82
/src/tests/test_bigint.cpp
1
/*
2
* (C) 2009,2015,2016 Jack Lloyd
3
* (C) 2024           Fabian Albert, René Meusel -  Rohde & Schwarz Cybersecurity
4
*
5
* Botan is released under the Simplified BSD License (see license.txt)
6
*/
7

8
#include "tests.h"
9

10
#if defined(BOTAN_HAS_NUMBERTHEORY)
11
   #include "test_rng.h"
12
   #include <botan/bigint.h>
13
   #include <botan/exceptn.h>
14
   #include <botan/numthry.h>
15
   #include <botan/internal/barrett.h>
16
   #include <botan/internal/concat_util.h>
17
   #include <botan/internal/ct_utils.h>
18
   #include <botan/internal/divide.h>
19
   #include <botan/internal/fmt.h>
20
   #include <botan/internal/loadstor.h>
21
   #include <botan/internal/mod_inv.h>
22
   #include <botan/internal/monty.h>
23
   #include <botan/internal/parsing.h>
24
   #include <botan/internal/primality.h>
25
   #include <set>
26
#endif
27

28
namespace Botan_Tests {
29

30
namespace {
31

32
#if defined(BOTAN_HAS_NUMBERTHEORY)
33

34
using Botan::BigInt;
35

36
class BigInt_Unit_Tests final : public Test {
1 ✔
37
   public:
38
      std::vector<Test::Result> run() override {
1 ✔
39
         std::vector<Test::Result> results;
1 ✔
40

41
         results.push_back(test_bigint_sizes());
2 ✔
42
         results.push_back(test_random_prime());
2 ✔
43
         results.push_back(test_is_prime_strong());
2 ✔
44
         results.push_back(test_encode());
2 ✔
45
         results.push_back(test_bigint_io());
2 ✔
46
         results.push_back(test_decimal_round_trip());
2 ✔
47
         results.push_back(test_get_substring());
2 ✔
48

49
         return results;
1 ✔
50
      }
×
51

52
   private:
53
      static Test::Result test_bigint_sizes() {
1 ✔
54
         Test::Result result("BigInt size functions");
1 ✔
55

56
         for(const size_t bit : {1, 8, 16, 31, 32, 64, 97, 128, 179, 192, 512, 521}) {
13 ✔
57
            BigInt a;
12 ✔
58

59
            a.set_bit(bit);
12 ✔
60

61
            // Test 2^n and 2^n-1
62
            for(size_t i = 0; i != 2; ++i) {
36 ✔
63
               const size_t exp_bits = bit + 1 - i;
24 ✔
64
               result.test_sz_eq("BigInt::bits", a.bits(), exp_bits);
24 ✔
65
               result.test_sz_eq(
24 ✔
66
                  "BigInt::bytes", a.bytes(), (exp_bits % 8 == 0) ? (exp_bits / 8) : (exp_bits + 8 - exp_bits % 8) / 8);
24 ✔
67

68
               if(bit == 1 && i == 1) {
24 ✔
69
                  result.test_u32_eq("BigInt::to_u32bit zero", a.to_u32bit(), static_cast<uint32_t>(1));
1 ✔
70
               } else if(bit <= 31 || (bit == 32 && i == 1)) {
23 ✔
71
                  result.test_u32_eq(
8 ✔
72
                     "BigInt::to_u32bit", a.to_u32bit(), static_cast<uint32_t>((uint64_t(1) << bit) - i));
8 ✔
73
               } else {
74
                  try {
15 ✔
75
                     a.to_u32bit();
15 ✔
76
                     result.test_failure("BigInt::to_u32bit roundtripped out of range value");
×
77
                  } catch(std::exception&) {
15 ✔
78
                     result.test_success("BigInt::to_u32bit rejected out of range");
15 ✔
79
                  }
15 ✔
80
               }
81

82
               a--;
24 ✔
83
            }
84
         }
12 ✔
85

86
         BigInt x = BigInt::from_u64(3);
1 ✔
87
         for(size_t i = 0; i != 1000; ++i) {
1,001 ✔
88
            x *= 1;
1,000 ✔
89
         }
90
         result.test_sz_lte("Repeated operator*= by a word does not grow the register", x.size(), 16);
1 ✔
91

92
         // operator% returns its input as is if it is already reduced, so
93
         // a product must not be sized from the registers of its operands
94
         const BigInt p = BigInt::power_of_2(127) - 1;
2 ✔
95
         const size_t bound = 2 * p.sig_words() + 8;
1 ✔
96
         for(const Botan::word start : {1, 2}) {
3 ✔
97
            BigInt r = BigInt::from_word(start);
2 ✔
98
            for(size_t i = 0; i != 64 && r.size() <= bound; ++i) {
130 ✔
99
               r = (r * r) % p;
128 ✔
100
            }
101
            result.test_sz_lte("Repeated modular squaring does not grow the register", r.size(), bound);
2 ✔
102
         }
2 ✔
103

104
         return result;
1 ✔
105
      }
1 ✔
106

107
      static Test::Result test_is_prime_strong() {
1 ✔
108
         Test::Result result("BigInt is_prime with many tests");
1 ✔
109

110
         auto rng = Test::new_rng("is_prime_strong");
1 ✔
111

112
         for(const size_t bits : {512, 1024}) {
3 ✔
113
            const BigInt p = Botan::random_prime(*rng, bits);
2 ✔
114
            result.test_is_true("Prime passes a strong check", Botan::is_prime(p, *rng, 128, false));
2 ✔
115
            result.test_is_true("Prime passes a strong vartime check", Botan::is_prime_vartime(p, *rng, 128, false));
2 ✔
116
         }
2 ✔
117

118
         /*
119
         * A composite with no small factors, tested with bases that are all n-1,
120
         * which is a strong liar for any odd n. This forces the Miller-Rabin tests
121
         * in the calling thread to pass, so that rejection can only come from the
122
         * remaining tests, including any run in the thread pool.
123
         */
124
         const BigInt n = Botan::random_prime(*rng, 512) * Botan::random_prime(*rng, 512);
1 ✔
125

126
         // random_integer draws bits(n - 2) bits and returns 2 + r, so r = n - 3 gives n - 1
127
         const BigInt n_minus_3 = n - 3;
1 ✔
128
         const auto liar = n_minus_3.serialize(((n - 2).bits() + 7) / 8);
1 ✔
129

130
         for(const bool vartime : {false, true}) {
3 ✔
131
            Fixed_Output_RNG liar_rng(*rng);
2 ✔
132
            for(size_t i = 0; i != 9; ++i) {
20 ✔
133
               liar_rng.add_entropy(liar);
18 ✔
134
            }
135

136
            const bool accepted =
2 ✔
137
               vartime ? Botan::is_prime_vartime(n, liar_rng, 128, false) : Botan::is_prime(n, liar_rng, 128, false);
2 ✔
138
            result.test_is_false("Composite rejected despite strong liar bases", accepted);
2 ✔
139
         }
2 ✔
140

141
         return result;
2 ✔
142
      }
2 ✔
143

144
      static Test::Result test_random_prime() {
1 ✔
145
         Test::Result result("BigInt prime generation");
1 ✔
146

147
         auto rng = Test::new_rng("random_prime");
1 ✔
148

149
         result.test_throws(
1 ✔
150
            "Invalid bit size", "random_prime: Can't make a prime of 0 bits", [&]() { Botan::random_prime(*rng, 0); });
2 ✔
151
         result.test_throws(
1 ✔
152
            "Invalid bit size", "random_prime: Can't make a prime of 1 bits", [&]() { Botan::random_prime(*rng, 1); });
2 ✔
153
         result.test_throws("Invalid arg", "random_prime Invalid value for equiv/modulo", [&]() {
1 ✔
154
            Botan::random_prime(*rng, 2, 1, 0, 2);
1 ✔
155
         });
×
156

157
         BigInt p = Botan::random_prime(*rng, 2);
1 ✔
158
         result.test_is_true("Only two 2-bit primes", p == 2 || p == 3);
2 ✔
159

160
         p = Botan::random_prime(*rng, 3);
1 ✔
161
         result.test_is_true("Only two 3-bit primes", p == 5 || p == 7);
3 ✔
162

163
         p = Botan::random_prime(*rng, 4);
1 ✔
164
         result.test_is_true("Only two 4-bit primes", p == 11 || p == 13);
3 ✔
165

166
         for(size_t bits = 5; bits <= 32; ++bits) {
29 ✔
167
            p = Botan::random_prime(*rng, bits);
28 ✔
168
            result.test_sz_eq("Expected bit size", p.bits(), bits);
28 ✔
169
            result.test_is_true("P is prime", Botan::is_prime(p, *rng));
28 ✔
170
         }
171

172
         const size_t safe_prime_bits = 65;
1 ✔
173
         const BigInt safe_prime = Botan::random_safe_prime(*rng, safe_prime_bits);
1 ✔
174
         result.test_sz_eq("Safe prime size", safe_prime.bits(), safe_prime_bits);
1 ✔
175
         result.test_is_true("P is prime", Botan::is_prime(safe_prime, *rng));
1 ✔
176
         result.test_is_true("(P-1)/2 is prime", Botan::is_prime((safe_prime - 1) / 2, *rng));
1 ✔
177
         result.test_sz_eq("Safe prime is 7 mod 8", safe_prime % 8, 7);
1 ✔
178

179
         for(const size_t modulo : {3, 5, 7, 11}) {
5 ✔
180
            const size_t equiv = (modulo - 1) / 2;
4 ✔
181
            const BigInt q = Botan::random_prime(*rng, 64, BigInt::zero(), equiv, modulo);
4 ✔
182
            result.test_is_true(
8 ✔
183
               "random_prime returned a prime for equiv=" + std::to_string(equiv) + " modulo=" + std::to_string(modulo),
16 ✔
184
               Botan::is_prime(q, *rng));
4 ✔
185
            result.test_bn_eq("congruence holds", q % BigInt::from_word(modulo), BigInt::from_word(equiv));
4 ✔
186
         }
4 ✔
187

188
         return result;
2 ✔
189
      }
2 ✔
190

191
      static Test::Result test_encode() {
1 ✔
192
         Test::Result result("BigInt encoding functions");
1 ✔
193

194
         const auto n1 = Botan::BigInt::from_u64(0xffff);
1 ✔
195
         const auto n2 = Botan::BigInt::from_u64(1023);
1 ✔
196

197
         const auto encoded_n1 = n1.serialize(256);
1 ✔
198
         const auto encoded_n2 = n2.serialize(256);
1 ✔
199
         const auto expected = Botan::concat(encoded_n1, encoded_n2);
1 ✔
200

201
         const auto encoded_n1_n2 = BigInt::encode_fixed_length_int_pair(n1, n2, 256);
1 ✔
202
         result.test_bin_eq("encode_fixed_length_int_pair", encoded_n1_n2, expected);
1 ✔
203

204
         for(size_t i = 0; i < 256 - n1.bytes(); ++i) {
255 ✔
205
            if(encoded_n1[i] != 0) {
254 ✔
206
               result.test_failure("BigInt::serialize", "no zero byte");
×
207
            }
208
         }
209

210
         return result;
2 ✔
211
      }
1 ✔
212

213
      static Test::Result test_get_substring() {
1 ✔
214
         Test::Result result("BigInt get_substring");
1 ✔
215

216
         const size_t rbits = 1024;
1 ✔
217

218
         auto rng = Test::new_rng("get_substring");
1 ✔
219

220
         const Botan::BigInt r(*rng, rbits);
1 ✔
221

222
         for(size_t wlen = 1; wlen <= 32; ++wlen) {
33 ✔
223
            for(size_t offset = 0; offset != rbits + 64; ++offset) {
34,848 ✔
224
               const uint32_t val = r.get_substring(offset, wlen);
34,816 ✔
225

226
               Botan::BigInt t = r >> offset;
34,816 ✔
227
               t.mask_bits(wlen);
34,816 ✔
228

229
               const uint32_t cmp = t.to_u32bit();
34,816 ✔
230

231
               result.test_sz_eq("Same value", size_t(val), size_t(cmp));
34,816 ✔
232
            }
34,816 ✔
233
         }
234

235
         return result;
2 ✔
236
      }
2 ✔
237

238
      static Test::Result test_decimal_round_trip() {
1 ✔
239
         Test::Result result("BigInt decimal round trip");
1 ✔
240

241
         auto rng = Test::new_rng("bigint_decimal_round_trip");
1 ✔
242

243
         const auto check_round_trip = [&](const BigInt& n) {
2,052 ✔
244
            const std::string dec = n.to_dec_string();
2,051 ✔
245
            result.test_bn_eq("decimal round trip", BigInt::from_radix_digits(dec, 10), n);
2,051 ✔
246
            result.test_str_eq("negative decimal", (-n).to_dec_string(), "-" + dec);
2,051 ✔
247
         };
4,102 ✔
248

249
         for(size_t bits = 1; bits <= 1024; ++bits) {
1,025 ✔
250
            check_round_trip(BigInt(*rng, bits));
1,024 ✔
251
            check_round_trip(BigInt::power_of_2(bits) - 1);
2,048 ✔
252
         }
253

254
         for(const size_t bits : {2048, 4096, 10000}) {
4 ✔
255
            check_round_trip(BigInt(*rng, bits));
3 ✔
256
         }
257

258
         return result;
1 ✔
259
      }
1 ✔
260

261
      static Test::Result test_bigint_io() {
1 ✔
262
         Test::Result result("BigInt IO operators");
1 ✔
263

264
         const std::map<std::string, Botan::BigInt> str_to_val = {{"-13", -Botan::BigInt(13)},
2 ✔
265
                                                                  {"0", Botan::BigInt(0)},
2 ✔
266
                                                                  {"0x13", Botan::BigInt(0x13)},
2 ✔
267
                                                                  {"1", Botan::BigInt(1)},
2 ✔
268
                                                                  {"4294967297", Botan::BigInt(2147483648) * 2 + 1}};
7 ✔
269

270
         for(const auto& vec : str_to_val) {
6 ✔
271
            Botan::BigInt n;
5 ✔
272
            std::istringstream iss;
5 ✔
273

274
            iss.str(vec.first);
5 ✔
275
            iss >> n;
5 ✔
276
            result.test_bn_eq("input '" + vec.first + "'", n, vec.second);
15 ✔
277
         }
5 ✔
278

279
         const auto check_bigint_formatting = [&](const Botan::BigInt& n,
6 ✔
280
                                                  const std::string& dec,
281
                                                  const std::string& hex,
282
                                                  const std::string& neg_dec,
283
                                                  const std::string& neg_hex) {
284
            std::ostringstream oss;
5 ✔
285
            oss << n;
5 ✔
286
            result.test_str_eq("output decimal", oss.str(), dec);
5 ✔
287

288
            oss.str("");
10 ✔
289
            oss << (-n);
5 ✔
290
            result.test_str_eq("output negative decimal", oss.str(), neg_dec);
5 ✔
291

292
            oss.str("");
10 ✔
293
            oss << std::hex << n;
5 ✔
294
            result.test_str_eq("output hex", oss.str(), hex);
5 ✔
295

296
            oss.str("");
10 ✔
297
            oss << std::hex << (-n);
5 ✔
298
            result.test_str_eq("output negative hex", oss.str(), neg_hex);
5 ✔
299
         };
5 ✔
300

301
         check_bigint_formatting(Botan::BigInt(33), "33", "0x21", "-33", "-0x21");
1 ✔
302
         check_bigint_formatting(Botan::BigInt::from_s32(-33), "-33", "-0x21", "33", "0x21");
1 ✔
303
         check_bigint_formatting(Botan::BigInt(255), "255", "0xFF", "-255", "-0xFF");
1 ✔
304
         check_bigint_formatting(Botan::BigInt(0), "0", "0x00", "0", "0x00");
1 ✔
305
         check_bigint_formatting(Botan::BigInt(5), "5", "0x05", "-5", "-0x05");
1 ✔
306

307
         result.test_throws("octal output not supported", [&]() {
1 ✔
308
            const Botan::BigInt n(5);
1 ✔
309
            std::ostringstream oss;
1 ✔
310
            oss << std::oct << n;
1 ✔
311
         });
2 ✔
312

313
         return result;
1 ✔
314
      }
5 ✔
315
};
316

317
BOTAN_REGISTER_TEST("math", "bigint_unit", BigInt_Unit_Tests);
318

319
class BigInt_Cmp_Test final : public Text_Based_Test {
×
320
   public:
321
      BigInt_Cmp_Test() : Text_Based_Test("bn/cmp.vec", "X,Y,R") {}
2 ✔
322

323
      Test::Result run_one_test(const std::string& op, const VarMap& vars) override {
19 ✔
324
         Test::Result result("BigInt Comparison " + op);
19 ✔
325

326
         const BigInt x = vars.get_req_bn("X");
19 ✔
327
         const BigInt y = vars.get_req_bn("Y");
19 ✔
328
         const bool expected = vars.get_req_bool("R");
19 ✔
329

330
         if(op == "EQ") {
19 ✔
331
            result.test_bool_eq("Values equal", x == y, expected);
6 ✔
332
         } else if(op == "LT") {
13 ✔
333
            result.test_bool_eq("Values LT", x < y, expected);
6 ✔
334

335
            if(expected) {
6 ✔
336
               result.test_is_true("If LT then reverse is GT", y >= x);
2 ✔
337
            } else {
338
               result.test_is_true("If not LT then GTE", x >= y);
4 ✔
339
            }
340
         } else if(op == "LTE") {
7 ✔
341
            result.test_bool_eq("Values LTE", x <= y, expected);
7 ✔
342

343
            if(expected) {
7 ✔
344
               result.test_is_true("If LTE then either LT or EQ", x < y || x == y);
9 ✔
345
            } else {
346
               result.test_is_true("If not LTE then GT", x > y);
3 ✔
347
            }
348
         } else {
349
            throw Test_Error("Unknown BigInt comparison type " + op);
×
350
         }
351

352
         return result;
19 ✔
353
      }
19 ✔
354
};
355

356
BOTAN_REGISTER_TEST("math", "bn_cmp", BigInt_Cmp_Test);
357

358
class BigInt_Add_Test final : public Text_Based_Test {
×
359
   public:
360
      BigInt_Add_Test() : Text_Based_Test("bn/add.vec", "In1,In2,Output") {}
2 ✔
361

362
      Test::Result run_one_test(const std::string& /*header*/, const VarMap& vars) override {
78 ✔
363
         Test::Result result("BigInt Addition");
78 ✔
364

365
         using Botan::BigInt;
78 ✔
366

367
         const BigInt a = vars.get_req_bn("In1");
78 ✔
368
         const BigInt b = vars.get_req_bn("In2");
78 ✔
369
         const BigInt c = vars.get_req_bn("Output");
78 ✔
370

371
         result.test_bn_eq("a + b", a + b, c);
78 ✔
372
         result.test_bn_eq("b + a", b + a, c);
78 ✔
373

374
         BigInt e = a;
78 ✔
375
         e += b;
78 ✔
376
         result.test_bn_eq("a += b", e, c);
78 ✔
377

378
         e = b;
78 ✔
379
         e += a;
78 ✔
380
         result.test_bn_eq("b += a", e, c);
78 ✔
381

382
         return result;
78 ✔
383
      }
78 ✔
384
};
385

386
BOTAN_REGISTER_TEST("math", "bn_add", BigInt_Add_Test);
387

388
class BigInt_Sub_Test final : public Text_Based_Test {
×
389
   public:
390
      BigInt_Sub_Test() : Text_Based_Test("bn/sub.vec", "In1,In2,Output") {}
2 ✔
391

392
      Test::Result run_one_test(const std::string& /*header*/, const VarMap& vars) override {
77 ✔
393
         Test::Result result("BigInt Subtraction");
77 ✔
394

395
         const BigInt a = vars.get_req_bn("In1");
77 ✔
396
         const BigInt b = vars.get_req_bn("In2");
77 ✔
397
         const BigInt c = vars.get_req_bn("Output");
77 ✔
398

399
         result.test_bn_eq("a - b", a - b, c);
77 ✔
400

401
         BigInt e = a;
77 ✔
402
         e -= b;
77 ✔
403
         result.test_bn_eq("a -= b", e, c);
77 ✔
404

405
         return result;
77 ✔
406
      }
77 ✔
407
};
408

409
BOTAN_REGISTER_TEST("math", "bn_sub", BigInt_Sub_Test);
410

411
class BigInt_Mul_Test final : public Text_Based_Test {
×
412
   public:
413
      BigInt_Mul_Test() : Text_Based_Test("bn/mul.vec", "In1,In2,Output") {}
2 ✔
414

415
      Test::Result run_one_test(const std::string& /*header*/, const VarMap& vars) override {
104 ✔
416
         Test::Result result("BigInt Multiply");
104 ✔
417

418
         const BigInt a = vars.get_req_bn("In1");
104 ✔
419
         const BigInt b = vars.get_req_bn("In2");
104 ✔
420
         const BigInt c = vars.get_req_bn("Output");
104 ✔
421

422
         result.test_bn_eq("a * b", a * b, c);
104 ✔
423
         result.test_bn_eq("b * a", b * a, c);
104 ✔
424

425
         BigInt e = a;
104 ✔
426
         e *= b;
104 ✔
427
         result.test_bn_eq("a *= b", e, c);
104 ✔
428

429
         e = b;
104 ✔
430
         e *= a;
104 ✔
431
         result.test_bn_eq("b *= a", e, c);
104 ✔
432

433
         if(b.signum() >= 0 && b.sig_words() <= 1) {
176 ✔
434
            const Botan::word w = b.word_at(0);
11 ✔
435
            result.test_bn_eq("a * word", a * w, c);
11 ✔
436
            e = a;
11 ✔
437
            e *= w;
11 ✔
438
            result.test_bn_eq("a *= word", e, c);
11 ✔
439
         }
440

441
         if(a.signum() >= 0 && a.sig_words() <= 1) {
175 ✔
442
            const Botan::word w = a.word_at(0);
16 ✔
443
            result.test_bn_eq("b * word", b * w, c);
16 ✔
444
            e = b;
16 ✔
445
            e *= w;
16 ✔
446
            result.test_bn_eq("b *= word", e, c);
16 ✔
447
         }
448

449
         return result;
104 ✔
450
      }
104 ✔
451
};
452

453
BOTAN_REGISTER_TEST("math", "bn_mul", BigInt_Mul_Test);
454

455
class BigInt_Sqr_Test final : public Text_Based_Test {
×
456
   public:
457
      BigInt_Sqr_Test() : Text_Based_Test("bn/sqr.vec", "Input,Output") {}
2 ✔
458

459
      Test::Result run_one_test(const std::string& /*header*/, const VarMap& vars) override {
21 ✔
460
         Test::Result result("BigInt Square");
21 ✔
461

462
         const BigInt input = vars.get_req_bn("Input");
21 ✔
463
         const BigInt output = vars.get_req_bn("Output");
21 ✔
464

465
         result.test_bn_eq("a * a", input * input, output);
21 ✔
466
         result.test_bn_eq("sqr(a)", square(input), output);
21 ✔
467

468
         return result;
21 ✔
469
      }
21 ✔
470
};
471

472
BOTAN_REGISTER_TEST("math", "bn_sqr", BigInt_Sqr_Test);
473

474
class BigInt_Div_Test final : public Text_Based_Test {
×
475
   public:
476
      BigInt_Div_Test() : Text_Based_Test("bn/divide.vec", "In1,In2,Output") {}
2 ✔
477

478
      Test::Result run_one_test(const std::string& /*header*/, const VarMap& vars) override {
792 ✔
479
         Test::Result result("BigInt Divide");
792 ✔
480

481
         const BigInt a = vars.get_req_bn("In1");
792 ✔
482
         const BigInt b = vars.get_req_bn("In2");
792 ✔
483
         const BigInt c = vars.get_req_bn("Output");
792 ✔
484

485
         result.test_bn_eq("a / b", a / b, c);
792 ✔
486

487
         BigInt e = a;
792 ✔
488
         e /= b;
792 ✔
489
         result.test_bn_eq("a /= b", e, c);
792 ✔
490

491
         if(b.sig_words() == 1 && b.signum() >= 0) {
792 ✔
492
            const Botan::word bw = b.word_at(0);
405 ✔
493
            result.test_bn_eq("Low word correct", Botan::BigInt::from_word(bw), b);
405 ✔
494

495
            Botan::BigInt ct_q;
405 ✔
496
            Botan::word ct_r = 0;
405 ✔
497
            Botan::ct_divide_word(a, bw, ct_q, ct_r);
405 ✔
498
            result.test_bn_eq("ct_divide_word q", ct_q, c);
405 ✔
499
            result.test_bn_eq("ct_divide_word r", ct_q * b + ct_r, a);
810 ✔
500
         }
405 ✔
501

502
         Botan::BigInt ct_q;
792 ✔
503
         Botan::BigInt ct_r;
792 ✔
504
         Botan::ct_divide(a, b, ct_q, ct_r);
792 ✔
505
         result.test_bn_eq("ct_divide q", ct_q, c);
792 ✔
506
         result.test_bn_eq("ct_divide r", ct_q * b + ct_r, a);
792 ✔
507

508
         return result;
792 ✔
509
      }
792 ✔
510
};
511

512
BOTAN_REGISTER_TEST("math", "bn_div", BigInt_Div_Test);
513

514
class BigInt_CtDivide_Test final : public Test {
1 ✔
515
   public:
516
      std::vector<Test::Result> run() override {
1 ✔
517
         Test::Result result("BigInt ct_divide");
1 ✔
518

519
         for(size_t y_bits = 1; y_bits <= 384; y_bits += 5) {
78 ✔
520
            const BigInt y(rng(), y_bits, true);
77 ✔
521

522
            const size_t x_bit_choices[] = {1, y_bits / 2 + 1, y_bits, y_bits + 1, y_bits + 65, 2 * y_bits + 3};
77 ✔
523

524
            // Test some random inputs of varying sizes
525
            for(const size_t x_bits : x_bit_choices) {
539 ✔
526
               const BigInt x(rng(), x_bits, false);
462 ✔
527
               check_divide(result, x, y);
462 ✔
528
               check_divide(result, -x, y);
462 ✔
529
               check_divide(result, x, -y);
462 ✔
530
            }
462 ✔
531

532
            const BigInt q(rng(), y_bits + 64, false);
77 ✔
533
            check_divide(result, q * y, y);            // Exact multiple
77 ✔
534
            check_divide(result, q * y + 1, y);        // Smallest non-zero remainder
154 ✔
535
            check_divide(result, q * y + (y - 1), y);  // Largest possible remainder
77 ✔
536

537
            // Cases where x and y are related
538
            check_divide(result, (y << 64) - 1, y);
154 ✔
539
            check_divide(result, (y << 128) - 1, y);
154 ✔
540
            check_divide(result, y - 1, y);
77 ✔
541
            check_divide(result, y, y);
77 ✔
542
            check_divide(result, y + 1, y);
77 ✔
543

544
            const BigInt x(rng(), y_bits + 130, false);
77 ✔
545

546
            // Power of 2 and all-1s divisors
547
            check_divide(result, x, BigInt::power_of_2(y_bits));
77 ✔
548
            check_divide(result, x, BigInt::power_of_2(y_bits) - 1);
154 ✔
549

550
            // Word sized divisors including 1 and the maximum word
551
            check_divide(result, x, BigInt::one());
77 ✔
552
            check_divide(result, x, BigInt::from_word(~static_cast<Botan::word>(0)));
77 ✔
553
         }
77 ✔
554

555
         return {result};
3 ✔
556
      }
2 ✔
557

558
   private:
559
      static void check_divide(Test::Result& result, const BigInt& x, const BigInt& y) {
2,310 ✔
560
         BigInt q;
2,310 ✔
561
         BigInt r;
2,310 ✔
562
         Botan::ct_divide(x, y, q, r);
2,310 ✔
563

564
         result.test_bn_eq("ct_divide identity", q * y + r, x);
2,310 ✔
565
         result.test_is_true("ct_divide r >= 0", r.signum() >= 0);
2,310 ✔
566
         result.test_is_true("ct_divide r < |y|", r < y.abs());
4,620 ✔
567

568
         if(y.sig_words() == 1 && y.signum() > 0) {
2,310 ✔
569
            // Cross-check with ct_divide_word if possible
570
            const Botan::word yw = y.word_at(0);
440 ✔
571

572
            BigInt wq;
440 ✔
573
            Botan::word wr = 0;
440 ✔
574
            Botan::ct_divide_word(x, yw, wq, wr);
440 ✔
575
            result.test_bn_eq("ct_divide_word q", wq, q);
440 ✔
576
            result.test_bn_eq("ct_divide_word r", BigInt::from_word(wr), r);
440 ✔
577

578
            if(x.signum() >= 0) {
440 ✔
579
               result.test_bn_eq("ct_mod_word", BigInt::from_word(Botan::ct_mod_word(x, yw)), r);
374 ✔
580
            }
581
         }
440 ✔
582
      }
2,310 ✔
583
};
584

585
BOTAN_REGISTER_TEST("math", "bn_ct_divide", BigInt_CtDivide_Test);
586

587
class BigInt_DivPow2k_Test final : public Test {
1 ✔
588
   public:
589
      std::vector<Test::Result> run() override {
1 ✔
590
         Test::Result result("BigInt divide pow2k");
1 ✔
591

592
         for(size_t k = 2; k != 128; ++k) {
127 ✔
593
            testcase(k, 1, result);
126 ✔
594
            testcase(k, 2, result);
126 ✔
595
            testcase(k, 4, result);
126 ✔
596
         }
597

598
         for(size_t k = 4; k != 512; ++k) {
509 ✔
599
            const BigInt pow2k = BigInt::power_of_2(k);
508 ✔
600

601
            for(size_t y_bits = k / 2; y_bits <= (k + 2); ++y_bits) {
67,564 ✔
602
               const BigInt y(rng(), y_bits, false);
67,056 ✔
603
               if(y.is_zero()) {
134,112 ✔
604
                  continue;
1 ✔
605
               }
606

607
               testcase(k, y, result);
67,055 ✔
608
            }
67,056 ✔
609
         }
508 ✔
610

611
         return {result};
3 ✔
612
      }
2 ✔
613

614
   private:
615
      static void testcase(size_t k, const BigInt& y, Test::Result& result) {
67,433 ✔
616
         const BigInt q = ct_divide_pow2k(k, y);
67,433 ✔
617
         const BigInt r = BigInt::power_of_2(k) - q * y;
67,433 ✔
618

619
         result.test_is_true("ct_divide_pow2k r >= 0", r.signum() >= 0);
67,433 ✔
620
         result.test_is_true("ct_divide_pow2k r < y", r < y);
67,433 ✔
621
      }
67,433 ✔
622
};
623

624
BOTAN_REGISTER_TEST("math", "bn_div_pow2k", BigInt_DivPow2k_Test);
625

626
class BigInt_Mod_Test final : public Text_Based_Test {
×
627
   public:
628
      BigInt_Mod_Test() : Text_Based_Test("bn/mod.vec", "In1,In2,Output") {}
2 ✔
629

630
      Test::Result run_one_test(const std::string& /*header*/, const VarMap& vars) override {
80 ✔
631
         Test::Result result("BigInt Mod");
80 ✔
632

633
         const BigInt a = vars.get_req_bn("In1");
80 ✔
634
         const BigInt b = vars.get_req_bn("In2");
80 ✔
635
         const BigInt expected = vars.get_req_bn("Output");
80 ✔
636

637
         result.test_bn_eq("a % b", a % b, expected);
80 ✔
638

639
         BigInt e = a;
80 ✔
640
         e %= b;
80 ✔
641
         result.test_bn_eq("a %= b", e, expected);
80 ✔
642

643
         if(a.signum() >= 0 && a < (b * b)) {
80 ✔
644
            const auto mod_b_pub = Botan::Barrett_Reduction::for_public_modulus(b);
43 ✔
645
            result.test_bn_eq("Barrett public", mod_b_pub.reduce(a), expected);
43 ✔
646

647
            const auto mod_b_sec = Botan::Barrett_Reduction::for_secret_modulus(b);
43 ✔
648
            result.test_bn_eq("Barrett secret", mod_b_sec.reduce(a), expected);
43 ✔
649
         }
86 ✔
650

651
         // if b fits into a Botan::word test %= operator for words
652
         if(b.sig_words() == 1) {
80 ✔
653
            const Botan::word b_word = b.word_at(0);
34 ✔
654

655
            e = a;
34 ✔
656
            e %= b_word;
34 ✔
657
            result.test_bn_eq("a %= b (as word)", e, expected);
34 ✔
658

659
            result.test_bn_eq("a % b (as word)", a % b_word, expected);
34 ✔
660

661
            Botan::BigInt ct_q;
34 ✔
662
            Botan::word ct_r = 0;
34 ✔
663
            Botan::ct_divide_word(a, b.word_at(0), ct_q, ct_r);
68 ✔
664
            result.test_bn_eq("ct_divide_u8 r", ct_r, expected);
34 ✔
665
         }
34 ✔
666

667
         Botan::BigInt ct_q;
80 ✔
668
         Botan::BigInt ct_r;
80 ✔
669
         Botan::ct_divide(a, b, ct_q, ct_r);
80 ✔
670
         result.test_bn_eq("ct_divide r", ct_r, expected);
80 ✔
671

672
         return result;
80 ✔
673
      }
80 ✔
674
};
675

676
BOTAN_REGISTER_TEST("math", "bn_mod", BigInt_Mod_Test);
677

678
class Barrett_Redc_Test final : public Test {
1 ✔
679
   public:
680
      std::vector<Test::Result> run() override {
1 ✔
681
         Test::Result result("Barrett reduction");
1 ✔
682

683
         for(size_t t = 0; t != 10000; ++t) {
10,001 ✔
684
            const auto mod = [&]() {
30,000 ✔
685
               if(t <= 16) {
10,000 ✔
686
                  return BigInt::from_u64(t) + 1;
34 ✔
687
               } else {
688
                  const size_t bits = (t / 4) + 2;
9,983 ✔
689

690
                  if(t % 4 == 0) {
9,983 ✔
691
                     return BigInt::power_of_2(bits);
2,495 ✔
692
                  } else if(t % 4 == 1) {
7,488 ✔
693
                     return BigInt::power_of_2(bits) - 1;
4,992 ✔
694
                  } else if(t % 4 == 2) {
4,992 ✔
695
                     return BigInt::power_of_2(bits) + 1;
4,992 ✔
696
                  } else {
697
                     Botan::BigInt b;
2,496 ✔
698
                     b.randomize(rng(), bits, true);
2,496 ✔
699
                     return b;
2,496 ✔
700
                  }
2,496 ✔
701
               }
702
            }();
10,000 ✔
703

704
            const size_t mod_bits = mod.bits();
10,000 ✔
705
            const auto barrett = Botan::Barrett_Reduction::for_public_modulus(mod);
10,000 ✔
706

707
            for(size_t i = 0; i != 10; ++i) {
110,000 ✔
708
               const auto input = [&]() {
×
709
                  Botan::BigInt b;
100,000 ✔
710
                  b.randomize(rng(), 2 * mod_bits, false);
100,000 ✔
711
                  return b;
100,000 ✔
712
               }();
100,000 ✔
713

714
               const auto reduced_ref = input % mod;
100,000 ✔
715
               const auto reduced_barrett = barrett.reduce(input);
100,000 ✔
716

717
               result.test_bn_eq("Barrett reduction matches variable time division", reduced_barrett, reduced_ref);
100,000 ✔
718
            }
100,000 ✔
719
         }
10,000 ✔
720

721
         return {result};
3 ✔
722
      }
2 ✔
723
};
724

725
BOTAN_REGISTER_TEST("math", "barrett_redc", Barrett_Redc_Test);
726

727
class BigInt_GCD_Test final : public Text_Based_Test {
×
728
   public:
729
      BigInt_GCD_Test() : Text_Based_Test("bn/gcd.vec", "X,Y,GCD") {}
2 ✔
730

731
      Test::Result run_one_test(const std::string& /*header*/, const VarMap& vars) override {
182 ✔
732
         Test::Result result("BigInt GCD");
182 ✔
733

734
         const BigInt x = vars.get_req_bn("X");
182 ✔
735
         const BigInt y = vars.get_req_bn("Y");
182 ✔
736
         const BigInt expected = vars.get_req_bn("GCD");
182 ✔
737

738
         const BigInt g1 = Botan::gcd(x, y);
182 ✔
739
         result.test_bn_eq("gcd", g1, expected);
182 ✔
740

741
         const BigInt g2 = Botan::gcd(y, x);
182 ✔
742
         result.test_bn_eq("gcd", g2, expected);
182 ✔
743

744
         return result;
182 ✔
745
      }
182 ✔
746
};
747

748
BOTAN_REGISTER_TEST("math", "bn_gcd", BigInt_GCD_Test);
749

750
class BigInt_Jacobi_Test final : public Text_Based_Test {
×
751
   public:
752
      BigInt_Jacobi_Test() : Text_Based_Test("bn/jacobi.vec", "A,N,J") {}
2 ✔
753

754
      Test::Result run_one_test(const std::string& /*header*/, const VarMap& vars) override {
698 ✔
755
         Test::Result result("BigInt Jacobi");
698 ✔
756

757
         const BigInt a = vars.get_req_bn("A");
698 ✔
758
         const BigInt n = vars.get_req_bn("N");
698 ✔
759
         const std::string expected = vars.get_req_str("J");
698 ✔
760

761
         const int32_t j = Botan::jacobi(a, n);
698 ✔
762

763
         if(j == 0) {
698 ✔
764
            result.test_str_eq("jacobi", expected, "0");
157 ✔
765
         } else if(j == -1) {
541 ✔
766
            result.test_str_eq("jacobi", expected, "-1");
307 ✔
767
         } else {
768
            result.test_str_eq("jacobi", expected, "1");
234 ✔
769
         }
770

771
         return result;
1,396 ✔
772
      }
698 ✔
773
};
774

775
BOTAN_REGISTER_TEST("math", "bn_jacobi", BigInt_Jacobi_Test);
776

777
class BigInt_Lshift_Test final : public Text_Based_Test {
×
778
   public:
779
      BigInt_Lshift_Test() : Text_Based_Test("bn/lshift.vec", "Value,Shift,Output") {}
2 ✔
780

781
      Test::Result run_one_test(const std::string& /*header*/, const VarMap& vars) override {
51 ✔
782
         Test::Result result("BigInt Lshift");
51 ✔
783

784
         const BigInt value = vars.get_req_bn("Value");
51 ✔
785
         const size_t shift = vars.get_req_bn("Shift").to_u32bit();
51 ✔
786
         const BigInt output = vars.get_req_bn("Output");
51 ✔
787

788
         result.test_bn_eq("a << s", value << shift, output);
51 ✔
789

790
         BigInt e = value;
51 ✔
791
         e <<= shift;
51 ✔
792
         result.test_bn_eq("a <<= s", e, output);
51 ✔
793

794
         return result;
51 ✔
795
      }
51 ✔
796
};
797

798
BOTAN_REGISTER_TEST("math", "bn_lshift", BigInt_Lshift_Test);
799

800
class BigInt_Rshift_Test final : public Text_Based_Test {
×
801
   public:
802
      BigInt_Rshift_Test() : Text_Based_Test("bn/rshift.vec", "Value,Shift,Output") {}
2 ✔
803

804
      Test::Result run_one_test(const std::string& /*header*/, const VarMap& vars) override {
54 ✔
805
         Test::Result result("BigInt Rshift");
54 ✔
806

807
         const BigInt value = vars.get_req_bn("Value");
54 ✔
808
         const size_t shift = vars.get_req_bn("Shift").to_u32bit();
54 ✔
809
         const BigInt output = vars.get_req_bn("Output");
54 ✔
810

811
         result.test_bn_eq("a >> s", value >> shift, output);
54 ✔
812

813
         BigInt e = value;
54 ✔
814
         e >>= shift;
54 ✔
815
         result.test_bn_eq("a >>= s", e, output);
54 ✔
816

817
         return result;
54 ✔
818
      }
54 ✔
819
};
820

821
BOTAN_REGISTER_TEST("math", "bn_rshift", BigInt_Rshift_Test);
822

823
Test::Result test_const_time_left_shift() {
1 ✔
824
   Test::Result result("BigInt const time shift");
1 ✔
825
   const size_t bits = Test::run_long_tests() ? 4096 : 2048;
1 ✔
826

827
   auto rng = Test::new_rng("const_time_left_shift");
1 ✔
828

829
   result.start_timer();
1 ✔
830

831
   Botan::BigInt a = Botan::BigInt::with_capacity(bits / sizeof(Botan::word));
1 ✔
832
   for(size_t i = 0; i < bits; ++i) {
4,097 ✔
833
      if(rng->next_byte() % 2 == 1) {
4,096 ✔
834
         a.set_bit(i);
4,096 ✔
835
      }
836
   }
837

838
   for(size_t i = 0; i < bits; ++i) {
4,097 ✔
839
      auto ct = a;
4,096 ✔
840
      auto chk = a;
4,096 ✔
841
      Botan::CT::poison(ct);
4,096 ✔
842
      ct.ct_shift_left(i);
4,096 ✔
843
      Botan::CT::unpoison(ct);
4,096 ✔
844
      chk <<= i;
4,096 ✔
845
      result.test_bn_eq(Botan::fmt("ct << {}", i), ct, chk);
4,096 ✔
846
   }
4,096 ✔
847

848
   result.end_timer();
1 ✔
849

850
   return result;
2 ✔
851
}
2 ✔
852

853
class BigInt_Powmod_Test final : public Text_Based_Test {
×
854
   public:
855
      BigInt_Powmod_Test() : Text_Based_Test("bn/powmod.vec", "Base,Exponent,Modulus,Output") {}
2 ✔
856

857
      Test::Result run_one_test(const std::string& /*header*/, const VarMap& vars) override {
138 ✔
858
         Test::Result result("BigInt Powmod");
138 ✔
859

860
         const BigInt base = vars.get_req_bn("Base");
138 ✔
861
         const BigInt exponent = vars.get_req_bn("Exponent");
138 ✔
862
         const BigInt modulus = vars.get_req_bn("Modulus");
138 ✔
863
         const BigInt expected = vars.get_req_bn("Output");
138 ✔
864

865
         result.test_bn_eq("power_mod", Botan::power_mod(base, exponent, modulus), expected);
138 ✔
866
         return result;
138 ✔
867
      }
138 ✔
868
};
869

870
BOTAN_REGISTER_TEST("math", "bn_powmod", BigInt_Powmod_Test);
871

872
class BigInt_IsPrime_Test final : public Text_Based_Test {
×
873
   public:
874
      BigInt_IsPrime_Test() : Text_Based_Test("bn/isprime.vec", "X") {}
2 ✔
875

876
      Test::Result run_one_test(const std::string& header, const VarMap& vars) override {
132 ✔
877
         if(header != "Prime" && header != "NonPrime") {
132 ✔
878
            throw Test_Error("Bad header for prime test " + header);
×
879
         }
880

881
         const BigInt value = vars.get_req_bn("X");
132 ✔
882
         const bool is_prime = (header == "Prime");
132 ✔
883

884
         Test::Result result("BigInt Test " + header);
132 ✔
885
         result.test_bool_eq("is_prime", Botan::is_prime(value, this->rng()), is_prime);
132 ✔
886
         result.test_bool_eq("is_prime_vartime", Botan::is_prime_vartime(value, this->rng(), 64, false), is_prime);
132 ✔
887

888
         if(value > 2 && value.is_odd()) {
261 ✔
889
            const Botan::Montgomery_Params monty(value);
128 ✔
890
            result.test_bool_eq(
128 ✔
891
               "is_bailie_psw_probable_prime", Botan::is_bailie_psw_probable_prime(value, monty), is_prime);
128 ✔
892
            result.test_bool_eq("is_bailie_psw_probable_prime_vartime",
128 ✔
893
                                Botan::is_bailie_psw_probable_prime_vartime(value, monty),
128 ✔
894
                                is_prime);
895

896
            if(is_prime) {
128 ✔
897
               result.test_is_true("Prime passes Miller-Rabin base 2",
24 ✔
898
                                   Botan::is_miller_rabin_base2_probable_prime(value, monty));
24 ✔
899
            }
900
         }
128 ✔
901

902
         return result;
132 ✔
903
      }
132 ✔
904
};
905

906
BOTAN_REGISTER_TEST("math", "bn_isprime", BigInt_IsPrime_Test);
907

908
class BigInt_ModSmallPrimes_Test final : public Test {
1 ✔
909
   public:
910
      std::vector<Test::Result> run() override {
1 ✔
911
         Test::Result result("BigInt mod_small_primes");
1 ✔
912

913
         result.start_timer();
1 ✔
914

915
         for(const size_t bits : {1, 16, 17, 31, 64, 100, 256, 1024, 2048}) {
10 ✔
916
            const Botan::BigInt n(this->rng(), bits);
9 ✔
917

918
            for(const size_t num_primes : {100, 6541}) {
27 ✔
919
               const auto residues = Botan::mod_small_primes(n, num_primes);
18 ✔
920

921
               bool all_ok = result.test_sz_eq("expected number of residues", residues.size(), num_primes);
18 ✔
922

923
               for(size_t i = 0; i != residues.size(); ++i) {
59,787 ✔
924
                  const Botan::word ref = n % Botan::PRIMES[i];
59,769 ✔
925
                  if(residues[i] != ref) {
59,769 ✔
926
                     result.test_failure(Botan::fmt("Wrong residue of {} mod {}", n.to_hex_string(), Botan::PRIMES[i]));
×
927
                     all_ok = false;
×
928
                  }
929
               }
930

931
               if(all_ok) {
18 ✔
932
                  result.test_success(Botan::fmt("Correct residues of a {} bit integer", bits));
36 ✔
933
               }
934
            }
18 ✔
935
         }
9 ✔
936

937
         std::vector<uint64_t> values = {
1 ✔
938
            0, 1, 2, 65520, 65521, 0xFFFFFFFF, 0x100000000, 0x1FFFFFFFF, ~uint64_t(0), ~uint64_t(0) - 3};
1 ✔
939
         for(size_t i = 0; i != 16; ++i) {
17 ✔
940
            values.push_back(Botan::load_le<uint64_t>(this->rng().random_array<8>()));
16 ✔
941
         }
942

943
         for(const uint64_t x : values) {
27 ✔
944
            const auto residues = Botan::mod_small_primes(x, 6541);
26 ✔
945

946
            bool all_ok = result.test_sz_eq("expected number of residues", residues.size(), 6541);
26 ✔
947

948
            for(size_t i = 0; i != residues.size(); ++i) {
170,092 ✔
949
               if(residues[i] != x % Botan::PRIMES[i]) {
170,066 ✔
950
                  result.test_failure(Botan::fmt("Wrong residue of {} mod {}", x, Botan::PRIMES[i]));
×
951
                  all_ok = false;
×
952
               }
953
            }
954

955
            if(all_ok) {
26 ✔
956
               result.test_success(Botan::fmt("Correct residues of {}", x));
52 ✔
957
            }
958
         }
26 ✔
959

960
         result.end_timer();
1 ✔
961

962
         return {result};
3 ✔
963
      }
2 ✔
964
};
965

966
BOTAN_REGISTER_TEST("math", "bn_mod_small_primes", BigInt_ModSmallPrimes_Test);
967

968
class BigInt_IsSquare_Test final : public Text_Based_Test {
×
969
   public:
970
      BigInt_IsSquare_Test() : Text_Based_Test("bn/perfect_square.vec", "X,R") {}
2 ✔
971

972
      Test::Result run_one_test(const std::string& /*header*/, const VarMap& vars) override {
7 ✔
973
         const BigInt value = vars.get_req_bn("X");
7 ✔
974
         const BigInt expected = vars.get_req_bn("R");
7 ✔
975
         const BigInt computed = Botan::is_perfect_square(value);
7 ✔
976

977
         Test::Result result("BigInt IsSquare");
7 ✔
978
         result.test_bn_eq("is_perfect_square", computed, expected);
7 ✔
979
         return result;
7 ✔
980
      }
7 ✔
981
};
982

983
BOTAN_REGISTER_TEST("math", "bn_issquare", BigInt_IsSquare_Test);
984

985
class BigInt_IsSquare_Random_Test final : public Test {
1 ✔
986
   public:
987
      std::vector<Test::Result> run() override {
1 ✔
988
         Test::Result result("BigInt IsSquare random");
1 ✔
989

990
         for(uint32_t x = 1; x <= (1 << 14); ++x) {
16,385 ✔
991
            uint32_t root = 0;
992
            while((root + 1) * (root + 1) <= x) {
1,406,400 ✔
993
               ++root;
994
            }
995
            const uint32_t expected = (root * root == x) ? root : 0;
16,384 ✔
996
            result.test_bn_eq(
16,384 ✔
997
               "is_perfect_square small", Botan::is_perfect_square(BigInt::from_u64(x)), BigInt::from_u64(expected));
32,768 ✔
998
         }
999

1000
         for(size_t bits = 1; bits <= 400; ++bits) {
401 ✔
1001
            const BigInt r(this->rng(), bits);
400 ✔
1002
            const BigInt x = r * r;
400 ✔
1003

1004
            result.test_bn_eq("is_perfect_square r^2", Botan::is_perfect_square(x), r);
400 ✔
1005
            result.test_bn_eq("is_perfect_square r^2 + 1", Botan::is_perfect_square(x + 1), BigInt::zero());
400 ✔
1006
            result.test_bn_eq("is_perfect_square r^2 + 2r", Botan::is_perfect_square(x + 2 * r), BigInt::zero());
400 ✔
1007
            if(x > 1) {
400 ✔
1008
               result.test_bn_eq("is_perfect_square r^2 - 1", Botan::is_perfect_square(x - 1), BigInt::zero());
399 ✔
1009
            }
1010
         }
400 ✔
1011

1012
         return {result};
3 ✔
1013
      }
2 ✔
1014
};
1015

1016
BOTAN_REGISTER_TEST("math", "bn_issquare_random", BigInt_IsSquare_Random_Test);
1017

1018
class BigInt_Sqrt_Modulo_Prime_Test final : public Text_Based_Test {
×
1019
   public:
1020
      BigInt_Sqrt_Modulo_Prime_Test() : Text_Based_Test("bn/sqrt_modulo_prime.vec", "Input,Modulus,Output") {}
2 ✔
1021

1022
      Test::Result run_one_test(const std::string& /*header*/, const VarMap& vars) override {
165 ✔
1023
         Test::Result result("BigInt Sqrt Modulo Prime");
165 ✔
1024

1025
         const Botan::BigInt a = vars.get_req_bn("Input");
165 ✔
1026
         const Botan::BigInt p = vars.get_req_bn("Modulus");
165 ✔
1027
         const Botan::BigInt exp = vars.get_req_bn("Output");
165 ✔
1028

1029
         const Botan::BigInt a_sqrt = Botan::sqrt_modulo_prime(a, p);
165 ✔
1030

1031
         // Either square root is acceptable
1032
         if(exp.signum() > 0 && a_sqrt == p - exp) {
165 ✔
1033
            result.test_bn_eq("sqrt_modulo_prime", a_sqrt, p - exp);
63 ✔
1034
         } else {
1035
            result.test_bn_eq("sqrt_modulo_prime", a_sqrt, exp);
102 ✔
1036
         }
1037

1038
         if(a_sqrt > 1) {
165 ✔
1039
            const Botan::BigInt a_sqrt2 = (a_sqrt * a_sqrt) % p;
122 ✔
1040
            result.test_bn_eq("square correct", a_sqrt2, a);
122 ✔
1041
         }
122 ✔
1042

1043
         return result;
165 ✔
1044
      }
165 ✔
1045
};
1046

1047
BOTAN_REGISTER_TEST("math", "bn_sqrt_modulo_prime", BigInt_Sqrt_Modulo_Prime_Test);
1048

1049
class BigInt_Sqrt_Modulo_Prime_Exhaustive_Test final : public Test {
1 ✔
1050
   public:
1051
      std::vector<Test::Result> run() override {
1 ✔
1052
         Test::Result result("BigInt Sqrt Modulo Prime exhaustive");
1 ✔
1053

1054
         const auto is_prime = [](uint32_t n) {
1 ✔
1055
            for(uint32_t d = 2; d * d <= n; ++d) {
5,643 ✔
1056
               if(n % d == 0) {
5,471 ✔
1057
                  return false;
1058
               }
1059
            }
1060
            return n >= 2;
172 ✔
1061
         };
1062

1063
         for(uint32_t p = 2; p < 1024; ++p) {
1,023 ✔
1064
            if(!is_prime(p)) {
1,022 ✔
1065
               continue;
850 ✔
1066
            }
1067

1068
            std::vector<bool> is_square(p);
172 ✔
1069
            for(uint32_t x = 0; x != p; ++x) {
80,361 ✔
1070
               is_square[(x * x) % p] = true;
80,189 ✔
1071
            }
1072

1073
            const BigInt p_bn = BigInt::from_u64(p);
172 ✔
1074

1075
            for(uint32_t a = 0; a != p; ++a) {
80,361 ✔
1076
               const BigInt r = Botan::sqrt_modulo_prime(BigInt::from_u64(a), p_bn);
80,189 ✔
1077

1078
               bool ok = false;
80,189 ✔
1079
               if(is_square[a]) {
80,189 ✔
1080
                  ok = r.signum() >= 0 && r < p_bn && (r * r) % p_bn == a;
80,362 ✔
1081
               } else {
1082
                  ok = (r == BigInt::from_s32(-1));
80,016 ✔
1083
               }
1084

1085
               if(!result.test_is_true("sqrt_modulo_prime result", ok)) {
80,189 ✔
1086
                  result.test_note(Botan::fmt("a = {} p = {} returned {}", a, p, r.to_dec_string()));
×
1087
               }
1088
            }
80,189 ✔
1089
         }
172 ✔
1090

1091
         return {result};
3 ✔
1092
      }
2 ✔
1093
};
1094

1095
BOTAN_REGISTER_TEST("math", "bn_sqrt_modulo_prime_exhaustive", BigInt_Sqrt_Modulo_Prime_Exhaustive_Test);
1096

1097
class BigInt_InvMod_Test final : public Text_Based_Test {
×
1098
   public:
1099
      BigInt_InvMod_Test() : Text_Based_Test("bn/invmod.vec", "Input,Modulus,Output") {}
2 ✔
1100

1101
      Test::Result run_one_test(const std::string& /*header*/, const VarMap& vars) override {
147 ✔
1102
         Test::Result result("BigInt InvMod");
147 ✔
1103

1104
         const Botan::BigInt a = vars.get_req_bn("Input");
147 ✔
1105
         const Botan::BigInt mod = vars.get_req_bn("Modulus");
147 ✔
1106
         const Botan::BigInt expected = vars.get_req_bn("Output");
147 ✔
1107

1108
         result.test_bn_eq("inverse_mod", Botan::inverse_mod(a, mod), expected);
147 ✔
1109

1110
         if(a < mod && a > 0 && a < mod) {
425 ✔
1111
            auto g = Botan::inverse_mod_general(a, mod);
137 ✔
1112
            if(g.has_value()) {
137 ✔
1113
               result.test_bn_eq("inverse_mod_general", g.value(), expected);
95 ✔
1114
               result.test_bn_eq("inverse works", ((g.value() * a) % mod), BigInt::one());
190 ✔
1115
            } else {
1116
               result.test_is_true("inverse_mod_general", expected.is_zero());
84 ✔
1117
            }
1118

1119
            if(Botan::is_prime(mod, rng()) && mod != 2) {
145 ✔
1120
               BOTAN_ASSERT_NOMSG(expected > 0);
7 ✔
1121
               result.test_bn_eq("inverse_mod_secret_prime", Botan::inverse_mod_secret_prime(a, mod), expected);
7 ✔
1122
               result.test_bn_eq("inverse_mod_public_prime", Botan::inverse_mod_public_prime(a, mod), expected);
7 ✔
1123
            }
1124
         }
137 ✔
1125

1126
         return result;
147 ✔
1127
      }
147 ✔
1128
};
1129

1130
BOTAN_REGISTER_TEST("math", "bn_invmod", BigInt_InvMod_Test);
1131

1132
class BigInt_InvMod_Random_Test final : public Test {
1 ✔
1133
   public:
1134
      std::vector<Test::Result> run() override {
1 ✔
1135
         Test::Result result("BigInt InvMod random");
1 ✔
1136

1137
         for(const size_t bits : {8,   31,  32,  33,  63,   64,   65,   127,  128,  129,  255, 256,
23 ✔
1138
                                  257, 511, 512, 513, 1023, 1024, 1025, 2047, 2048, 3072, 4096}) {
24 ✔
1139
            for(size_t trial = 0; trial != 8; ++trial) {
207 ✔
1140
               Botan::BigInt mod(rng(), bits);
184 ✔
1141
               if(trial % 2 == 0) {
184 ✔
1142
                  mod.set_bit(0);
92 ✔
1143
               } else {
1144
                  mod.clear_bit(0);
92 ✔
1145
               }
1146
               if(mod < 3) {
184 ✔
1147
                  mod = 3;
×
1148
               }
1149

1150
               const std::vector<Botan::BigInt> inputs = {
184 ✔
1151
                  Botan::BigInt::one(),
1152
                  mod - 1,
1153
                  mod >> 1,
1154
                  Botan::BigInt(rng(), bits) % mod,
368 ✔
1155
               };
920 ✔
1156

1157
               for(const auto& a : inputs) {
920 ✔
1158
                  const Botan::BigInt inv = Botan::inverse_mod(a, mod);
736 ✔
1159

1160
                  if(Botan::gcd(a, mod) == 1) {
1,472 ✔
1161
                     result.test_bn_eq("inverse works", (inv * a) % mod, Botan::BigInt::one());
574 ✔
1162
                     result.test_is_true("inverse in range", inv > 0 && inv < mod);
1,148 ✔
1163
                  } else {
1164
                     result.test_bn_eq("no inverse exists", inv, Botan::BigInt::zero());
162 ✔
1165
                  }
1166
               }
736 ✔
1167
            }
184 ✔
1168
         }
1169

1170
         return {result};
3 ✔
1171
      }
370 ✔
1172
};
1173

1174
BOTAN_REGISTER_TEST("math", "bn_invmod_random", BigInt_InvMod_Random_Test);
1175

1176
class BigInt_Rand_Test final : public Text_Based_Test {
×
1177
   public:
1178
      BigInt_Rand_Test() : Text_Based_Test("bn/random.vec", "Seed,Min,Max,Output") {}
2 ✔
1179

1180
      Test::Result run_one_test(const std::string& /*header*/, const VarMap& vars) override {
4 ✔
1181
         Test::Result result("BigInt Random");
4 ✔
1182

1183
         const std::vector<uint8_t> seed = vars.get_req_bin("Seed");
4 ✔
1184
         const Botan::BigInt min = vars.get_req_bn("Min");
4 ✔
1185
         const Botan::BigInt max = vars.get_req_bn("Max");
4 ✔
1186
         const Botan::BigInt expected = vars.get_req_bn("Output");
4 ✔
1187

1188
         Fixed_Output_RNG rng(seed);
4 ✔
1189
         const Botan::BigInt generated = BigInt::random_integer(rng, min, max);
4 ✔
1190

1191
         result.test_bn_eq("random_integer KAT", generated, expected);
4 ✔
1192

1193
         return result;
4 ✔
1194
      }
4 ✔
1195
};
1196

1197
BOTAN_REGISTER_TEST("math", "bn_rand", BigInt_Rand_Test);
1198

1199
class Miller_Rabin_Base2_Test final : public Test {
1 ✔
1200
   public:
1201
      std::vector<Test::Result> run() override {
1 ✔
1202
         const uint32_t max = (Test::run_long_tests() ? 100000 : 10000) + 1;
1 ✔
1203

1204
         // OEIS A001262
1205
         const std::set<uint32_t> strong_pp{
1 ✔
1206
            2047,
1207
            3277,
1208
            4033,
1209
            4681,
1210
            8321,
1211
            15841,
1212
            29341,
1213
            42799,
1214
            49141,
1215
            52633,
1216
            65281,
1217
            74665,
1218
            80581,
1219
            85489,
1220
            88357,
1221
            90751,
1222
         };
1 ✔
1223

1224
         Test::Result result("Miller-Rabin base 2 test");
1 ✔
1225

1226
         for(uint32_t i = 3; i <= max; i += 2) {
50,001 ✔
1227
            const auto i_bn = Botan::BigInt::from_word(i);
50,000 ✔
1228
            const Botan::Montgomery_Params monty_i(i_bn);
50,000 ✔
1229
            const bool passes = Botan::is_miller_rabin_base2_probable_prime(i_bn, monty_i);
50,000 ✔
1230
            const bool is_prime = Botan::is_prime(i_bn, this->rng());
50,000 ✔
1231

1232
            if(is_prime) {
50,000 ✔
1233
               result.test_is_true("Prime passes base 2 test", passes);
9,591 ✔
1234
            } else {
1235
               result.test_bool_eq("Composite passes only if a strong pseudoprime", passes, strong_pp.contains(i));
80,818 ✔
1236
            }
1237
         }
50,000 ✔
1238

1239
         return {result};
2 ✔
1240
      }
2 ✔
1241
};
1242

1243
BOTAN_REGISTER_TEST("math", "miller_rabin_base2", Miller_Rabin_Base2_Test);
1244

1245
class Lucas_Primality_Test final : public Test {
1 ✔
1246
   public:
1247
      std::vector<Test::Result> run() override {
1 ✔
1248
         const uint32_t lucas_max = (Test::run_long_tests() ? 100000 : 10000) + 1;
1 ✔
1249

1250
         // OEIS A217120
1251
         const std::set<uint32_t> lucas_pp{
1 ✔
1252
            323,   377,   1159,  1829,  3827,  5459,  5777,  9071,  9179,  10877, 11419, 11663, 13919, 14839, 16109,
1253
            16211, 18407, 18971, 19043, 22499, 23407, 24569, 25199, 25877, 26069, 27323, 32759, 34943, 35207, 39059,
1254
            39203, 39689, 40309, 44099, 46979, 47879, 50183, 51983, 53663, 56279, 58519, 60377, 63881, 69509, 72389,
1255
            73919, 75077, 77219, 79547, 79799, 82983, 84419, 86063, 90287, 94667, 97019, 97439,
1256
         };
1 ✔
1257

1258
         Test::Result result("Lucas primality test");
1 ✔
1259

1260
         for(uint32_t i = 3; i <= lucas_max; i += 2) {
50,001 ✔
1261
            const auto i_bn = Botan::BigInt::from_word(i);
50,000 ✔
1262
            const Botan::Montgomery_Params monty_i(i_bn);
50,000 ✔
1263
            const bool passes_lucas = Botan::is_lucas_probable_prime(i_bn, monty_i);
50,000 ✔
1264
            const bool is_prime = Botan::is_prime(i_bn, this->rng());
50,000 ✔
1265

1266
            result.test_bool_eq(
50,000 ✔
1267
               "Lucas vartime test agrees", Botan::is_lucas_probable_prime_vartime(i_bn, monty_i), passes_lucas);
50,000 ✔
1268

1269
            const bool is_lucas_pp = (is_prime == false && passes_lucas == true);
50,000 ✔
1270

1271
            if(is_lucas_pp) {
50,000 ✔
1272
               result.test_is_true("Lucas pseudoprime is in list", lucas_pp.contains(i));
114 ✔
1273
            } else {
1274
               result.test_is_true("Lucas non-pseudoprime is not in list", !lucas_pp.contains(i));
99,886 ✔
1275
            }
1276
         }
50,000 ✔
1277

1278
         /*
1279
         * Values of the form 1 + k*4*(product of odd primes up to 131, 259 or
1280
         * 515), so that (D/n) == 1 for every D up to that bound. Includes
1281
         * primes, composites, and squares.
1282
         */
1283
         const std::vector<std::pair<const char*, bool>> large_d = {
1 ✔
1284
            {"0xAE4B49E43FD9905611CAF877C712E60AF12A21DEFBA9", true},
1285
            {"0x9CF1ED19D5C15DFF23AF4E2DEC621DD5C36F48BB518B276FBC8778032988F20ED164860986900AD09549B081", false},
1286
            {"0x76AA6E96A7DD219B726554163C183C058747A761EC7C1C9F0AB712E648DA31FE4511CE184CAE048F0280D591", false},
1287
            {"0xCE7AA76E014CD3795A5C326A0921E38DECF32E583CEB73CB97C4C09DD37DCFCC7F309D26E675B666B0770A9", true},
1288
            {"0x158F882BF50A22587DFB18880A975246EC52CD84FBC15B58E3224BFE4F9A998DAF229AB0362D8A89CA0232380E7FC064CD98EEEFECF3EBE73DD1C175F7949CC9581173C19500ABCFD9D454BB22CACAF714A0F6B91503E65",
1289
             false},
1290
            {"0xA689A0390C719688370641E5D6388D2CA5CF0752A16B9570C8C24AFBC7F9993D8F639059E9192542C8E4D35F6367E840BA68874CD4456FEC176CA4490FA7E24E8EC2454005D43D075729D36DFD3522A4C32510A0D24F91",
1291
             false},
1292
            {"0x2E55A630473962F3FE8B8DF41F2377C7523C781DF01C1F181D241A8A043569A22BFB4D121B9F51CD1C9B9EDFB05AFE38C1771D32908AF13BEE9DA3EC829034DEF53D31143E0EA50DDCF2B8FF75C7799A99252CBD79B04985CD",
1293
             true},
1294
            {"0x1015CF3833BE3C28D5AFF708219A4D342445F331B2980B4E7814FAB6641A88E86BDCF9CF78AE8BD6093B2232A062F024170422285B1946E5394DF79D1E56927682C71E50125629C7F2D426B7A17D45986E98EC11E25177F2C6D6F6C4F3F6D1BF00853D98FC6791338F809F9385F7A8C86F087260A495BB5707D6F1D7D7A209946D0F0E62ECB0C3FACCDCB687F3D4BD01F826F0F51412EEA2E5216AA1D76B62CD7D0D7D66AC770B6FB4D6111169491CB42CC9",
1295
             false},
1296
            {"0x862E461218A91249B2B9B0CFDD3BAD98B40EA01D7A49AAE619D8947063DF89C2F7BF63577CEF7F2DF9DBC7F0B6A48B05AC4E3DC26BE68CAA7B90F51EA9EE9E6442EECCBA9495DFD0872FC1E191E4DDB81DDF36BC923E9342EDDC618B08F14DB264925A535B47D7FF8FD04ED3E4B9137EDE8C77169EB6E1C1B01D58CAB6A744236621FA930DC5476F7C05AE9A474A50B76ADE58607B3937D8CD7C248DC7682BA22A31C64810B39AD5521EEEE5AE174D8A629",
1297
             false},
1298
            // Primes with D = 509 and D = 521, the closest possible values on
1299
            // either side of the end of the first block of 256 candidates
1300
            {"0x244AF82885071CF8235622191C56EA2247639CEB9C6319FACBBCEF045BA67A22994B331BD003D204B686C5DF62E5B16256384FECE6CA93946E7CCFD8DB3704165E6B715942CE098415D99561C02CE74AEDF112BE589AC515",
1301
             true},
1302
            {"0x58DF0832A1CA65AA059A5BD0095D357A1BA22556CC89DF4FD32C115442D38FDAB9145D444E292FC85CA430B9A1FE43EEF52BCF157190CA7F8AB8D9E302D171FF933A9D1609E9BA7B1D4B41421CA8911BEF2E1F4173E50286ED",
1303
             true},
1304
         };
1 ✔
1305

1306
         for(const auto& [hex, expected] : large_d) {
12 ✔
1307
            const Botan::BigInt n(hex);
11 ✔
1308
            const Botan::Montgomery_Params monty_n(n);
11 ✔
1309
            result.test_bool_eq("Lucas test with large D", Botan::is_lucas_probable_prime(n, monty_n), expected);
11 ✔
1310
            result.test_bool_eq(
11 ✔
1311
               "Lucas vartime test with large D", Botan::is_lucas_probable_prime_vartime(n, monty_n), expected);
11 ✔
1312
         }
11 ✔
1313

1314
         return {result};
2 ✔
1315
      }
2 ✔
1316
};
1317

1318
BOTAN_REGISTER_TEST("math", "bn_lucas", Lucas_Primality_Test);
1319

1320
class RSA_Compute_Exp_Test : public Test {
1 ✔
1321
   public:
1322
      std::vector<Test::Result> run() override {
1 ✔
1323
         const size_t iter = 4000;
1 ✔
1324

1325
         Test::Result result("RSA compute exponent");
1 ✔
1326

1327
         const auto e = Botan::BigInt::from_u64(65537);
1 ✔
1328

1329
         /*
1330
         * Rather than create a fresh p/q for each iteration this test creates
1331
         * a pool of primes then selects 2 at random as p/q
1332
         */
1333

1334
         const auto random_primes = [&]() {
3 ✔
1335
            std::vector<Botan::BigInt> rp;
1 ✔
1336
            for(size_t i = 0; i != iter / 10; ++i) {
401 ✔
1337
               const size_t bits = (128 + (i % 1024)) % 4096;
400 ✔
1338
               const auto p = Botan::random_prime(rng(), bits);
400 ✔
1339
               if(gcd(p - 1, e) == 1) {
800 ✔
1340
                  rp.push_back(p);
400 ✔
1341
               }
1342
            }
400 ✔
1343
            return rp;
1 ✔
1344
         }();
1 ✔
1345

1346
         for(size_t i = 0; i != iter; ++i) {
4,001 ✔
1347
            const size_t p_idx = random_index(rng(), random_primes.size());
4,000 ✔
1348
            const size_t q_idx = random_index(rng(), random_primes.size());
4,000 ✔
1349

1350
            if(p_idx == q_idx) {
4,000 ✔
1351
               continue;
13 ✔
1352
            }
1353

1354
            const auto& p = random_primes[p_idx];
3,987 ✔
1355
            const auto& q = random_primes[q_idx];
3,987 ✔
1356

1357
            const auto phi_n = lcm(p - 1, q - 1);
3,987 ✔
1358

1359
            const auto d = Botan::compute_rsa_secret_exponent(e, phi_n, p, q);
3,987 ✔
1360

1361
            if(!result.test_is_true("compute_rsa_secret_exponent found an inverse", d.has_value())) {
3,987 ✔
1362
               continue;
×
1363
            }
1364

1365
            const auto ed_mod_phi_n = (e * *d) % phi_n;
3,987 ✔
1366

1367
            result.test_bn_eq("compute_rsa_secret_exponent returned inverse", ed_mod_phi_n, Botan::BigInt::one());
3,987 ✔
1368
         }
7,974 ✔
1369

1370
         return {result};
3 ✔
1371
      }
2 ✔
1372
};
1373

1374
BOTAN_REGISTER_TEST("math", "rsa_compute_d", RSA_Compute_Exp_Test);
1375

1376
class DSA_ParamGen_Test final : public Text_Based_Test {
×
1377
   public:
1378
      DSA_ParamGen_Test() : Text_Based_Test("bn/dsa_gen.vec", "P,Q,Counter,Seed") {}
2 ✔
1379

1380
      Test::Result run_one_test(const std::string& header, const VarMap& vars) override {
20 ✔
1381
         const std::vector<uint8_t> seed = vars.get_req_bin("Seed");
20 ✔
1382
         const size_t offset = vars.get_req_sz("Counter");
20 ✔
1383

1384
         const Botan::BigInt exp_P = vars.get_req_bn("P");
20 ✔
1385
         const Botan::BigInt exp_Q = vars.get_req_bn("Q");
20 ✔
1386

1387
         const std::vector<std::string> header_parts = Botan::split_on(header, ',');
20 ✔
1388

1389
         if(header_parts.size() != 2) {
20 ✔
1390
            throw Test_Error("Unexpected header '" + header + "' in DSA param gen test");
×
1391
         }
1392

1393
         const size_t p_bits = Botan::to_u32bit(header_parts[1]);
20 ✔
1394
         const size_t q_bits = Botan::to_u32bit(header_parts[0]);
20 ✔
1395

1396
         Test::Result result("DSA Parameter Generation");
20 ✔
1397

1398
         try {
20 ✔
1399
            Botan::BigInt gen_P;
20 ✔
1400
            Botan::BigInt gen_Q;
20 ✔
1401
            if(Botan::generate_dsa_primes(this->rng(), gen_P, gen_Q, p_bits, q_bits, seed, offset)) {
20 ✔
1402
               result.test_bn_eq("P", gen_P, exp_P);
20 ✔
1403
               result.test_bn_eq("Q", gen_Q, exp_Q);
20 ✔
1404
            } else {
1405
               result.test_failure("Seed did not generate a DSA parameter");
×
1406
            }
1407
         } catch(Botan::Lookup_Error&) {}
20 ✔
1408

1409
         return result;
20 ✔
1410
      }
20 ✔
1411
};
1412

1413
BOTAN_REGISTER_TEST("math", "dsa_param", DSA_ParamGen_Test);
1414

1415
std::vector<Test::Result> test_bigint_serialization() {
1 ✔
1416
   auto rng = Test::new_rng("test_bigint_serialization");
1 ✔
1417

1418
   return {
1 ✔
1419
      CHECK("BigInt binary serialization",
1420
            [](Test::Result& res) {
1 ✔
1421
               Botan::BigInt a(0x1234567890ABCDEF);
1 ✔
1422
               auto enc = a.serialize();
1 ✔
1423
               res.test_bin_eq("BigInt::serialize", enc, "1234567890ABCDEF");
1 ✔
1424

1425
               auto enc10 = a.serialize(10);
1 ✔
1426
               res.test_bin_eq("BigInt::serialize", enc10, "00001234567890ABCDEF");
1 ✔
1427

1428
               res.test_throws("BigInt::serialize rejects short output", [&]() { a.serialize(7); });
2 ✔
1429
            }),
1 ✔
1430

1431
      CHECK("BigInt truncated/padded binary serialization",
1432
            [&](Test::Result& res) {
1 ✔
1433
               const Botan::BigInt a(0xFEDCBA9876543210);
1 ✔
1434

1435
               std::vector<uint8_t> enc1(a.bytes() - 1);
1 ✔
1436
               a.binary_encode(enc1.data(), enc1.size());
1 ✔
1437
               res.test_bin_eq("BigInt::binary_encode", enc1, "DCBA9876543210");
1 ✔
1438

1439
               std::vector<uint8_t> enc2(a.bytes() - 3);
1 ✔
1440
               a.binary_encode(enc2.data(), enc2.size());
1 ✔
1441
               res.test_bin_eq("BigInt::binary_encode", enc2, "9876543210");
1 ✔
1442

1443
               std::vector<uint8_t> enc3(a.bytes() + 1);
1 ✔
1444
               a.binary_encode(enc3.data(), enc3.size());
1 ✔
1445
               res.test_bin_eq("BigInt::binary_encode", enc3, "00FEDCBA9876543210");
1 ✔
1446

1447
               // make sure that the padding is actually written
1448
               std::vector<uint8_t> enc4(a.bytes() + 3);
1 ✔
1449
               rng->randomize(enc4);
1 ✔
1450
               a.binary_encode(enc4.data(), enc4.size());
1 ✔
1451
               res.test_bin_eq("BigInt::binary_encode", enc4, "000000FEDCBA9876543210");
1 ✔
1452

1453
               const Botan::BigInt b("0xFEDCBA9876543210BAADC0FFEE");
1 ✔
1454

1455
               std::vector<uint8_t> enc5(b.bytes() + 12);
1 ✔
1456
               rng->randomize(enc5);
1 ✔
1457
               b.binary_encode(enc5.data(), enc5.size());
1 ✔
1458
               res.test_bin_eq("BigInt::binary_encode", enc5, "000000000000000000000000FEDCBA9876543210BAADC0FFEE");
1 ✔
1459
            }),
1 ✔
1460
   };
3 ✔
1461
}
2 ✔
1462

1463
BOTAN_REGISTER_TEST_FN("math", "bignum_auxiliary", test_const_time_left_shift, test_bigint_serialization);
1464

1465
class BigInt_FromRadix_Tests final : public Text_Based_Test {
×
1466
   public:
1467
      BigInt_FromRadix_Tests() : Text_Based_Test("bn/from_radix.vec", "Input,Radix,Output") {}
2 ✔
1468

1469
      bool clear_between_callbacks() const override { return false; }
149 ✔
1470

1471
      Test::Result run_one_test(const std::string& header, const VarMap& vars) override {
149 ✔
1472
         Test::Result result("BigInt from_radix_digits");
149 ✔
1473

1474
         const std::string input = vars.get_req_str("Input");
149 ✔
1475
         const size_t radix = vars.get_req_sz("Radix");
149 ✔
1476
         const std::string expected_output = vars.get_req_str("Output");
149 ✔
1477

1478
         if(header == "Valid") {
149 ✔
1479
            const Botan::BigInt n = Botan::BigInt::from_radix_digits(input, radix);
140 ✔
1480
            const auto serialized = n.serialize();
140 ✔
1481
            result.test_bin_eq("from_radix_digits", serialized, expected_output);
140 ✔
1482

1483
            if(radix == 10) {
140 ✔
1484
               // Decimal formatting does not include leading zeros
1485
               const size_t first_nonzero = input.find_first_not_of('0');
125 ✔
1486
               const std::string canonical = (first_nonzero == std::string::npos) ? "0" : input.substr(first_nonzero);
125 ✔
1487
               const auto value = Botan::BigInt::from_bytes(vars.get_req_bin("Output"));
125 ✔
1488
               result.test_str_eq("to_dec_string", value.to_dec_string(), canonical);
125 ✔
1489
            }
125 ✔
1490
         } else if(header == "Invalid") {
149 ✔
1491
            try {
9 ✔
1492
               Botan::BigInt::from_radix_digits(input, radix);
9 ✔
1493
               result.test_failure("from_radix_digits should have thrown");
×
1494
            } catch(const std::exception& e) {
9 ✔
1495
               const std::string msg = e.what();
9 ✔
1496
               result.test_is_true("exception message contains '" + expected_output + "'",
27 ✔
1497
                                   msg.find(expected_output) != std::string::npos);
9 ✔
1498
            }
9 ✔
1499
         } else {
1500
            result.test_failure("Unknown header " + header);
×
1501
         }
1502

1503
         return result;
149 ✔
1504
      }
149 ✔
1505
};
1506

1507
BOTAN_REGISTER_TEST("math", "bn_from_radix", BigInt_FromRadix_Tests);
1508

1509
#endif
1510

1511
}  // namespace
1512

1513
}  // namespace Botan_Tests
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc