• 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

93.78
/src/tests/test_ec_group.cpp
1
/*
2
* (C) 2007 Falko Strenzke
3
*     2007 Manuel Hartl
4
*     2009,2015,2018,2021 Jack Lloyd
5
*
6
* Botan is released under the Simplified BSD License (see license.txt)
7
*/
8

9
#include "tests.h"
10

11
#if defined(BOTAN_HAS_ECC_GROUP)
12
   #include <botan/bigint.h>
13
   #include <botan/data_src.h>
14
   #include <botan/der_enc.h>
15
   #include <botan/ec_group.h>
16
   #include <botan/hex.h>
17
   #include <botan/numthry.h>
18
   #include <botan/pk_keys.h>
19
   #include <botan/rng.h>
20
   #include <botan/x509_key.h>
21
   #include <botan/internal/barrett.h>
22
   #include <botan/internal/ec_inner_data.h>
23
   #include <array>
24
   #if defined(BOTAN_HAS_ECDSA)
25
      #include <botan/ecdsa.h>
26
      #include <botan/hash.h>
27
      #include <botan/pk_algs.h>
28
      #include <botan/pk_options.h>
29
      #include <botan/pubkey.h>
30
   #endif
31
#endif
32

33
namespace Botan_Tests {
34

35
namespace {
36

37
#if defined(BOTAN_HAS_ECC_GROUP)
38

39
std::vector<uint8_t> encode_explicit_group(const Botan::BigInt& p,
5 ✔
40
                                           const Botan::BigInt& a,
41
                                           const Botan::BigInt& b,
42
                                           const Botan::BigInt& base_x,
43
                                           const Botan::BigInt& base_y,
44
                                           const Botan::BigInt& order,
45
                                           const Botan::BigInt& cofactor) {
46
   const size_t p_bytes = p.bytes();
5 ✔
47
   std::vector<uint8_t> base_point = {0x04};
5 ✔
48
   const auto x_bytes = base_x.serialize(p_bytes);
5 ✔
49
   const auto y_bytes = base_y.serialize(p_bytes);
5 ✔
50
   base_point.insert(base_point.end(), x_bytes.begin(), x_bytes.end());
5 ✔
51
   base_point.insert(base_point.end(), y_bytes.begin(), y_bytes.end());
5 ✔
52

53
   std::vector<uint8_t> output;
5 ✔
54
   Botan::DER_Encoder(output)
5 ✔
55
      .start_sequence()
5 ✔
56
      .encode(size_t(1))
5 ✔
57
      .start_sequence()
5 ✔
58
      .encode(Botan::OID("1.2.840.10045.1.1"))
10 ✔
59
      .encode(p)
5 ✔
60
      .end_cons()
5 ✔
61
      .start_sequence()
5 ✔
62
      .encode(a.serialize(p_bytes), Botan::ASN1_Type::OctetString)
10 ✔
63
      .encode(b.serialize(p_bytes), Botan::ASN1_Type::OctetString)
10 ✔
64
      .end_cons()
5 ✔
65
      .encode(base_point, Botan::ASN1_Type::OctetString)
10 ✔
66
      .encode(order)
5 ✔
67
      .encode(cofactor)
5 ✔
68
      .end_cons();
5 ✔
69

70
   return output;
5 ✔
71
}
15 ✔
72

73
   #if defined(BOTAN_HAS_LEGACY_EC_POINT)
74

75
Botan::BigInt test_integer(Botan::RandomNumberGenerator& rng, size_t bits, const BigInt& max) {
560 ✔
76
   /*
77
   Produces integers with long runs of ones and zeros, for testing for
78
   carry handling problems.
79
   */
80
   Botan::BigInt x = 0;
560 ✔
81

82
   const auto flip_prob = [](size_t i) -> double {
154,040 ✔
83
      if(i % 64 == 0) {
153,480 ✔
84
         return .5;
85
      }
86
      if(i % 32 == 0) {
150,980 ✔
87
         return .4;
88
      }
89
      if(i % 8 == 0) {
148,560 ✔
90
         return .05;
14,360 ✔
91
      }
92
      return .01;
93
   };
94

95
   bool active = (rng.next_byte() > 128) ? true : false;
560 ✔
96
   for(size_t i = 0; i != bits; ++i) {
154,040 ✔
97
      x <<= 1;
153,480 ✔
98
      x += static_cast<int>(active);
153,480 ✔
99

100
      const double prob = flip_prob(i);
153,480 ✔
101
      const double sample = double(rng.next_byte() % 100) / 100.0;  // biased
153,480 ✔
102

103
      if(sample < prob) {
153,480 ✔
104
         active = !active;
5,005 ✔
105
      }
106
   }
107

108
   if(x == 0) {
560 ✔
109
      // EC_Scalar rejects zero as an input, if we hit this case instead
110
      // test with a completely randomized scalar
111
      return BigInt::random_integer(rng, 1, max);
×
112
   }
113

114
   if(max > 0) {
560 ✔
115
      while(x >= max) {
631 ✔
116
         const size_t b = x.bits() - 1;
71 ✔
117
         BOTAN_ASSERT(x.get_bit(b) == true, "Set");
142 ✔
118
         x.clear_bit(b);
71 ✔
119
      }
120
   }
121

122
   return x;
560 ✔
123
}
560 ✔
124

125
Botan::EC_Point create_random_point(Botan::RandomNumberGenerator& rng, const Botan::EC_Group& group) {
112 ✔
126
   const Botan::BigInt& p = group.get_p();
112 ✔
127
   const auto mod_p = Botan::Barrett_Reduction::for_public_modulus(p);
112 ✔
128

129
   for(;;) {
94 ✔
130
      const Botan::BigInt x = Botan::BigInt::random_integer(rng, 1, p);
206 ✔
131
      const Botan::BigInt x3 = mod_p.multiply(x, mod_p.square(x));
206 ✔
132
      const Botan::BigInt ax = mod_p.multiply(group.get_a(), x);
206 ✔
133
      const Botan::BigInt y = mod_p.reduce(x3 + ax + group.get_b());
206 ✔
134
      const Botan::BigInt sqrt_y = Botan::sqrt_modulo_prime(y, p);
206 ✔
135

136
      if(sqrt_y > 1) {
206 ✔
137
         BOTAN_ASSERT_EQUAL(mod_p.square(sqrt_y), y, "Square root is correct");
224 ✔
138
         return group.point(x, sqrt_y);
112 ✔
139
      }
140
   }
206 ✔
141
}
112 ✔
142

143
class ECC_Randomized_Tests final : public Test {
1 ✔
144
   public:
145
      std::vector<Test::Result> run() override;
146
};
147

148
std::vector<Test::Result> ECC_Randomized_Tests::run() {
1 ✔
149
   std::vector<Test::Result> results;
1 ✔
150
   for(const std::string& group_name : Botan::EC_Group::known_named_groups()) {
29 ✔
151
      Test::Result result("ECC randomized " + group_name);
28 ✔
152

153
      result.start_timer();
28 ✔
154

155
      const auto group = Botan::EC_Group::from_name(group_name);
28 ✔
156

157
      const Botan::EC_Point pt = create_random_point(this->rng(), group);
28 ✔
158

159
      try {
28 ✔
160
         std::vector<Botan::BigInt> blind_ws;
28 ✔
161
         const size_t trials = (Test::run_long_tests() ? 10 : 3);
28 ✔
162
         for(size_t i = 0; i < trials; ++i) {
308 ✔
163
            const Botan::BigInt a = test_integer(rng(), group.get_order_bits(), group.get_order());
280 ✔
164
            const Botan::BigInt b = test_integer(rng(), group.get_order_bits(), group.get_order());
280 ✔
165
            const Botan::BigInt c = group.mod_order(a + b);
280 ✔
166

167
            const Botan::EC_Point P = pt * a;
280 ✔
168
            const Botan::EC_Point Q = pt * b;
280 ✔
169
            const Botan::EC_Point R = pt * c;
280 ✔
170

171
            Botan::EC_Point P1 = group.blinded_var_point_multiply(pt, a, this->rng(), blind_ws);
280 ✔
172
            Botan::EC_Point Q1 = group.blinded_var_point_multiply(pt, b, this->rng(), blind_ws);
280 ✔
173
            Botan::EC_Point R1 = group.blinded_var_point_multiply(pt, c, this->rng(), blind_ws);
280 ✔
174

175
            Botan::EC_Point A1 = P + Q;
280 ✔
176
            Botan::EC_Point A2 = Q + P;
280 ✔
177

178
            result.test_bin_eq("p + q", A1.xy_bytes(), R.xy_bytes());
560 ✔
179
            result.test_bin_eq("q + p", A2.xy_bytes(), R.xy_bytes());
560 ✔
180

181
            A1.force_affine();
280 ✔
182
            A2.force_affine();
280 ✔
183
            result.test_bin_eq("p + q", A1.xy_bytes(), R.xy_bytes());
560 ✔
184
            result.test_bin_eq("q + p", A2.xy_bytes(), R.xy_bytes());
560 ✔
185

186
            result.test_is_true("p on the curve", P.on_the_curve());
280 ✔
187
            result.test_is_true("q on the curve", Q.on_the_curve());
280 ✔
188
            result.test_is_true("r on the curve", R.on_the_curve());
280 ✔
189

190
            result.test_bin_eq("P1", P1.xy_bytes(), P.xy_bytes());
560 ✔
191
            result.test_bin_eq("Q1", Q1.xy_bytes(), Q.xy_bytes());
560 ✔
192
            result.test_bin_eq("R1", R1.xy_bytes(), R.xy_bytes());
560 ✔
193

194
            P1.force_affine();
280 ✔
195
            Q1.force_affine();
280 ✔
196
            R1.force_affine();
280 ✔
197
            result.test_bin_eq("P1", P1.xy_bytes(), P.xy_bytes());
560 ✔
198
            result.test_bin_eq("Q1", Q1.xy_bytes(), Q.xy_bytes());
560 ✔
199
            result.test_bin_eq("R1", R1.xy_bytes(), R.xy_bytes());
560 ✔
200
         }
280 ✔
201
      } catch(std::exception& e) {
28 ✔
202
         result.test_failure(group_name, e.what());
×
203
      }
×
204
      result.end_timer();
28 ✔
205
      results.push_back(result);
28 ✔
206
   }
28 ✔
207

208
   return results;
1 ✔
209
}
×
210

211
BOTAN_REGISTER_TEST("pubkey", "ecc_randomized", ECC_Randomized_Tests);
212

213
   #endif
214

215
class EC_Group_Tests : public Test {
1 ✔
216
   public:
217
      std::vector<Test::Result> run() override {
1 ✔
218
         std::vector<Test::Result> results;
1 ✔
219

220
         for(const std::string& group_name : Botan::EC_Group::known_named_groups()) {
29 ✔
221
            Test::Result result("EC_Group " + group_name);
28 ✔
222

223
            result.start_timer();
28 ✔
224

225
            const auto group = Botan::EC_Group::from_name(group_name);
28 ✔
226

227
            result.test_is_true("EC_Group is known", group.get_curve_oid().has_value());
28 ✔
228
            result.test_is_true("EC_Group is considered valid", group.verify_group(this->rng(), true));
28 ✔
229
            result.test_is_true("EC_Group is not considered explicit encoding", !group.used_explicit_encoding());
28 ✔
230

231
            result.test_sz_eq("EC_Group has correct bit size", group.get_p().bits(), group.get_p_bits());
28 ✔
232
            result.test_sz_eq("EC_Group has byte size", group.get_p().bytes(), group.get_p_bytes());
28 ✔
233

234
            result.test_bn_eq("EC_Group has cofactor == 1", group.get_cofactor(), 1);
28 ✔
235

236
            const Botan::OID from_order = Botan::EC_Group::EC_group_identity_from_order(group.get_order());
28 ✔
237

238
            result.test_str_eq(
28 ✔
239
               "EC_group_identity_from_order works", from_order.to_string(), group.get_curve_oid().to_string());
56 ✔
240

241
            result.test_is_true("Same group is same", group == Botan::EC_Group::from_name(group_name));
28 ✔
242

243
            try {
28 ✔
244
               const auto copy = Botan::EC_Group::register_custom_group(group.get_curve_oid(),
28 ✔
245
                                                                        group.get_p(),
246
                                                                        group.get_a(),
247
                                                                        group.get_b(),
248
                                                                        group.get_g_x(),
249
                                                                        group.get_g_y(),
250
                                                                        group.get_order());
28 ✔
251

252
               result.test_is_true("Same group is same even with copy", group == copy);
20 ✔
253
            } catch(Botan::Invalid_Argument&) {}
28 ✔
254

255
            const auto group_der_oid = group.DER_encode();
28 ✔
256
            const Botan::EC_Group group_via_oid(group_der_oid);
28 ✔
257
            result.test_is_true("EC_Group via OID is not considered explicit encoding",
28 ✔
258
                                !group_via_oid.used_explicit_encoding());
28 ✔
259

260
            const auto group_der_explicit = group.DER_encode(Botan::EC_Group_Encoding::Explicit);
28 ✔
261
            const Botan::EC_Group group_via_explicit(group_der_explicit);
28 ✔
262
            result.test_is_true("EC_Group via explicit DER is considered explicit encoding",
28 ✔
263
                                group_via_explicit.used_explicit_encoding());
28 ✔
264

265
            if(group.a_is_minus_3()) {
28 ✔
266
               result.test_bn_eq("Group A equals -3", group.get_a(), group.get_p() - 3);
17 ✔
267
            } else {
268
               result.test_bn_ne("Group " + group_name + " A does not equal -3", group.get_a(), group.get_p() - 3);
33 ✔
269
            }
270

271
            if(group.a_is_zero()) {
28 ✔
272
               result.test_bn_eq("Group A is zero", group.get_a(), BigInt(0));
4 ✔
273
            } else {
274
               result.test_bn_ne("Group " + group_name + " A does not equal zero", group.get_a(), BigInt(0));
72 ✔
275
            }
276

277
   #if defined(BOTAN_HAS_LEGACY_EC_POINT)
278
            const auto pt_mult_by_order = group.get_base_point() * group.get_order();
28 ✔
279
            result.test_is_true("Multiplying point by the order results in zero point", pt_mult_by_order.is_zero());
28 ✔
280

281
            // get a valid point
282
            Botan::EC_Point p = group.get_base_point() * this->rng().next_nonzero_byte();
28 ✔
283

284
            // get a copy
285
            Botan::EC_Point q = p;
28 ✔
286

287
            p.randomize_repr(this->rng());
28 ✔
288
            q.randomize_repr(this->rng());
28 ✔
289

290
            result.test_bn_eq("affine x after copy", p.get_affine_x(), q.get_affine_x());
28 ✔
291
            result.test_bn_eq("affine y after copy", p.get_affine_y(), q.get_affine_y());
28 ✔
292

293
            q.force_affine();
28 ✔
294

295
            result.test_bn_eq("affine x after copy", p.get_affine_x(), q.get_affine_x());
28 ✔
296
            result.test_bn_eq("affine y after copy", p.get_affine_y(), q.get_affine_y());
28 ✔
297

298
            test_ser_der(result, group);
28 ✔
299
            test_basic_math(result, group);
28 ✔
300
            test_point_swap(result, group);
28 ✔
301
            test_zeropoint(result, group);
28 ✔
302
   #endif
303

304
            result.end_timer();
28 ✔
305

306
            results.push_back(result);
28 ✔
307
         }
84 ✔
308

309
         return results;
1 ✔
310
      }
×
311

312
   private:
313
   #if defined(BOTAN_HAS_LEGACY_EC_POINT)
314

315
      void test_ser_der(Test::Result& result, const Botan::EC_Group& group) {
28 ✔
316
         // generate point
317
         const Botan::EC_Point pt = create_random_point(this->rng(), group);
28 ✔
318
         const Botan::EC_Point zero = group.zero_point();
28 ✔
319

320
         for(const auto scheme : {Botan::EC_Point_Format::Uncompressed,
84 ✔
321
                                  Botan::EC_Point_Format::Compressed,
322
                                  Botan::EC_Point_Format::Hybrid}) {
112 ✔
323
            try {
84 ✔
324
               result.test_bin_eq("encoded/decode rt works", group.OS2ECP(pt.encode(scheme)).xy_bytes(), pt.xy_bytes());
336 ✔
325
            } catch(Botan::Exception& e) {
×
326
               result.test_failure("Failed to round trip encode a random point", e.what());
×
327
            }
×
328

329
            try {
84 ✔
330
               result.test_is_true("encoded/decode rt works", group.OS2ECP(zero.encode(scheme)).is_zero());
252 ✔
331
            } catch(Botan::Exception& e) {
×
332
               result.test_failure("Failed to round trip encode the identity element", e.what());
×
333
            }
×
334
         }
335
      }
28 ✔
336

337
      static void test_basic_math(Test::Result& result, const Botan::EC_Group& group) {
28 ✔
338
         const Botan::EC_Point& G = group.get_base_point();
28 ✔
339

340
         const auto G2 = G * 2;
56 ✔
341
         const auto G3 = G * 3;
56 ✔
342

343
         Botan::EC_Point p1 = G2;
28 ✔
344
         p1 += G;
28 ✔
345

346
         result.test_bin_eq("point addition", p1.xy_bytes(), G3.xy_bytes());
56 ✔
347

348
         p1 -= G2;
28 ✔
349

350
         result.test_bin_eq("point subtraction", p1.xy_bytes(), G.xy_bytes());
56 ✔
351

352
         // The scalar multiplication algorithm relies on this being true:
353
         try {
28 ✔
354
            const Botan::EC_Point zero_coords = group.point(0, 0);
56 ✔
355
            result.test_is_true("point (0,0) is not on the curve", !zero_coords.on_the_curve());
×
356
         } catch(Botan::Exception&) {
28 ✔
357
            result.test_success("point (0,0) is rejected");
28 ✔
358
         }
28 ✔
359
      }
28 ✔
360

361
      void test_point_swap(Test::Result& result, const Botan::EC_Group& group) {
28 ✔
362
         const Botan::EC_Point a(create_random_point(this->rng(), group));
28 ✔
363
         Botan::EC_Point b(create_random_point(this->rng(), group));
28 ✔
364
         b *= Botan::BigInt(this->rng(), 20);
28 ✔
365

366
         Botan::EC_Point c(a);
28 ✔
367
         Botan::EC_Point d(b);
28 ✔
368

369
         d.swap(c);
28 ✔
370
         result.test_bin_eq("swap correct", a.xy_bytes(), d.xy_bytes());
56 ✔
371
         result.test_bin_eq("swap correct", b.xy_bytes(), c.xy_bytes());
56 ✔
372
      }
28 ✔
373

374
      static void test_zeropoint(Test::Result& result, const Botan::EC_Group& group) {
28 ✔
375
         Botan::EC_Point zero = group.zero_point();
28 ✔
376

377
         result.test_throws("Zero point throws", "Cannot convert zero point to affine", [&]() { zero.get_affine_x(); });
56 ✔
378
         result.test_throws("Zero point throws", "Cannot convert zero point to affine", [&]() { zero.get_affine_y(); });
56 ✔
379

380
         const Botan::EC_Point p1 = group.get_base_point() * 2;
28 ✔
381

382
         result.test_is_true("point is on the curve", p1.on_the_curve());
28 ✔
383
         result.test_is_true("point is not zero", !p1.is_zero());
28 ✔
384

385
         Botan::EC_Point p2 = p1;
28 ✔
386
         p2 -= p1;
28 ✔
387

388
         result.test_is_true("p - q with q = p results in zero", p2.is_zero());
28 ✔
389

390
         const Botan::EC_Point minus_p1 = -p1;
28 ✔
391
         result.test_is_true("point is on the curve", minus_p1.on_the_curve());
28 ✔
392
         const Botan::EC_Point shouldBeZero = p1 + minus_p1;
28 ✔
393
         result.test_is_true("point is on the curve", shouldBeZero.on_the_curve());
28 ✔
394
         result.test_is_true("point is zero", shouldBeZero.is_zero());
28 ✔
395

396
         result.test_bn_eq("minus point x", minus_p1.get_affine_x(), p1.get_affine_x());
28 ✔
397
         result.test_bn_eq("minus point y", minus_p1.get_affine_y(), group.get_p() - p1.get_affine_y());
28 ✔
398

399
         result.test_is_true("zero point is zero", zero.is_zero());
28 ✔
400
         result.test_is_true("zero point is on the curve", zero.on_the_curve());
28 ✔
401
         result.test_bin_eq("addition of zero does nothing", p1.xy_bytes(), (p1 + zero).xy_bytes());
84 ✔
402
         result.test_bin_eq("addition of zero does nothing", p1.xy_bytes(), (zero + p1).xy_bytes());
84 ✔
403
         result.test_bin_eq("addition of zero does nothing", p1.xy_bytes(), (p1 - zero).xy_bytes());
84 ✔
404
         result.test_is_true("zero times anything is the zero point", (zero * 39193).is_zero());
56 ✔
405

406
         for(const auto scheme : {Botan::EC_Point_Format::Uncompressed,
196 ✔
407
                                  Botan::EC_Point_Format::Compressed,
408
                                  Botan::EC_Point_Format::Hybrid}) {
112 ✔
409
            const std::vector<uint8_t> v = zero.encode(scheme);
84 ✔
410
            result.test_is_true("encoded/decode rt works", group.OS2ECP(v).is_zero());
168 ✔
411
         }
84 ✔
412
      }
28 ✔
413
   #endif
414
};
415

416
BOTAN_REGISTER_TEST("pubkey", "ec_group", EC_Group_Tests);
417

418
Test::Result test_decoding_with_seed() {
1 ✔
419
   Test::Result result("Decode EC_Group with seed");
1 ✔
420

421
   try {
1 ✔
422
      if(Botan::EC_Group::supports_named_group("secp384r1")) {
1 ✔
423
         const auto secp384r1 = Botan::EC_Group::from_name("secp384r1");
1 ✔
424
         const auto secp384r1_with_seed =
1 ✔
425
            Botan::EC_Group::from_PEM(Test::read_data_file("x509/ecc/secp384r1_seed.pem"));
2 ✔
426
         result.test_is_true("decoding worked", secp384r1_with_seed.initialized());
1 ✔
427
         result.test_bn_eq("P-384 prime", secp384r1_with_seed.get_p(), secp384r1.get_p());
1 ✔
428
      }
1 ✔
429
   } catch(Botan::Exception& e) {
×
430
      result.test_failure(e.what());
×
431
   }
×
432

433
   return result;
1 ✔
434
}
×
435

436
Test::Result test_mixed_points() {
1 ✔
437
   Test::Result result("Mixed Point Arithmetic");
1 ✔
438

439
   if(Botan::EC_Group::supports_named_group("secp256r1") && Botan::EC_Group::supports_named_group("secp384r1")) {
1 ✔
440
      const auto secp256r1 = Botan::EC_Group::from_name("secp256r1");
1 ✔
441
      const auto secp384r1 = Botan::EC_Group::from_name("secp384r1");
1 ✔
442

443
   #if defined(BOTAN_HAS_LEGACY_EC_POINT)
444
      const Botan::EC_Point& G256 = secp256r1.get_base_point();
1 ✔
445
      const Botan::EC_Point& G384 = secp384r1.get_base_point();
1 ✔
446

447
      result.test_throws("Mixing points from different groups", [&] { const Botan::EC_Point p = G256 + G384; });
2 ✔
448
   #endif
449

450
      const auto p1 = Botan::EC_AffinePoint::generator(secp256r1);
1 ✔
451
      const auto p2 = Botan::EC_AffinePoint::generator(secp384r1);
1 ✔
452
      result.test_throws("Mixing points from different groups", [&] { const auto p3 = p1.add(p2); });
2 ✔
453
   }
1 ✔
454

455
   return result;
1 ✔
456
}
×
457

458
Test::Result test_mixed_scalars() {
1 ✔
459
   Test::Result result("Mixed EC_Scalar Arithmetic");
1 ✔
460

461
   if(Botan::EC_Group::supports_named_group("secp256r1") && Botan::EC_Group::supports_named_group("secp384r1")) {
1 ✔
462
      const auto secp256r1 = Botan::EC_Group::from_name("secp256r1");
1 ✔
463
      const auto secp384r1 = Botan::EC_Group::from_name("secp384r1");
1 ✔
464

465
      const auto five_256 = Botan::EC_Scalar::from_bigint(secp256r1, 5);
1 ✔
466
      const auto five_384 = Botan::EC_Scalar::from_bigint(secp384r1, 5);
1 ✔
467

468
      result.test_is_false("same integer in different scalar groups is different", five_256 == five_384);
1 ✔
469
      result.test_throws<Botan::Invalid_Argument>("Adding scalars from different groups",
1 ✔
470
                                                  [&] { static_cast<void>(five_256 + five_384); });
2 ✔
471
      result.test_throws<Botan::Invalid_Argument>("Subtracting scalars from different groups",
1 ✔
472
                                                  [&] { static_cast<void>(five_256 - five_384); });
2 ✔
473
      result.test_throws<Botan::Invalid_Argument>("Multiplying scalars from different groups",
1 ✔
474
                                                  [&] { static_cast<void>(five_256 * five_384); });
2 ✔
475

476
      auto scalar_copy = Botan::EC_Scalar::from_bigint(secp256r1, 1);
1 ✔
477
      scalar_copy = five_384;
1 ✔
478
      result.test_is_true("copy assignment replaces scalar group", scalar_copy == five_384);
1 ✔
479
      result.test_sz_eq("copy assignment replaces scalar size", scalar_copy.bytes(), five_384.bytes());
1 ✔
480

481
      auto scalar_assign = Botan::EC_Scalar::from_bigint(secp256r1, 1);
1 ✔
482
      scalar_assign.assign(five_384);
1 ✔
483
      result.test_is_true("assign replaces scalar group", scalar_assign == five_384);
1 ✔
484
      result.test_sz_eq("assign replaces scalar size", scalar_assign.bytes(), five_384.bytes());
1 ✔
485
   }
1 ✔
486

487
   return result;
1 ✔
488
}
×
489

490
Test::Result test_group_accessor() {
1 ✔
491
   Test::Result result("EC_Scalar/EC_AffinePoint group accessor");
1 ✔
492

493
   if(Botan::EC_Group::supports_named_group("secp256r1") && Botan::EC_Group::supports_named_group("secp384r1")) {
1 ✔
494
      const auto secp256r1 = Botan::EC_Group::from_name("secp256r1");
1 ✔
495
      const auto secp384r1 = Botan::EC_Group::from_name("secp384r1");
1 ✔
496

497
      const auto scalar = Botan::EC_Scalar::one(secp256r1);
1 ✔
498
      result.test_is_true("EC_Scalar::group returns the originating group", scalar.group() == secp256r1);
1 ✔
499
      result.test_is_true("EC_Scalar::group does not match a different group", scalar.group() != secp384r1);
2 ✔
500
      // The recovered group shares the same canonical inner representation
501
      result.test_is_true("EC_Scalar::group shares inner data", scalar.group()._data() == secp256r1._data());
1 ✔
502

503
      const auto point = Botan::EC_AffinePoint::generator(secp256r1);
1 ✔
504
      result.test_is_true("EC_AffinePoint::group returns the originating group", point.group() == secp256r1);
1 ✔
505
      result.test_is_true("EC_AffinePoint::group does not match a different group", point.group() != secp384r1);
2 ✔
506
      result.test_is_true("EC_AffinePoint::group shares inner data", point.group()._data() == secp256r1._data());
1 ✔
507
   }
1 ✔
508

509
   return result;
1 ✔
510
}
×
511

512
class ECC_Unit_Tests final : public Test {
1 ✔
513
   public:
514
      std::vector<Test::Result> run() override {
1 ✔
515
         std::vector<Test::Result> results;
1 ✔
516

517
         results.push_back(test_decoding_with_seed());
2 ✔
518
         results.push_back(test_mixed_points());
2 ✔
519
         results.push_back(test_mixed_scalars());
2 ✔
520
         results.push_back(test_group_accessor());
2 ✔
521

522
         return results;
1 ✔
523
      }
×
524
};
525

526
BOTAN_REGISTER_TEST("pubkey", "ecc_unit", ECC_Unit_Tests);
527

528
class EC_Group_Registration_Tests final : public Test {
1 ✔
529
   public:
530
      std::vector<Test::Result> run() override {
1 ✔
531
         std::vector<Test::Result> results;
1 ✔
532

533
         if(Botan::EC_Group::supports_application_specific_group()) {
1 ✔
534
            results.push_back(test_ecc_registration());
2 ✔
535
            results.push_back(test_ec_group_from_params());
2 ✔
536
            results.push_back(test_ec_group_bad_registration());
2 ✔
537
            results.push_back(test_ec_group_off_curve_generator());
2 ✔
538
            results.push_back(test_ec_group_duplicate_orders());
2 ✔
539
            results.push_back(test_ec_group_incorrect_order());
2 ✔
540
            results.push_back(test_ec_group_registration_with_custom_oid());
2 ✔
541
            results.push_back(test_ec_group_registration_with_mismatched_custom_oid());
2 ✔
542
            results.push_back(test_ec_group_alias_oid_cache());
2 ✔
543
            results.push_back(test_ec_group_unregistration());
2 ✔
544
            results.push_back(test_supports_named_group_with_registration());
2 ✔
545
   #if defined(BOTAN_HAS_ECDSA)
546
            results.push_back(test_ec_key_with_equivalent_group());
2 ✔
547
   #endif
548
         }
549

550
         return results;
1 ✔
551
      }
×
552

553
   private:
554
      Test::Result test_ecc_registration() {
1 ✔
555
         Test::Result result("ECC registration");
1 ✔
556

557
         // numsp256d1
558
         const Botan::BigInt p("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF43");
1 ✔
559
         const Botan::BigInt a("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF40");
1 ✔
560
         const Botan::BigInt b("0x25581");
1 ✔
561
         const Botan::BigInt order("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE43C8275EA265C6020AB20294751A825");
1 ✔
562

563
         const Botan::BigInt g_x("0x01");
1 ✔
564
         const Botan::BigInt g_y("0x696F1853C1E466D7FC82C96CCEEEDD6BD02C2F9375894EC10BF46306C2B56C77");
1 ✔
565

566
         const Botan::OID oid("1.3.6.1.4.1.25258.4.1");
1 ✔
567

568
         // Creating this object implicitly registers the curve for future use ...
569
         const auto reg_group = Botan::EC_Group::register_custom_group(oid, p, a, b, g_x, g_y, order);
1 ✔
570

571
         const auto group = Botan::EC_Group::from_OID(oid);
1 ✔
572

573
         result.test_bn_eq("Group registration worked", group.get_p(), p);
1 ✔
574

575
         // TODO(Botan4) this could change to == Generic
576
         result.test_is_true("Group is not pcurve", group.engine() != Botan::EC_Group_Engine::Optimized);
1 ✔
577

578
         return result;
1 ✔
579
      }
1 ✔
580

581
      Test::Result test_ec_group_from_params() {
1 ✔
582
         Test::Result result("EC_Group from params");
1 ✔
583

584
         Botan::EC_Group::clear_registered_curve_data();
1 ✔
585

586
         // secp256r1
587
         const Botan::BigInt p("0xFFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF");
1 ✔
588
         const Botan::BigInt a("0xFFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC");
1 ✔
589
         const Botan::BigInt b("0x5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B");
1 ✔
590

591
         const Botan::BigInt g_x("0x6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296");
1 ✔
592
         const Botan::BigInt g_y("0x4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5");
1 ✔
593
         const Botan::BigInt order("0xFFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551");
1 ✔
594

595
         const Botan::OID oid("1.2.840.10045.3.1.7");
1 ✔
596

597
         // This uses the deprecated constructor to verify we dedup even without an OID
598
         // This whole test can be removed once explicit curve support is removed
599
         const Botan::EC_Group reg_group(p, a, b, g_x, g_y, order, 1);
1 ✔
600
         result.test_is_true("Group has correct OID", reg_group.get_curve_oid() == oid);
1 ✔
601

602
         return result;
1 ✔
603
      }
1 ✔
604

605
   #if defined(BOTAN_HAS_ECDSA)
606
      Test::Result test_ec_key_with_equivalent_group() {
1 ✔
607
         Test::Result result("EC key construction with equivalent but distinct EC_Group");
1 ✔
608

609
         // numsp384d1 is not a builtin group, so decoding it does not register it
610
         const Botan::BigInt p(
1 ✔
611
            "0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEC3");
1 ✔
612
         const Botan::BigInt a(
1 ✔
613
            "0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEC0");
1 ✔
614
         const Botan::BigInt b(
1 ✔
615
            "0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF77BB");
1 ✔
616
         const Botan::BigInt g_x("0x02");
1 ✔
617
         const Botan::BigInt g_y(
1 ✔
618
            "0x3C9F82CB4B87B4DC71E763E0663E5DBD8034ED422F04F82673330DC58D15FFA2B4A3D0BAD5D30F865BCBBF503EA66F43");
1 ✔
619
         const Botan::BigInt order(
1 ✔
620
            "0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFD61EAF1EEB5D6881BEDA9D3D4C37E27A604D81F67B0E61B9");
1 ✔
621

622
         const auto der = encode_explicit_group(p, a, b, g_x, g_y, order, 1);
1 ✔
623

624
         const Botan::EC_Group group1(der);
1 ✔
625
         const Botan::EC_Group group2(der);
1 ✔
626

627
         result.test_is_true("Groups compare equal", group1 == group2);
1 ✔
628
         result.test_is_true("Groups have distinct inner data", group1._data() != group2._data());
1 ✔
629

630
         const Botan::ECDSA_PrivateKey sk1(rng(), group1);
1 ✔
631

632
         // Keys created with the equivalent group adopt it, rebinding the key material
633
         const Botan::ECDSA_PrivateKey sk2(group2, sk1._private_key());
1 ✔
634
         const Botan::ECDSA_PublicKey pk2(group2, sk1.public_ec_point());
1 ✔
635

636
         result.test_is_true("Private key uses the specified group", sk2.domain()._data() == group2._data());
1 ✔
637
         result.test_is_true("Private scalar was rebound", sk2._private_key().group()._data() == group2._data());
1 ✔
638
         result.test_is_true("Public key uses the specified group", pk2.domain()._data() == group2._data());
1 ✔
639
         result.test_is_true("Public point was rebound", pk2.public_ec_point()._group() == group2._data());
1 ✔
640
         result.test_bin_eq(
1 ✔
641
            "Rebound private key has the same encoding", sk2.private_key_bits(), sk1.private_key_bits());
2 ✔
642
         result.test_bin_eq("Rebound public key has the same encoding", pk2.public_key_bits(), sk1.public_key_bits());
2 ✔
643

644
         if(Botan::HashFunction::create("SHA-256")) {
2 ✔
645
            const auto msg = rng().random_vec(32);
1 ✔
646
            Botan::PK_Signer signer(sk2, rng(), Botan::PK_Signature_Options().with_hash("SHA-256"));
1 ✔
647
            Botan::PK_Verifier verifier(pk2, Botan::PK_Signature_Options().with_hash("SHA-256"));
1 ✔
648
            result.test_is_true("Signature from rebound keys verifies",
×
649
                                verifier.verify_message(msg, signer.sign_message(msg, rng())));
2 ✔
650
         }
2 ✔
651

652
         if(Botan::EC_Group::supports_named_group("secp256r1")) {
1 ✔
653
            const auto secp256r1 = Botan::EC_Group::from_name("secp256r1");
1 ✔
654

655
            result.test_throws<Botan::Decoding_Error>("Point from a different group is rejected", [&] {
1 ✔
656
               static_cast<void>(Botan::ECDSA_PublicKey(secp256r1, sk1.public_ec_point()));
1 ✔
657
            });
×
658
            result.test_throws<Botan::Decoding_Error>("Scalar from a different group is rejected", [&] {
1 ✔
659
               static_cast<void>(Botan::ECDSA_PrivateKey(secp256r1, sk1._private_key()));
1 ✔
660
            });
×
661

662
            // Clearing the registry causes builtin groups to get fresh inner data as well
663
            const Botan::ECDSA_PrivateKey sk3(rng(), secp256r1);
1 ✔
664
            Botan::EC_Group::clear_registered_curve_data();
1 ✔
665
            const auto secp256r1_again = Botan::EC_Group::from_name("secp256r1");
1 ✔
666
            result.test_is_true("Builtin group has distinct inner data after registry clear",
2 ✔
667
                                secp256r1_again._data() != secp256r1._data());
1 ✔
668

669
            const Botan::ECDSA_PublicKey pk3(secp256r1_again, sk3.public_ec_point());
1 ✔
670
            result.test_is_true("Builtin point was rebound", pk3.public_ec_point()._group() == secp256r1_again._data());
1 ✔
671

672
            if(Botan::HashFunction::create("SHA-256")) {
2 ✔
673
               const auto msg = rng().random_vec(32);
1 ✔
674
               Botan::PK_Signer signer(sk3, rng(), Botan::PK_Signature_Options().with_hash("SHA-256"));
1 ✔
675
               Botan::PK_Verifier verifier(pk3, Botan::PK_Signature_Options().with_hash("SHA-256"));
1 ✔
676
               result.test_is_true("Signature verifies across registry clear",
×
677
                                   verifier.verify_message(msg, signer.sign_message(msg, rng())));
2 ✔
678
            }
2 ✔
679
         }
1 ✔
680

681
         return result;
2 ✔
682
      }
2 ✔
683
   #endif
684

685
      Test::Result test_ec_group_bad_registration() {
1 ✔
686
         Test::Result result("EC_Group registering non-match");
1 ✔
687

688
         Botan::EC_Group::clear_registered_curve_data();
1 ✔
689

690
         // secp256r1 params except with a bad B param
691
         const Botan::BigInt p("0xFFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF");
1 ✔
692
         const Botan::BigInt a("0xFFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC");
1 ✔
693
         const Botan::BigInt b("0x5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604C");
1 ✔
694

695
         const Botan::BigInt g_x("0x6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296");
1 ✔
696
         const Botan::BigInt g_y("0x4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5");
1 ✔
697
         const Botan::BigInt order("0xFFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551");
1 ✔
698

699
         const Botan::OID oid("1.2.840.10045.3.1.7");
1 ✔
700

701
         try {
1 ✔
702
            const auto reg_group = Botan::EC_Group::register_custom_group(oid, p, a, b, g_x, g_y, order);
1 ✔
703
            result.test_failure("Should have failed");
×
704
         } catch(Botan::Invalid_Argument&) {
1 ✔
705
            result.test_success("Got expected exception");
1 ✔
706
         }
1 ✔
707

708
         return result;
2 ✔
709
      }
1 ✔
710

711
      Test::Result test_ec_group_off_curve_generator() {
1 ✔
712
         Test::Result result("EC_Group rejects off-curve generator");
1 ✔
713

714
         Botan::EC_Group::clear_registered_curve_data();
1 ✔
715

716
         // secp256r1 params, but g_y has its low bit flipped so (g_x, g_y) is not on the curve
717
         const Botan::BigInt p("0xFFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF");
1 ✔
718
         const Botan::BigInt a("0xFFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC");
1 ✔
719
         const Botan::BigInt b("0x5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B");
1 ✔
720

721
         const Botan::BigInt g_x("0x6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296");
1 ✔
722
         const Botan::BigInt bad_g_y("0x4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F4");
1 ✔
723
         const Botan::BigInt order("0xFFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551");
1 ✔
724

725
         result.test_throws("Deprecated EC_Group constructor rejects off-curve generator",
1 ✔
726
                            "EC_Group generator is not on the curve",
727
                            [&]() { const Botan::EC_Group g(p, a, b, g_x, bad_g_y, order, 1); });
3 ✔
728

729
         const Botan::OID custom_oid("1.3.6.1.4.1.25258.100.42");
1 ✔
730
         result.test_throws("Deprecated EC_Group constructor with custom OID rejects off-curve generator",
1 ✔
731
                            "EC_Group generator is not on the curve",
732
                            [&]() { const Botan::EC_Group g(p, a, b, g_x, bad_g_y, order, 1, custom_oid); });
2 ✔
733

734
         return result;
2 ✔
735
      }
1 ✔
736

737
      Test::Result test_ec_group_duplicate_orders() {
1 ✔
738
         Test::Result result("EC_Group with duplicate group order");
1 ✔
739

740
         Botan::EC_Group::clear_registered_curve_data();
1 ✔
741

742
         // secp256r1
743
         const Botan::BigInt p("0xFFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF");
1 ✔
744
         const Botan::BigInt a("0xFFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC");
1 ✔
745
         const Botan::BigInt b("0x5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B");
1 ✔
746

747
         const Botan::BigInt g_x("0x6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296");
1 ✔
748
         const Botan::BigInt g_y("0x4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5");
1 ✔
749
         const Botan::BigInt order("0xFFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551");
1 ✔
750

751
         const Botan::OID oid("1.3.6.1.4.1.25258.100.0");  // some other random OID
1 ✔
752

753
         const auto reg_group = Botan::EC_Group::register_custom_group(oid, p, a, b, g_x, g_y, order);
1 ✔
754
         result.test_success("Registration success");
1 ✔
755
         result.test_is_true("Group has correct OID", reg_group.get_curve_oid() == oid);
1 ✔
756

757
         // We can now get it by OID:
758
         const auto hc_group = Botan::EC_Group::from_OID(oid);
1 ✔
759
         result.test_is_true("Group has correct OID", hc_group.get_curve_oid() == oid);
1 ✔
760

761
         // Existing secp256r1 unmodified:
762
         const Botan::OID secp160r1("1.2.840.10045.3.1.7");
1 ✔
763
         const auto other_group = Botan::EC_Group::from_OID(secp160r1);
1 ✔
764
         result.test_is_true("Group has correct OID", other_group.get_curve_oid() == secp160r1);
1 ✔
765

766
         return result;
1 ✔
767
      }
1 ✔
768

769
      Test::Result test_ec_group_registration_with_custom_oid() {
1 ✔
770
         Test::Result result("EC_Group registration of standard group with custom OID");
1 ✔
771

772
         Botan::EC_Group::clear_registered_curve_data();
1 ✔
773

774
         const Botan::OID secp256r1_oid("1.2.840.10045.3.1.7");
1 ✔
775
         const auto secp256r1 = Botan::EC_Group::from_OID(secp256r1_oid);
1 ✔
776
         result.test_is_true("Group has correct OID", secp256r1.get_curve_oid() == secp256r1_oid);
1 ✔
777

778
         const Botan::OID custom_oid("1.3.6.1.4.1.25258.100.99");  // some other random OID
1 ✔
779

780
         Botan::OID::register_oid(custom_oid, "secp256r1");
1 ✔
781

782
         const auto reg_group = Botan::EC_Group::register_custom_group(custom_oid,
1 ✔
783
                                                                       secp256r1.get_p(),
784
                                                                       secp256r1.get_a(),
785
                                                                       secp256r1.get_b(),
786
                                                                       secp256r1.get_g_x(),
787
                                                                       secp256r1.get_g_y(),
788
                                                                       secp256r1.get_order());
1 ✔
789

790
         result.test_success("Registration success");
1 ✔
791
         result.test_is_true("Group has correct OID", reg_group.get_curve_oid() == custom_oid);
1 ✔
792

793
         // We can now get it by OID:
794
         result.test_is_true("Group has correct OID",
1 ✔
795
                             Botan::EC_Group::from_OID(custom_oid).get_curve_oid() == custom_oid);
1 ✔
796

797
         // In the current data model of EC_Group there is a 1:1 OID:group, so these
798
         // have distinct underlying data
799
         result.test_is_true("Groups have different inner data pointers", reg_group._data() != secp256r1._data());
1 ✔
800

801
   #if defined(BOTAN_HAS_PCURVES_SECP256R1)
802
         // However we should have gotten a pcurves out of the deal *and* it
803
         // should be the exact same shared_ptr as the official curve
804

805
         result.test_enum_eq("Group is pcurves based", reg_group.engine(), Botan::EC_Group_Engine::Optimized);
1 ✔
806

807
         try {
1 ✔
808
            const auto& pcurve = reg_group._data()->pcurve();
1 ✔
809
            result.test_is_true("Group with custom OID got the same pcurve pointer",
1 ✔
810
                                &pcurve == &secp256r1._data()->pcurve());
1 ✔
811
         } catch(...) {
×
812
            result.test_failure("Group with custom OID did not get a pcurve pointer");
×
813
         }
×
814
   #endif
815

816
         return result;
2 ✔
817
      }
1 ✔
818

819
      Test::Result test_ec_group_incorrect_order() {
1 ✔
820
         Test::Result result("EC_Group rejects incorrect generator order");
1 ✔
821

822
         Botan::EC_Group::clear_registered_curve_data();
1 ✔
823

824
         const auto secp256r1 = Botan::EC_Group::from_name("secp256r1");
1 ✔
825
         const Botan::BigInt wrong_order("0xFFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC6325EB");
1 ✔
826

827
         result.test_throws<Botan::Invalid_Argument>(
1 ✔
828
            "Custom group with incorrect order is rejected", "generator does not have the claimed order", [&] {
1 ✔
829
               static_cast<void>(Botan::EC_Group(Botan::OID("1.3.6.1.4.1.25258.100.101"),
1 ✔
830
                                                 secp256r1.get_p(),
831
                                                 secp256r1.get_a(),
832
                                                 secp256r1.get_b(),
833
                                                 secp256r1.get_g_x(),
834
                                                 secp256r1.get_g_y(),
835
                                                 wrong_order));
836
            });
×
837

838
         const auto wrong_order_der = encode_explicit_group(secp256r1.get_p(),
1 ✔
839
                                                            secp256r1.get_a(),
840
                                                            secp256r1.get_b(),
841
                                                            secp256r1.get_g_x(),
842
                                                            secp256r1.get_g_y(),
843
                                                            wrong_order,
844
                                                            1);
1 ✔
845
         result.test_throws<Botan::Decoding_Error>("Explicit group with incorrect order is rejected",
1 ✔
846
                                                   "generator does not have the claimed order",
847
                                                   [&] { static_cast<void>(Botan::EC_Group(wrong_order_der)); });
2 ✔
848

849
         result.test_throws<Botan::Invalid_Argument>(
1 ✔
850
            "Custom anomalous group is rejected", "Anomalous elliptic curves are not supported", [&] {
1 ✔
851
               static_cast<void>(Botan::EC_Group(Botan::OID("1.3.6.1.4.1.25258.100.102"),
1 ✔
852
                                                 secp256r1.get_p(),
853
                                                 secp256r1.get_a(),
854
                                                 secp256r1.get_b(),
855
                                                 secp256r1.get_g_x(),
856
                                                 secp256r1.get_g_y(),
857
                                                 secp256r1.get_p()));
858
            });
×
859

860
         result.test_throws<Botan::Invalid_Argument>(
1 ✔
861
            "Deprecated constructor rejects anomalous group", "Anomalous elliptic curves are not supported", [&] {
1 ✔
862
               static_cast<void>(Botan::EC_Group(secp256r1.get_p(),
2 ✔
863
                                                 secp256r1.get_a(),
864
                                                 secp256r1.get_b(),
865
                                                 secp256r1.get_g_x(),
866
                                                 secp256r1.get_g_y(),
867
                                                 secp256r1.get_p(),
868
                                                 1));
1 ✔
869
            });
×
870

871
         const auto anomalous_der = encode_explicit_group(secp256r1.get_p(),
1 ✔
872
                                                          secp256r1.get_a(),
873
                                                          secp256r1.get_b(),
874
                                                          secp256r1.get_g_x(),
875
                                                          secp256r1.get_g_y(),
876
                                                          secp256r1.get_p(),
877
                                                          1);
1 ✔
878
         result.test_throws<Botan::Decoding_Error>("Explicit anomalous group is rejected",
1 ✔
879
                                                   "Anomalous elliptic curves are not supported",
880
                                                   [&] { static_cast<void>(Botan::EC_Group(anomalous_der)); });
2 ✔
881

882
         const auto invalid_hasse_der = encode_explicit_group(
1 ✔
883
            secp256r1.get_p(), secp256r1.get_a(), secp256r1.get_b(), secp256r1.get_g_x(), secp256r1.get_g_y(), 2, 1);
1 ✔
884
         result.test_throws<Botan::Decoding_Error>("Explicit group outside the Hasse bound is rejected",
1 ✔
885
                                                   "Invalid ECC Hasse bound",
886
                                                   [&] { static_cast<void>(Botan::EC_Group(invalid_hasse_der)); });
2 ✔
887

888
         const auto singular_der =
1 ✔
889
            encode_explicit_group(secp256r1.get_p(), secp256r1.get_p() - 3, 2, 1, 0, secp256r1.get_order(), 1);
1 ✔
890
         result.test_throws<Botan::Decoding_Error>("Explicit singular curve is rejected",
1 ✔
891
                                                   "Invalid ECC curve discriminant",
892
                                                   [&] { static_cast<void>(Botan::EC_Group(singular_der)); });
2 ✔
893

894
   #if defined(BOTAN_HAS_LEGACY_EC_POINT)
895
         // y^2 = x^3 + 1 over this p has 6*q points. G generates the
896
         // prime-order q subgroup and the differing bit lengths force use of
897
         // the legacy backend.
898
         const Botan::BigInt legacy_p("0x600000000000000000000000000005ED");
1 ✔
899
         const Botan::BigInt legacy_q("0x100000000000000000000000000000FD");
1 ✔
900
         const Botan::BigInt legacy_g_x("0x49140B0575E552D007C01F9A6464B5F3");
1 ✔
901
         const Botan::BigInt legacy_g_y("0x234D45F598F8C9260BA56DB89BAB9D7B");
1 ✔
902

903
         result.test_no_throw("Valid small cofactor group is accepted", [&] {
1 ✔
904
            static_cast<void>(Botan::EC_Group(legacy_p, 0, 1, legacy_g_x, legacy_g_y, legacy_q, 6));
1 ✔
905
         });
1 ✔
906
         result.test_throws<Botan::Invalid_Argument>(
1 ✔
907
            "Legacy group with incorrect order is rejected", "generator does not have the claimed order", [&] {
1 ✔
908
               const Botan::BigInt wrong_legacy_q("0x100000000000000000000000000001E7");
1 ✔
909
               static_cast<void>(Botan::EC_Group(legacy_p, 0, 1, legacy_g_x, legacy_g_y, wrong_legacy_q, 6));
4 ✔
910
            });
1 ✔
911
   #endif
912

913
         return result;
1 ✔
914
      }
5 ✔
915

916
      Test::Result test_ec_group_registration_with_mismatched_custom_oid() {
1 ✔
917
         Test::Result result("EC_Group registration of non-standard group with aliased OID");
1 ✔
918

919
         Botan::EC_Group::clear_registered_curve_data();
1 ✔
920

921
         const auto secp256r1 = Botan::EC_Group::from_name("secp256r1");
1 ✔
922
         const Botan::OID custom_oid("1.3.6.1.4.1.25258.100.100");
1 ✔
923

924
         Botan::OID::register_oid(custom_oid, "secp256r1");
1 ✔
925

926
         // The next prime after secp256r1's order. This satisfies the constructor's
927
         // structural checks, but it is not the order of secp256r1's generator.
928
         const Botan::BigInt wrong_order("0xFFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC6325EB");
1 ✔
929

930
         result.test_throws<Botan::Invalid_Argument>(
1 ✔
931
            "Mismatched parameters are rejected", "generator does not have the claimed order", [&] {
1 ✔
932
               static_cast<void>(Botan::EC_Group(custom_oid,
1 ✔
933
                                                 secp256r1.get_p(),
934
                                                 secp256r1.get_a(),
935
                                                 secp256r1.get_b(),
936
                                                 secp256r1.get_g_x(),
937
                                                 secp256r1.get_g_y(),
938
                                                 wrong_order));
939
            });
×
940

941
         return result;
1 ✔
942
      }
1 ✔
943

944
      Test::Result test_supports_named_group_with_registration() {
1 ✔
945
         Test::Result result("EC_Group::supports_named_group with custom registration");
1 ✔
946

947
         Botan::EC_Group::clear_registered_curve_data();
1 ✔
948

949
         result.test_is_false("Unknown name is not supported",
1 ✔
950
                              Botan::EC_Group::supports_named_group("not_a_real_curve_name_xyz"));
1 ✔
951

952
         const Botan::OID custom_oid("1.3.6.1.4.1.25258.4.9000");
1 ✔
953
         const std::string custom_name = "goku-curve";  // very strong
1 ✔
954

955
         Botan::OID::register_oid(custom_oid, custom_name);
1 ✔
956

957
         result.test_is_false("Mapped OID without registered EC_Group is not supported",
1 ✔
958
                              Botan::EC_Group::supports_named_group(custom_name));
1 ✔
959

960
         const Botan::BigInt p("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF43");
1 ✔
961
         const Botan::BigInt a("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF40");
1 ✔
962
         const Botan::BigInt b("0x25581");
1 ✔
963
         const Botan::BigInt order("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE43C8275EA265C6020AB20294751A825");
1 ✔
964
         const Botan::BigInt g_x("0x01");
1 ✔
965
         const Botan::BigInt g_y("0x696F1853C1E466D7FC82C96CCEEEDD6BD02C2F9375894EC10BF46306C2B56C77");
1 ✔
966

967
         const auto reg_group = Botan::EC_Group::register_custom_group(custom_oid, p, a, b, g_x, g_y, order);
1 ✔
968

969
         result.test_is_true("After registration the custom name is supported",
1 ✔
970
                             Botan::EC_Group::supports_named_group(custom_name));
1 ✔
971

972
         const auto resolved = Botan::EC_Group::from_name(custom_name);
1 ✔
973
         result.test_is_true("from_name resolves to the registered OID", resolved.get_curve_oid() == custom_oid);
1 ✔
974

975
         result.test_is_false("known_named_groups still does not include custom name",
1 ✔
976
                              Botan::EC_Group::known_named_groups().contains(custom_name));
1 ✔
977

978
         result.test_is_true("Unregistering removes support for the custom name",
1 ✔
979
                             Botan::EC_Group::unregister(custom_oid));
1 ✔
980
         result.test_is_false("After unregister the custom name is not supported",
1 ✔
981
                              Botan::EC_Group::supports_named_group(custom_name));
1 ✔
982

983
         return result;
2 ✔
984
      }
1 ✔
985

986
      Test::Result test_ec_group_alias_oid_cache() {
1 ✔
987
         Test::Result result("EC_Group lookup by alias OID does not duplicate cache entry");
1 ✔
988

989
         // TODO(Botan4) once groups are required to have a single canonical OID this test can be removed
990

991
         if(!Botan::EC_Group::known_named_groups().contains("gost_256A")) {
1 ✔
992
            result.test_note("Skipping: gost_256A not enabled in this build");
×
993
            return result;
×
994
         }
995

996
         const Botan::OID gost_canonical("1.2.643.7.1.2.1.1.1");
1 ✔
997
         const std::array<Botan::OID, 2> aliases = {
1 ✔
998
            Botan::OID("1.2.643.2.2.35.1"),
999
            Botan::OID("1.2.643.2.2.36.0"),
1000
         };
1 ✔
1001

1002
         // Exercise every ordering of {canonical, alias_a, alias_b} as the first lookup
1003
         // to confirm the cache dedup works regardless of which OID populates it first.
1004
         const std::array<std::array<Botan::OID, 3>, 3> orderings = {{
1 ✔
1005
            {gost_canonical, aliases[0], aliases[1]},
2 ✔
1006
            {aliases[0], gost_canonical, aliases[1]},
2 ✔
1007
            {aliases[1], aliases[0], gost_canonical},
2 ✔
1008
         }};
1 ✔
1009

1010
         for(const auto& order : orderings) {
4 ✔
1011
            Botan::EC_Group::clear_registered_curve_data();
3 ✔
1012

1013
            const auto first = Botan::EC_Group::from_OID(order[0]);
3 ✔
1014
            const auto second = Botan::EC_Group::from_OID(order[1]);
3 ✔
1015
            const auto third = Botan::EC_Group::from_OID(order[2]);
3 ✔
1016

1017
            result.test_is_true("First lookup yields canonical OID", first.get_curve_oid() == gost_canonical);
3 ✔
1018
            result.test_is_true("Second lookup yields canonical OID", second.get_curve_oid() == gost_canonical);
3 ✔
1019
            result.test_is_true("Third lookup yields canonical OID", third.get_curve_oid() == gost_canonical);
3 ✔
1020

1021
            result.test_is_true("Second lookup shares cached data with first", second._data() == first._data());
3 ✔
1022
            result.test_is_true("Third lookup shares cached data with first", third._data() == first._data());
3 ✔
1023

1024
            for(size_t i = 0; i != 16; ++i) {
51 ✔
1025
               const auto repeated = Botan::EC_Group::from_OID(order[i % 3]);
48 ✔
1026
               result.test_is_true("Repeated lookup is stable", repeated._data() == first._data());
48 ✔
1027
            }
48 ✔
1028
         }
3 ✔
1029

1030
         return result;
1031
      }
2 ✔
1032

1033
      Test::Result test_ec_group_unregistration() {
1 ✔
1034
         Test::Result result("EC_Group unregistration of group");
1 ✔
1035

1036
         Botan::EC_Group::clear_registered_curve_data();
1 ✔
1037

1038
         const Botan::OID secp256r1_oid("1.2.840.10045.3.1.7");
1 ✔
1039
         const auto secp256r1 = Botan::EC_Group::from_OID(secp256r1_oid);
1 ✔
1040
         const Botan::OID custom_oid("1.3.6.1.4.1.25258.100.99");
1 ✔
1041
         Botan::OID::register_oid(custom_oid, "secp256r1");
1 ✔
1042

1043
         const auto reg_group = Botan::EC_Group::register_custom_group(custom_oid,
1 ✔
1044
                                                                       secp256r1.get_p(),
1045
                                                                       secp256r1.get_a(),
1046
                                                                       secp256r1.get_b(),
1047
                                                                       secp256r1.get_g_x(),
1048
                                                                       secp256r1.get_g_y(),
1049
                                                                       secp256r1.get_order());
1 ✔
1050

1051
         const Botan::EC_Group group_from_oid = Botan::EC_Group::from_OID(custom_oid);
1 ✔
1052

1053
         result.test_is_true("Internal group is unregistered", Botan::EC_Group::unregister(secp256r1_oid));
1 ✔
1054
         result.test_is_false("Unregistering internal group again does nothing",
1 ✔
1055
                              Botan::EC_Group::unregister(secp256r1_oid));
1 ✔
1056
         result.test_is_true("User defined group is unregistered", Botan::EC_Group::unregister(custom_oid));
1 ✔
1057
         result.test_is_false("Unregistering user defined group again does nothing",
1 ✔
1058
                              Botan::EC_Group::unregister(custom_oid));
1 ✔
1059

1060
         try {
1 ✔
1061
            Botan::EC_Group::from_OID(custom_oid);
1 ✔
1062
            result.test_failure("Should have failed");
×
1063
         } catch(Botan::Invalid_Argument&) {
1 ✔
1064
            result.test_success("Got expected exception");
1 ✔
1065
         }
1 ✔
1066

1067
         result.test_is_true("Group can still be accessed", reg_group.get_curve_oid() == custom_oid);
1 ✔
1068
         result.test_is_true("Group has correct p parameter", reg_group.get_p() == secp256r1.get_p());
1 ✔
1069
         result.test_is_true("Group has correct a parameter", reg_group.get_a() == secp256r1.get_a());
1 ✔
1070
         result.test_is_true("Group has correct b parameter", reg_group.get_b() == secp256r1.get_b());
1 ✔
1071
         result.test_is_true("Group has correct g_x parameter", reg_group.get_g_x() == secp256r1.get_g_x());
1 ✔
1072
         result.test_is_true("Group has correct g_y parameter", reg_group.get_g_y() == secp256r1.get_g_y());
1 ✔
1073
         result.test_is_true("Group has correct order parameter", reg_group.get_order() == secp256r1.get_order());
1 ✔
1074

1075
   #if defined(BOTAN_HAS_ECDSA)
1076
         std::unique_ptr<Botan::RandomNumberGenerator> rng = Test::new_rng("test_ec_group_unregistration");
1 ✔
1077
         std::unique_ptr<Botan::Private_Key> key = Botan::create_ec_private_key("ECDSA", group_from_oid, *rng);
1 ✔
1078
         result.test_success("Can still use group to create a key");
1 ✔
1079
         result.test_is_true("Key was created correctly", key->check_key(*rng, true));
1 ✔
1080
   #endif
1081

1082
         // TODO(Botan4) remove this when OIDs lose internal nullability
1083
         try {
1 ✔
1084
            const Botan::OID empty_oid("");
1 ✔
1085
            Botan::EC_Group::unregister(empty_oid);
1 ✔
1086
            result.test_failure("Should have failed");
×
1087
         } catch(Botan::Invalid_Argument&) {
1 ✔
1088
            result.test_success("Got expected exception");
1 ✔
1089
         }
1 ✔
1090

1091
         return result;
1 ✔
1092
      }
2 ✔
1093
};
1094

1095
BOTAN_REGISTER_SERIALIZED_TEST("pubkey", "ec_group_registration", EC_Group_Registration_Tests);
1096

1097
class EC_PointEnc_Tests final : public Test {
1 ✔
1098
   public:
1099
      std::vector<Test::Result> run() override {
1 ✔
1100
         std::vector<Test::Result> results;
1 ✔
1101

1102
         auto& rng = Test::rng();
1 ✔
1103

1104
         for(const auto& group_id : Botan::EC_Group::known_named_groups()) {
29 ✔
1105
            const auto group = Botan::EC_Group::from_name(group_id);
28 ✔
1106

1107
            Result result("EC_AffinePoint encoding " + group_id);
28 ✔
1108

1109
            result.start_timer();
28 ✔
1110

1111
            // The SEC1 encoding of the identity element; accepted by the
1112
            // permissive deserialization but not the strict variants
1113
            const std::vector<uint8_t> id_encoding{0x00};
28 ✔
1114

1115
            result.test_is_true("Permissive deserialization accepts the identity encoding",
56 ✔
1116
                                Botan::EC_AffinePoint::deserialize(group, id_encoding).has_value());
28 ✔
1117
            result.test_is_false("deserialize_uncompressed rejects the identity encoding",
56 ✔
1118
                                 Botan::EC_AffinePoint::deserialize_uncompressed(group, id_encoding).has_value());
28 ✔
1119
            result.test_is_false("deserialize_compressed rejects the identity encoding",
56 ✔
1120
                                 Botan::EC_AffinePoint::deserialize_compressed(group, id_encoding).has_value());
28 ✔
1121

1122
            result.test_is_false("deserialize_uncompressed rejects empty input",
56 ✔
1123
                                 Botan::EC_AffinePoint::deserialize_uncompressed(group, {}).has_value());
28 ✔
1124
            result.test_is_false("deserialize_compressed rejects empty input",
56 ✔
1125
                                 Botan::EC_AffinePoint::deserialize_compressed(group, {}).has_value());
28 ✔
1126

1127
            for(size_t trial = 0; trial != 100; ++trial) {
2,828 ✔
1128
               const auto scalar = Botan::EC_Scalar::random(group, rng);
2,800 ✔
1129
               const auto pt = Botan::EC_AffinePoint::g_mul(scalar, rng);
2,800 ✔
1130

1131
               const auto pt_u = pt.serialize_uncompressed();
2,800 ✔
1132
               result.test_u8_eq("Expected uncompressed header", pt_u[0], 0x04);
2,800 ✔
1133
               const size_t fe_bytes = (pt_u.size() - 1) / 2;
2,800 ✔
1134
               const auto pt_c = pt.serialize_compressed();
2,800 ✔
1135

1136
               result.test_sz_eq("Expected compressed size", pt_c.size(), 1 + fe_bytes);
2,800 ✔
1137
               const uint8_t expected_c_header = (pt_u[pt_u.size() - 1] % 2 == 0) ? 0x02 : 0x03;
2,800 ✔
1138
               result.test_u8_eq("Expected compressed header", pt_c[0], expected_c_header);
2,800 ✔
1139

1140
               result.test_bin_eq(
2,800 ✔
1141
                  "Expected compressed x", std::span{pt_c}.subspan(1), std::span{pt_u}.subspan(1, fe_bytes));
1142

1143
               if(auto d_pt_u = Botan::EC_AffinePoint::deserialize(group, pt_u)) {
2,800 ✔
1144
                  result.test_bin_eq(
2,800 ✔
1145
                     "Deserializing uncompressed returned correct point", d_pt_u->serialize_uncompressed(), pt_u);
5,600 ✔
1146
               } else {
1147
                  result.test_failure("Failed to deserialize uncompressed point");
×
1148
               }
×
1149

1150
               if(auto d_pt_c = Botan::EC_AffinePoint::deserialize(group, pt_c)) {
2,800 ✔
1151
                  result.test_bin_eq(
2,800 ✔
1152
                     "Deserializing compressed returned correct point", d_pt_c->serialize_uncompressed(), pt_u);
5,600 ✔
1153
               } else {
1154
                  result.test_failure("Failed to deserialize compressed point");
×
1155
               }
×
1156

1157
               const auto neg_pt_c = [&]() {
2,800 ✔
1158
                  auto x = pt_c;
2,800 ✔
1159
                  x[0] ^= 0x01;
2,800 ✔
1160
                  return x;
2,800 ✔
1161
               }();
2,800 ✔
1162

1163
               if(auto d_neg_pt_c = Botan::EC_AffinePoint::deserialize(group, neg_pt_c)) {
2,800 ✔
1164
                  result.test_bin_eq("Deserializing compressed with inverted header returned negated point",
2,800 ✔
1165
                                     d_neg_pt_c->serialize_uncompressed(),
5,600 ✔
1166
                                     pt.negate().serialize_uncompressed());
5,600 ✔
1167
               } else {
1168
                  result.test_failure("Failed to deserialize compressed point");
×
1169
               }
×
1170

1171
               // The deprecated hybrid encoding; accepted by the permissive
1172
               // deserialization (until Botan4) but not the strict variants
1173
               const auto pt_h = [&]() {
×
1174
                  auto x = pt_u;
2,800 ✔
1175
                  x[0] = ((pt_u[pt_u.size() - 1] & 0x01) == 0x01) ? 0x07 : 0x06;
2,800 ✔
1176
                  return x;
2,800 ✔
1177
               }();
2,800 ✔
1178

1179
               if(auto d_pt_h = Botan::EC_AffinePoint::deserialize(group, pt_h)) {
2,800 ✔
1180
                  result.test_bin_eq(
2,800 ✔
1181
                     "Permissive deserialization accepts hybrid encoding", d_pt_h->serialize_uncompressed(), pt_u);
5,600 ✔
1182
               } else {
1183
                  result.test_failure("Failed to deserialize hybrid point");
×
1184
               }
×
1185

1186
               if(auto d_pt_u = Botan::EC_AffinePoint::deserialize_uncompressed(group, pt_u)) {
2,800 ✔
1187
                  result.test_bin_eq(
2,800 ✔
1188
                     "deserialize_uncompressed accepts uncompressed", d_pt_u->serialize_uncompressed(), pt_u);
5,600 ✔
1189
               } else {
1190
                  result.test_failure("Failed to deserialize uncompressed point");
×
1191
               }
×
1192

1193
               result.test_is_false("deserialize_uncompressed rejects compressed",
5,600 ✔
1194
                                    Botan::EC_AffinePoint::deserialize_uncompressed(group, pt_c).has_value());
2,800 ✔
1195
               result.test_is_false("deserialize_uncompressed rejects hybrid",
5,600 ✔
1196
                                    Botan::EC_AffinePoint::deserialize_uncompressed(group, pt_h).has_value());
2,800 ✔
1197
               result.test_is_false(
5,600 ✔
1198
                  "deserialize_uncompressed rejects truncated input",
1199
                  Botan::EC_AffinePoint::deserialize_uncompressed(group, std::span{pt_u}.first(pt_u.size() - 1))
×
1200
                     .has_value());
2,800 ✔
1201

1202
               if(auto d_pt_c = Botan::EC_AffinePoint::deserialize_compressed(group, pt_c)) {
2,800 ✔
1203
                  result.test_bin_eq(
2,800 ✔
1204
                     "deserialize_compressed accepts compressed", d_pt_c->serialize_uncompressed(), pt_u);
5,600 ✔
1205
               } else {
1206
                  result.test_failure("Failed to deserialize compressed point");
×
1207
               }
×
1208

1209
               result.test_is_false("deserialize_compressed rejects uncompressed",
5,600 ✔
1210
                                    Botan::EC_AffinePoint::deserialize_compressed(group, pt_u).has_value());
2,800 ✔
1211
               result.test_is_false("deserialize_compressed rejects hybrid",
5,600 ✔
1212
                                    Botan::EC_AffinePoint::deserialize_compressed(group, pt_h).has_value());
2,800 ✔
1213
               result.test_is_false(
5,600 ✔
1214
                  "deserialize_compressed rejects truncated input",
1215
                  Botan::EC_AffinePoint::deserialize_compressed(group, std::span{pt_c}.first(pt_c.size() - 1))
2,800 ✔
1216
                     .has_value());
2,800 ✔
1217
            }
5,600 ✔
1218

1219
            result.end_timer();
28 ✔
1220

1221
            results.push_back(result);
28 ✔
1222
         }
28 ✔
1223

1224
         return results;
1 ✔
1225
      }
8,400 ✔
1226
};
1227

1228
BOTAN_REGISTER_TEST("pubkey", "ec_point_enc", EC_PointEnc_Tests);
1229

1230
class EC_Point_Arithmetic_Tests final : public Test {
1 ✔
1231
   public:
1232
      std::vector<Test::Result> run() override {
1 ✔
1233
         std::vector<Test::Result> results;
1 ✔
1234

1235
         auto& rng = Test::rng();
1 ✔
1236

1237
         for(const auto& group_id : Botan::EC_Group::known_named_groups()) {
29 ✔
1238
            const auto group = Botan::EC_Group::from_name(group_id);
28 ✔
1239

1240
            Result result("EC_AffinePoint arithmetic " + group_id);
28 ✔
1241

1242
            result.start_timer();
28 ✔
1243

1244
            const auto one = Botan::EC_Scalar::one(group);
28 ✔
1245
            const auto zero = one - one;  // NOLINT(*-redundant-expression)
28 ✔
1246
            const auto g = Botan::EC_AffinePoint::generator(group);
28 ✔
1247
            const auto g_bytes = g.serialize_uncompressed();
28 ✔
1248

1249
            auto moved_from = Botan::EC_Scalar::from_bigint(group, 1);
28 ✔
1250
            const auto replacement = Botan::EC_Scalar::from_bigint(group, 2);
28 ✔
1251
            auto moved_to = std::move(moved_from);
28 ✔
1252
            const auto as_rvalue = [](auto& x) -> decltype(auto) { return std::move(x); };
28 ✔
1253
            moved_from = as_rvalue(moved_from);
28 ✔
1254
            moved_from = replacement;
28 ✔
1255
            result.test_is_true("copy assignment into moved-from EC_Scalar", moved_from == replacement);
28 ✔
1256
            moved_from = std::move(moved_to);
28 ✔
1257
            result.test_is_true("move assignment into EC_Scalar", moved_from == one);
28 ✔
1258
            const auto before_self_move = moved_from.to_bigint();
28 ✔
1259
            moved_from = as_rvalue(moved_from);
28 ✔
1260
            result.test_bn_eq("self-move keeps EC_Scalar value", moved_from.to_bigint(), before_self_move);
28 ✔
1261

1262
            const auto id = Botan::EC_AffinePoint::g_mul(zero, rng);
28 ✔
1263
            result.test_is_true("g*zero is point at identity", id.is_identity());
28 ✔
1264

1265
            const auto id2 = id.add(id);
28 ✔
1266
            result.test_is_true("identity plus itself is identity", id2.is_identity());
28 ✔
1267

1268
            result.test_bn_eq("generator get_affine_x", g.get_affine_x(), group.get_g_x());
28 ✔
1269
            result.test_bn_eq("generator get_affine_y", g.get_affine_y(), group.get_g_y());
28 ✔
1270
            result.test_throws<Botan::Invalid_State>("identity get_affine_x throws", [&] { id.get_affine_x(); });
56 ✔
1271
            result.test_throws<Botan::Invalid_State>("identity get_affine_y throws", [&] { id.get_affine_y(); });
56 ✔
1272

1273
            const auto g_one = Botan::EC_AffinePoint::g_mul(one, rng);
28 ✔
1274
            result.test_bin_eq("g*one == generator", g_one.serialize_uncompressed(), g_bytes);
28 ✔
1275

1276
            const auto g_plus_id = g_one.add(id);
28 ✔
1277
            result.test_bin_eq("g + id == g", g_plus_id.serialize_uncompressed(), g_bytes);
28 ✔
1278

1279
            const auto id_plus_g = id.add(g_one);
28 ✔
1280
            result.test_bin_eq("id + g == g", id_plus_g.serialize_uncompressed(), g_bytes);
28 ✔
1281

1282
            const auto g_neg_one = Botan::EC_AffinePoint::g_mul(one.negate(), rng);
28 ✔
1283

1284
            const auto id_from_g = g_one.add(g_neg_one);
28 ✔
1285
            result.test_is_true("g - g is identity", id_from_g.is_identity());
28 ✔
1286

1287
            const auto g_two = Botan::EC_AffinePoint::g_mul(one + one, rng);
28 ✔
1288
            const auto g_plus_g = g_one.add(g_one);
28 ✔
1289
            result.test_bin_eq("2*g == g+g", g_two.serialize_uncompressed(), g_plus_g.serialize_uncompressed());
56 ✔
1290

1291
            result.test_is_true("Scalar::zero is zero", zero.is_zero());
28 ✔
1292
            result.test_is_true("(zero+zero) is zero", (zero + zero).is_zero());
28 ✔
1293
            result.test_is_true("(zero*zero) is zero", (zero * zero).is_zero());
28 ✔
1294
            result.test_is_true("(zero-zero) is zero", (zero - zero).is_zero());  // NOLINT(*-redundant-expression)
28 ✔
1295

1296
            const auto neg_zero = zero.negate();
28 ✔
1297
            result.test_is_true("zero.negate() is zero", neg_zero.is_zero());
28 ✔
1298

1299
            result.test_is_true("(zero+nz) is zero", (zero + neg_zero).is_zero());
28 ✔
1300
            result.test_is_true("(nz+nz) is zero", (neg_zero + neg_zero).is_zero());
28 ✔
1301
            result.test_is_true("(nz+zero) is zero", (neg_zero + zero).is_zero());
28 ✔
1302

1303
            result.test_is_true("Scalar::one is not zero", !one.is_zero());
28 ✔
1304
            result.test_is_true("(one-one) is zero", (one - one).is_zero());  // NOLINT(*-redundant-expression)
28 ✔
1305
            result.test_is_true("(one+one.negate()) is zero", (one + one.negate()).is_zero());
56 ✔
1306
            result.test_is_true("(one.negate()+one) is zero", (one.negate() + one).is_zero());
56 ✔
1307

1308
            for(size_t i = 0; i != 16; ++i) {
476 ✔
1309
               const auto pt = Botan::EC_AffinePoint::g_mul(Botan::EC_Scalar::random(group, rng), rng);
448 ✔
1310

1311
               const auto a = Botan::EC_Scalar::random(group, rng);
448 ✔
1312
               const auto b = Botan::EC_Scalar::random(group, rng);
448 ✔
1313
               const auto c = a + b;
448 ✔
1314

1315
               const auto Pa = pt.mul(a, rng);
448 ✔
1316
               const auto Pb = pt.mul(b, rng);
448 ✔
1317
               const auto Pc = pt.mul(c, rng);
448 ✔
1318

1319
               const auto Pc_bytes = Pc.serialize_uncompressed();
448 ✔
1320

1321
               const auto Pab = Pa.add(Pb);
448 ✔
1322
               result.test_bin_eq("Pa + Pb == Pc", Pab.serialize_uncompressed(), Pc_bytes);
448 ✔
1323

1324
               const auto Pba = Pb.add(Pa);
448 ✔
1325
               result.test_bin_eq("Pb + Pa == Pc", Pba.serialize_uncompressed(), Pc_bytes);
448 ✔
1326
            }
896 ✔
1327

1328
            for(size_t i = 0; i != 64; ++i) {
1,820 ✔
1329
               const auto h = [&]() {
5,376 ✔
1330
                  const auto s = [&]() {
5,376 ✔
1331
                     if(i == 0) {
1,792 ✔
1332
                        // Test the identity case
1333
                        return Botan::EC_Scalar(zero);
28 ✔
1334
                     } else if(i <= 32) {
1,764 ✔
1335
                        // Test cases where the two points have a linear relation
1336
                        std::vector<uint8_t> sbytes(group.get_order_bytes());
896 ✔
1337
                        sbytes[sbytes.size() - 1] = static_cast<uint8_t>((i + 1) / 2);
896 ✔
1338
                        auto si = Botan::EC_Scalar::deserialize(group, sbytes).value();
1,792 ✔
1339
                        if(i % 2 == 0) {
896 ✔
1340
                           return si;
448 ✔
1341
                        } else {
1342
                           return si.negate();
448 ✔
1343
                        }
1344
                     } else {
1,792 ✔
1345
                        return Botan::EC_Scalar::random(group, rng);
868 ✔
1346
                     }
1347
                  }();
1,792 ✔
1348
                  auto x = Botan::EC_AffinePoint::g_mul(s, rng);
1,792 ✔
1349
                  return x;
1,792 ✔
1350
               }();
3,584 ✔
1351

1352
               const auto s1 = Botan::EC_Scalar::random(group, rng);
1,792 ✔
1353
               const auto s2 = Botan::EC_Scalar::random(group, rng);
1,792 ✔
1354

1355
               const Botan::EC_Group::Mul2Table mul2_table(h);
1,792 ✔
1356

1357
               const auto ref = Botan::EC_AffinePoint::g_mul(s1, rng).add(h.mul(s2, rng));
1,792 ✔
1358

1359
               if(auto mul2pt = mul2_table.mul2_vartime(s1, s2)) {
1,792 ✔
1360
                  result.test_bin_eq("ref == mul2t", ref.serialize_uncompressed(), mul2pt->serialize_uncompressed());
5,376 ✔
1361
               } else {
1362
                  result.test_is_true("ref is identity", ref.is_identity());
×
1363
               }
×
1364
            }
1,792 ✔
1365

1366
            // Edge cases for the variable time 2-ary multiplication: zero
1367
            // scalars, cancellation, and partial sums which coincide with
1368
            // table entries (forcing the exceptional addition paths)
1369
            {
28 ✔
1370
               const auto check_mul2 = [&](const std::string& what,
14,934 ✔
1371
                                           const Botan::EC_AffinePoint& h,
1372
                                           const Botan::EC_Group::Mul2Table& tbl,
1373
                                           const Botan::EC_Scalar& s1,
1374
                                           const Botan::EC_Scalar& s2) {
1375
                  const auto ref = Botan::EC_AffinePoint::g_mul(s1, rng).add(h.mul(s2, rng));
14,906 ✔
1376
                  if(auto mul2pt = tbl.mul2_vartime(s1, s2)) {
14,906 ✔
1377
                     result.test_bin_eq(what, mul2pt->serialize_uncompressed(), ref.serialize_uncompressed());
34,854 ✔
1378
                  } else {
1379
                     result.test_is_true(what + " is identity", ref.is_identity());
6,576 ✔
1380
                  }
×
1381
               };
14,906 ✔
1382

1383
               const auto scalar_of = [&](const Botan::BigInt& v) { return Botan::EC_Scalar::from_bigint(group, v); };
4,636 ✔
1384

1385
               const auto r1 = Botan::EC_Scalar::random(group, rng);
28 ✔
1386
               const auto r2 = Botan::EC_Scalar::random(group, rng);
28 ✔
1387
               const auto zero_s = r1 - r1;  // NOLINT(*-redundant-expression)
28 ✔
1388

1389
               const auto h = Botan::EC_AffinePoint::g_mul(Botan::EC_Scalar::random(group, rng), rng);
28 ✔
1390
               const Botan::EC_Group::Mul2Table h_table(h);
28 ✔
1391

1392
               check_mul2("mul2 s1=0", h, h_table, zero_s, r2);
28 ✔
1393
               check_mul2("mul2 s2=0", h, h_table, r1, zero_s);
28 ✔
1394
               check_mul2("mul2 s1=s2=0", h, h_table, zero_s, zero_s);
28 ✔
1395

1396
               // Small and near-order scalars exercise the digit recoding boundaries
1397
               for(uint64_t i = 1; i != 70; ++i) {
1,960 ✔
1398
                  const auto si = scalar_of(Botan::BigInt::from_u64(i));
3,864 ✔
1399
                  check_mul2("mul2 small s2", h, h_table, r1, si);
1,932 ✔
1400
                  check_mul2("mul2 small s1", h, h_table, si, r2);
1,932 ✔
1401
                  check_mul2("mul2 small -s2", h, h_table, r1, si.negate());
3,864 ✔
1402
                  check_mul2("mul2 small -s1", h, h_table, si.negate(), r2);
3,864 ✔
1403
               }
1,932 ✔
1404

1405
               for(size_t i = 1; i < group.get_order_bits(); i += 7) {
1,130 ✔
1406
                  const auto si = scalar_of(Botan::BigInt::power_of_2(i));
2,204 ✔
1407
                  check_mul2("mul2 s2=2^i", h, h_table, r1, si);
1,102 ✔
1408
                  check_mul2("mul2 s2=-2^i", h, h_table, r1, si.negate());
2,204 ✔
1409
               }
1,102 ✔
1410

1411
               // With h = G (or -G) the two halves can cancel or coincide
1412
               const Botan::EC_Group::Mul2Table g_table(g);
28 ✔
1413
               const Botan::EC_Group::Mul2Table neg_g_table(g.negate());
28 ✔
1414

1415
               check_mul2("mul2 g s1=s2", g, g_table, r1, r1);
28 ✔
1416
               check_mul2("mul2 g s1=-s2", g, g_table, r1, r1.negate());
56 ✔
1417
               check_mul2("mul2 -g s1=s2", g.negate(), neg_g_table, r1, r1);
56 ✔
1418

1419
               for(size_t k = 0; 6 * k + 6 < group.get_order_bits(); k += 5) {
295 ✔
1420
                  for(const uint64_t m : {1, 5, 31, 32, 33, 63}) {
1,869 ✔
1421
                     const auto si = scalar_of(Botan::BigInt::from_u64(m) << (6 * k));
3,204 ✔
1422
                     check_mul2("mul2 g coincident", g, g_table, si, si);
1,602 ✔
1423
                     check_mul2("mul2 g coincident neg", g, g_table, si, si.negate());
3,204 ✔
1424
                     check_mul2("mul2 -g coincident", g.negate(), neg_g_table, si, si);
3,204 ✔
1425
                  }
1,602 ✔
1426
               }
1427
            }
28 ✔
1428

1429
            result.end_timer();
28 ✔
1430

1431
            results.push_back(result);
28 ✔
1432
         }
56 ✔
1433

1434
         return results;
1 ✔
1435
      }
×
1436
};
1437

1438
BOTAN_REGISTER_TEST("pubkey", "ec_point_arith", EC_Point_Arithmetic_Tests);
1439

1440
   #if defined(BOTAN_HAS_ECDSA)
1441

1442
class ECC_Invalid_Key_Tests final : public Text_Based_Test {
×
1443
   public:
1444
      ECC_Invalid_Key_Tests() : Text_Based_Test("pubkey/ecc_invalid.vec", "SubjectPublicKey") {}
2 ✔
1445

1446
      bool clear_between_callbacks() const override { return false; }
5 ✔
1447

1448
      Test::Result run_one_test(const std::string& /*header*/, const VarMap& vars) override {
5 ✔
1449
         Test::Result result("ECC invalid keys");
5 ✔
1450

1451
         const std::string encoded = vars.get_req_str("SubjectPublicKey");
5 ✔
1452
         Botan::DataSource_Memory key_data(Botan::hex_decode(encoded));
10 ✔
1453

1454
         try {
5 ✔
1455
            auto key = Botan::X509::load_key(key_data);
5 ✔
1456
            result.test_is_false("public key fails check", key->check_key(this->rng(), false));
×
1457
         } catch(Botan::Decoding_Error&) {
5 ✔
1458
            result.test_success("Decoding invalid ECC key results in decoding error exception");
5 ✔
1459
         }
5 ✔
1460

1461
         return result;
5 ✔
1462
      }
5 ✔
1463
};
1464

1465
BOTAN_REGISTER_TEST("pubkey", "ecc_invalid", ECC_Invalid_Key_Tests);
1466

1467
   #endif
1468

1469
#endif
1470

1471
}  // namespace
1472

1473
}  // 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