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

randombit / botan / 10427677597

16 Aug 2024 11:51PM UTC coverage: 91.282% (+0.005%) from 91.277%
10427677597

push

github

web-flow
Merge pull request #4311 from randombit/jack/timer-fixes

Fix timer usage in benchmarks

87851 of 96241 relevant lines covered (91.28%)

9135190.41 hits per line

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

80.57
/src/cli/speed.cpp
1
/*
2
* (C) 2009,2010,2014,2015,2017,2018 Jack Lloyd
3
* (C) 2015 Simon Warta (Kullo GmbH)
4
*
5
* Botan is released under the Simplified BSD License (see license.txt)
6
*/
7

8
#include "../tests/test_rng.h"  // FIXME
9
#include "cli.h"
10

11
#include <algorithm>
12
#include <chrono>
13
#include <functional>
14
#include <iomanip>
15
#include <map>
16
#include <set>
17
#include <sstream>
18

19
// Always available:
20
#include <botan/entropy_src.h>
21
#include <botan/version.h>
22
#include <botan/internal/cpuid.h>
23
#include <botan/internal/fmt.h>
24
#include <botan/internal/os_utils.h>
25
#include <botan/internal/stl_util.h>
26
#include <botan/internal/timer.h>
27

28
#if defined(BOTAN_HAS_BIGINT)
29
   #include <botan/bigint.h>
30
   #include <botan/internal/divide.h>
31
#endif
32

33
#if defined(BOTAN_HAS_BLOCK_CIPHER)
34
   #include <botan/block_cipher.h>
35
#endif
36

37
#if defined(BOTAN_HAS_STREAM_CIPHER)
38
   #include <botan/stream_cipher.h>
39
#endif
40

41
#if defined(BOTAN_HAS_HASH)
42
   #include <botan/hash.h>
43
#endif
44

45
#if defined(BOTAN_HAS_XOF)
46
   #include <botan/xof.h>
47
#endif
48

49
#if defined(BOTAN_HAS_CIPHER_MODES)
50
   #include <botan/cipher_mode.h>
51
#endif
52

53
#if defined(BOTAN_HAS_MAC)
54
   #include <botan/mac.h>
55
#endif
56

57
#if defined(BOTAN_HAS_BASE64_CODEC)
58
   #include <botan/base64.h>
59
#endif
60

61
#if defined(BOTAN_HAS_HEX_CODEC)
62
   #include <botan/hex.h>
63
#endif
64

65
#if defined(BOTAN_HAS_AUTO_SEEDING_RNG)
66
   #include <botan/auto_rng.h>
67
#endif
68

69
#if defined(BOTAN_HAS_SYSTEM_RNG)
70
   #include <botan/system_rng.h>
71
#endif
72

73
#if defined(BOTAN_HAS_HMAC_DRBG)
74
   #include <botan/hmac_drbg.h>
75
#endif
76

77
#if defined(BOTAN_HAS_PROCESSOR_RNG)
78
   #include <botan/processor_rng.h>
79
#endif
80

81
#if defined(BOTAN_HAS_CHACHA_RNG)
82
   #include <botan/chacha_rng.h>
83
#endif
84

85
#if defined(BOTAN_HAS_FPE_FE1)
86
   #include <botan/fpe_fe1.h>
87
#endif
88

89
#if defined(BOTAN_HAS_RFC3394_KEYWRAP)
90
   #include <botan/rfc3394.h>
91
#endif
92

93
#if defined(BOTAN_HAS_COMPRESSION)
94
   #include <botan/compression.h>
95
#endif
96

97
#if defined(BOTAN_HAS_POLY_DBL)
98
   #include <botan/internal/poly_dbl.h>
99
#endif
100

101
#if defined(BOTAN_HAS_PUBLIC_KEY_CRYPTO)
102
   #include <botan/pk_algs.h>
103
   #include <botan/pkcs8.h>
104
   #include <botan/pubkey.h>
105
   #include <botan/x509_key.h>
106
   #include <botan/internal/workfactor.h>
107
#endif
108

109
#if defined(BOTAN_HAS_NUMBERTHEORY)
110
   #include <botan/numthry.h>
111
   #include <botan/reducer.h>
112
   #include <botan/internal/curve_nistp.h>
113
   #include <botan/internal/primality.h>
114
#endif
115

116
#if defined(BOTAN_HAS_ECC_GROUP)
117
   #include <botan/ec_group.h>
118
#endif
119

120
#if defined(BOTAN_HAS_PCURVES)
121
   #include <botan/internal/pcurves.h>
122
#endif
123

124
#if defined(BOTAN_HAS_DL_GROUP)
125
   #include <botan/dl_group.h>
126
#endif
127

128
#if defined(BOTAN_HAS_MCELIECE)
129
   #include <botan/mceliece.h>
130
#endif
131

132
#if defined(BOTAN_HAS_KYBER) || defined(BOTAN_HAS_KYBER_90S)
133
   #include <botan/kyber.h>
134
#endif
135

136
#if defined(BOTAN_HAS_DILITHIUM) || defined(BOTAN_HAS_DILITHIUM_AES)
137
   #include <botan/dilithium.h>
138
#endif
139

140
#if defined(BOTAN_HAS_HSS_LMS)
141
   #include <botan/hss_lms.h>
142
#endif
143

144
#if defined(BOTAN_HAS_SPHINCS_PLUS_WITH_SHA2) || defined(BOTAN_HAS_SPHINCS_PLUS_WITH_SHAKE)
145
   #include <botan/sphincsplus.h>
146
#endif
147

148
#if defined(BOTAN_HAS_FRODOKEM)
149
   #include <botan/frodokem.h>
150
#endif
151

152
#if defined(BOTAN_HAS_ECDSA)
153
   #include <botan/ecdsa.h>
154
#endif
155

156
#if defined(BOTAN_HAS_BCRYPT)
157
   #include <botan/bcrypt.h>
158
#endif
159

160
#if defined(BOTAN_HAS_PASSHASH9)
161
   #include <botan/passhash9.h>
162
#endif
163

164
#if defined(BOTAN_HAS_PASSWORD_HASHING)
165
   #include <botan/pwdhash.h>
166
#endif
167

168
#if defined(BOTAN_HAS_ZFEC)
169
   #include <botan/zfec.h>
170
#endif
171

172
namespace Botan_CLI {
173

174
using Botan::Timer;
175

176
namespace {
177

178
class JSON_Output final {
2✔
179
   public:
180
      void add(const Timer& timer) { m_results.push_back(timer); }
2✔
181

182
      std::string print() const {
1✔
183
         std::ostringstream out;
1✔
184

185
         out << "[\n";
1✔
186

187
         for(size_t i = 0; i != m_results.size(); ++i) {
3✔
188
            const Timer& t = m_results[i];
2✔
189

190
            out << "{"
2✔
191
                << "\"algo\": \"" << t.get_name() << "\", "
2✔
192
                << "\"op\": \"" << t.doing() << "\", "
2✔
193
                << "\"events\": " << t.events() << ", ";
2✔
194

195
            if(t.cycles_consumed() > 0) {
4✔
196
               out << "\"cycles\": " << t.cycles_consumed() << ", ";
4✔
197
            }
198

199
            if(t.buf_size() > 0) {
2✔
200
               out << "\"bps\": " << static_cast<uint64_t>(t.events() / (t.value() / 1000000000.0)) << ", ";
2✔
201
               out << "\"buf_size\": " << t.buf_size() << ", ";
2✔
202
            }
203

204
            out << "\"nanos\": " << t.value() << "}";
2✔
205

206
            if(i != m_results.size() - 1) {
2✔
207
               out << ",";
1✔
208
            }
209

210
            out << "\n";
2✔
211
         }
212
         out << "]\n";
1✔
213

214
         return out.str();
2✔
215
      }
1✔
216

217
   private:
218
      std::vector<Timer> m_results;
219
};
220

221
class Summary final {
1✔
222
   public:
223
      Summary() = default;
1✔
224

225
      void add(const Timer& t) {
2✔
226
         if(t.buf_size() == 0) {
2✔
227
            m_ops_entries.push_back(t);
×
228
         } else {
229
            m_bps_entries[std::make_pair(t.doing(), t.get_name())].push_back(t);
4✔
230
         }
231
      }
2✔
232

233
      std::string print() {
1✔
234
         const size_t name_padding = 35;
1✔
235
         const size_t op_name_padding = 16;
1✔
236
         const size_t op_padding = 16;
1✔
237

238
         std::ostringstream result_ss;
1✔
239
         result_ss << std::fixed;
1✔
240

241
         if(!m_bps_entries.empty()) {
1✔
242
            result_ss << "\n";
1✔
243

244
            // add table header
245
            result_ss << std::setw(name_padding) << std::left << "algo" << std::setw(op_name_padding) << std::left
1✔
246
                      << "operation";
1✔
247

248
            for(const Timer& t : m_bps_entries.begin()->second) {
2✔
249
               result_ss << std::setw(op_padding) << std::right << (std::to_string(t.buf_size()) + " bytes");
2✔
250
            }
251
            result_ss << "\n";
1✔
252

253
            // add table entries
254
            for(const auto& entry : m_bps_entries) {
3✔
255
               if(entry.second.empty()) {
2✔
256
                  continue;
×
257
               }
258

259
               result_ss << std::setw(name_padding) << std::left << (entry.first.second) << std::setw(op_name_padding)
2✔
260
                         << std::left << (entry.first.first);
2✔
261

262
               for(const Timer& t : entry.second) {
4✔
263
                  if(t.events() == 0) {
2✔
264
                     result_ss << std::setw(op_padding) << std::right << "N/A";
×
265
                  } else {
266
                     result_ss << std::setw(op_padding) << std::right << std::setprecision(2)
2✔
267
                               << (t.bytes_per_second() / 1000.0);
2✔
268
                  }
269
               }
270

271
               result_ss << "\n";
2✔
272
            }
273

274
            result_ss << "\n[results are the number of 1000s bytes processed per second]\n";
1✔
275
         }
276

277
         if(!m_ops_entries.empty()) {
1✔
278
            result_ss << std::setprecision(6) << "\n";
×
279

280
            // sort entries
281
            std::sort(m_ops_entries.begin(), m_ops_entries.end());
×
282

283
            // add table header
284
            result_ss << std::setw(name_padding) << std::left << "algo" << std::setw(op_name_padding) << std::left
×
285
                      << "operation" << std::setw(op_padding) << std::right << "sec/op" << std::setw(op_padding)
×
286
                      << std::right << "op/sec"
×
287
                      << "\n";
×
288

289
            // add table entries
290
            for(const Timer& entry : m_ops_entries) {
×
291
               result_ss << std::setw(name_padding) << std::left << entry.get_name() << std::setw(op_name_padding)
×
292
                         << std::left << entry.doing() << std::setw(op_padding) << std::right
×
293
                         << entry.seconds_per_event() << std::setw(op_padding) << std::right
×
294
                         << entry.events_per_second() << "\n";
×
295
            }
296
         }
297

298
         return result_ss.str();
2✔
299
      }
1✔
300

301
   private:
302
      std::map<std::pair<std::string, std::string>, std::vector<Timer>> m_bps_entries;
303
      std::vector<Timer> m_ops_entries;
304
};
305

306
std::vector<size_t> unique_buffer_sizes(const std::string& cmdline_arg) {
33✔
307
   const size_t MAX_BUF_SIZE = 64 * 1024 * 1024;
33✔
308

309
   std::set<size_t> buf;
33✔
310
   for(const std::string& size_str : Command::split_on(cmdline_arg, ',')) {
64✔
311
      size_t x = 0;
34✔
312
      try {
34✔
313
         size_t converted = 0;
34✔
314
         x = static_cast<size_t>(std::stoul(size_str, &converted, 0));
34✔
315

316
         if(converted != size_str.size()) {
33✔
317
            throw CLI_Usage_Error("Invalid integer");
×
318
         }
319
      } catch(std::exception&) {
1✔
320
         throw CLI_Usage_Error("Invalid integer value '" + size_str + "' for option buf-size");
2✔
321
      }
1✔
322

323
      if(x == 0) {
33✔
324
         throw CLI_Usage_Error("Cannot have a zero-sized buffer");
2✔
325
      }
326

327
      if(x > MAX_BUF_SIZE) {
32✔
328
         throw CLI_Usage_Error("Specified buffer size is too large");
2✔
329
      }
330

331
      buf.insert(x);
31✔
332
   }
33✔
333

334
   return std::vector<size_t>(buf.begin(), buf.end());
33✔
335
}
30✔
336

337
}  // namespace
338

339
class Speed final : public Command {
×
340
   public:
341
      Speed() :
34✔
342
            Command(
343
               "speed --msec=500 --format=default --ecc-groups= --provider= --buf-size=1024 --clear-cpuid= --cpu-clock-speed=0 --cpu-clock-ratio=1.0 *algos") {
68✔
344
      }
34✔
345

346
      static std::vector<std::string> default_benchmark_list() {
×
347
         /*
348
         This is not intended to be exhaustive: it just hits the high
349
         points of the most interesting or widely used algorithms.
350
         */
351
         // clang-format off
352
         return {
×
353
            /* Block ciphers */
354
            "AES-128",
355
            "AES-192",
356
            "AES-256",
357
            "ARIA-128",
358
            "ARIA-192",
359
            "ARIA-256",
360
            "Blowfish",
361
            "CAST-128",
362
            "Camellia-128",
363
            "Camellia-192",
364
            "Camellia-256",
365
            "DES",
366
            "TripleDES",
367
            "GOST-28147-89",
368
            "IDEA",
369
            "Noekeon",
370
            "SHACAL2",
371
            "SM4",
372
            "Serpent",
373
            "Threefish-512",
374
            "Twofish",
375

376
            /* Cipher modes */
377
            "AES-128/CBC",
378
            "AES-128/CTR-BE",
379
            "AES-128/EAX",
380
            "AES-128/OCB",
381
            "AES-128/GCM",
382
            "AES-128/XTS",
383
            "AES-128/SIV",
384

385
            "Serpent/CBC",
386
            "Serpent/CTR-BE",
387
            "Serpent/EAX",
388
            "Serpent/OCB",
389
            "Serpent/GCM",
390
            "Serpent/XTS",
391
            "Serpent/SIV",
392

393
            "ChaCha20Poly1305",
394

395
            /* Stream ciphers */
396
            "RC4",
397
            "Salsa20",
398
            "ChaCha20",
399

400
            /* Hashes */
401
            "SHA-1",
402
            "SHA-256",
403
            "SHA-512",
404
            "SHA-3(256)",
405
            "SHA-3(512)",
406
            "RIPEMD-160",
407
            "Skein-512",
408
            "Blake2b",
409
            "Whirlpool",
410

411
            /* XOFs */
412
            "SHAKE-128",
413
            "SHAKE-256",
414

415
            /* MACs */
416
            "CMAC(AES-128)",
417
            "HMAC(SHA-256)",
418

419
            /* pubkey */
420
            "RSA",
421
            "DH",
422
            "ECDH",
423
            "ECDSA",
424
            "Ed25519",
425
            "Ed448",
426
            "X25519",
427
            "X448",
428
            "McEliece",
429
            "Kyber",
430
            "SPHINCS+",
431
            "FrodoKEM",
432
            "HSS-LMS",
433
         };
×
434
         // clang-format on
435
      }
436

437
      std::string group() const override { return "misc"; }
1✔
438

439
      std::string description() const override { return "Measures the speed of algorithms"; }
1✔
440

441
      void go() override {
33✔
442
         std::chrono::milliseconds msec(get_arg_sz("msec"));
33✔
443
         const std::string provider = get_arg("provider");
33✔
444
         std::vector<std::string> ecc_groups = Command::split_on(get_arg("ecc-groups"), ',');
69✔
445
         const std::string format = get_arg("format");
33✔
446
         const std::string clock_ratio = get_arg("cpu-clock-ratio");
36✔
447
         m_clock_speed = get_arg_sz("cpu-clock-speed");
33✔
448

449
         m_clock_cycle_ratio = std::strtod(clock_ratio.c_str(), nullptr);
33✔
450

451
         /*
452
         * This argument is intended to be the ratio between the cycle counter
453
         * and the actual machine cycles. It is extremely unlikely that there is
454
         * any machine where the cycle counter increments faster than the actual
455
         * clock.
456
         */
457
         if(m_clock_cycle_ratio < 0.0 || m_clock_cycle_ratio > 1.0) {
33✔
458
            throw CLI_Usage_Error("Unlikely CPU clock ratio of " + clock_ratio);
×
459
         }
460

461
         m_clock_cycle_ratio = 1.0 / m_clock_cycle_ratio;
33✔
462

463
         if(m_clock_speed != 0 && Botan::OS::get_cpu_cycle_counter() != 0) {
33✔
464
            error_output() << "The --cpu-clock-speed option is only intended to be used on "
×
465
                              "platforms without access to a cycle counter.\n"
466
                              "Expected incorrect results\n\n";
×
467
         }
468

469
         if(format == "table") {
33✔
470
            m_summary = std::make_unique<Summary>();
1✔
471
         } else if(format == "json") {
32✔
472
            m_json = std::make_unique<JSON_Output>();
1✔
473
         } else if(format != "default") {
31✔
474
            throw CLI_Usage_Error("Unknown --format type '" + format + "'");
×
475
         }
476

477
#if defined(BOTAN_HAS_ECC_GROUP)
478
         if(ecc_groups.empty()) {
33✔
479
            ecc_groups = {"secp256r1", "secp384r1", "secp521r1", "brainpool256r1", "brainpool384r1", "brainpool512r1"};
264✔
480
         } else if(ecc_groups.size() == 1 && ecc_groups[0] == "all") {
×
481
            auto all = Botan::EC_Group::known_named_groups();
×
482
            ecc_groups.assign(all.begin(), all.end());
×
483
         }
×
484
#endif
485

486
         std::vector<std::string> algos = get_arg_list("algos");
36✔
487

488
         const std::vector<size_t> buf_sizes = unique_buffer_sizes(get_arg("buf-size"));
69✔
489

490
         for(const std::string& cpuid_to_clear : Command::split_on(get_arg("clear-cpuid"), ',')) {
31✔
491
            auto bits = Botan::CPUID::bit_from_string(cpuid_to_clear);
1✔
492
            if(bits.empty()) {
1✔
493
               error_output() << "Warning don't know CPUID flag '" << cpuid_to_clear << "'\n";
1✔
494
            }
495

496
            for(auto bit : bits) {
1✔
497
               Botan::CPUID::clear_cpuid_bit(bit);
×
498
            }
499
         }
31✔
500

501
         if(verbose() || m_summary) {
30✔
502
            output() << Botan::version_string() << "\n"
2✔
503
                     << "CPUID: " << Botan::CPUID::to_string() << "\n\n";
3✔
504
         }
505

506
         const bool using_defaults = (algos.empty());
30✔
507
         if(using_defaults) {
30✔
508
            algos = default_benchmark_list();
×
509
         }
510

511
         for(const auto& algo : algos) {
82✔
512
            using namespace std::placeholders;
52✔
513

514
            if(false) {
52✔
515
               // Since everything might be disabled, need a block to else if from
516
            }
517
#if defined(BOTAN_HAS_HASH)
518
            else if(!Botan::HashFunction::providers(algo).empty()) {
52✔
519
               bench_providers_of<Botan::HashFunction>(
1✔
520
                  algo, provider, msec, buf_sizes, std::bind(&Speed::bench_hash, this, _1, _2, _3, _4));
2✔
521
            }
522
#endif
523
#if defined(BOTAN_HAS_XOF)
524
            else if(!Botan::XOF::providers(algo).empty()) {
51✔
525
               bench_providers_of<Botan::XOF>(
×
526
                  algo, provider, msec, buf_sizes, std::bind(&Speed::bench_xof, this, _1, _2, _3, _4));
×
527
            }
528
#endif
529
#if defined(BOTAN_HAS_BLOCK_CIPHER)
530
            else if(!Botan::BlockCipher::providers(algo).empty()) {
51✔
531
               bench_providers_of<Botan::BlockCipher>(
4✔
532
                  algo, provider, msec, buf_sizes, std::bind(&Speed::bench_block_cipher, this, _1, _2, _3, _4));
8✔
533
            }
534
#endif
535
#if defined(BOTAN_HAS_STREAM_CIPHER)
536
            else if(!Botan::StreamCipher::providers(algo).empty()) {
47✔
537
               bench_providers_of<Botan::StreamCipher>(
1✔
538
                  algo, provider, msec, buf_sizes, std::bind(&Speed::bench_stream_cipher, this, _1, _2, _3, _4));
2✔
539
            }
540
#endif
541
#if defined(BOTAN_HAS_CIPHER_MODES)
542
            else if(auto enc = Botan::Cipher_Mode::create(algo, Botan::Cipher_Dir::Encryption, provider)) {
46✔
543
               auto dec = Botan::Cipher_Mode::create_or_throw(algo, Botan::Cipher_Dir::Decryption, provider);
1✔
544
               bench_cipher_mode(*enc, *dec, msec, buf_sizes);
1✔
545
            }
1✔
546
#endif
547
#if defined(BOTAN_HAS_MAC)
548
            else if(!Botan::MessageAuthenticationCode::providers(algo).empty()) {
45✔
549
               bench_providers_of<Botan::MessageAuthenticationCode>(
1✔
550
                  algo, provider, msec, buf_sizes, std::bind(&Speed::bench_mac, this, _1, _2, _3, _4));
2✔
551
            }
552
#endif
553
#if defined(BOTAN_HAS_RSA)
554
            else if(algo == "RSA") {
44✔
555
               bench_rsa(provider, msec);
1✔
556
            } else if(algo == "RSA_keygen") {
43✔
557
               bench_rsa_keygen(provider, msec);
1✔
558
            }
559
#endif
560

561
#if defined(BOTAN_HAS_PCURVES)
562
            else if(algo == "ECDSA-pcurves") {
42✔
563
               bench_pcurve_ecdsa(ecc_groups, msec);
×
564
            } else if(algo == "ECDH-pcurves") {
42✔
565
               bench_pcurve_ecdh(ecc_groups, msec);
×
566
            } else if(algo == "pcurves") {
42✔
567
               bench_pcurves(ecc_groups, msec);
×
568
            }
569
#endif
570

571
#if defined(BOTAN_HAS_ECDSA)
572
            else if(algo == "ECDSA") {
42✔
573
               bench_ecdsa(ecc_groups, provider, msec);
1✔
574
            } else if(algo == "ecdsa_recovery") {
41✔
575
               bench_ecdsa_recovery(ecc_groups, provider, msec);
1✔
576
            }
577
#endif
578
#if defined(BOTAN_HAS_SM2)
579
            else if(algo == "SM2") {
40✔
580
               bench_sm2(ecc_groups, provider, msec);
1✔
581
            }
582
#endif
583
#if defined(BOTAN_HAS_ECKCDSA)
584
            else if(algo == "ECKCDSA") {
39✔
585
               bench_eckcdsa(ecc_groups, provider, msec);
1✔
586
            }
587
#endif
588
#if defined(BOTAN_HAS_GOST_34_10_2001)
589
            else if(algo == "GOST-34.10") {
38✔
590
               bench_gost_3410(provider, msec);
1✔
591
            }
592
#endif
593
#if defined(BOTAN_HAS_ECGDSA)
594
            else if(algo == "ECGDSA") {
37✔
595
               bench_ecgdsa(ecc_groups, provider, msec);
1✔
596
            }
597
#endif
598
#if defined(BOTAN_HAS_ED25519)
599
            else if(algo == "Ed25519") {
36✔
600
               bench_ed25519(provider, msec);
1✔
601
            }
602
#endif
603
#if defined(BOTAN_HAS_ED448)
604
            else if(algo == "Ed448") {
35✔
605
               bench_ed448(provider, msec);
1✔
606
            }
607
#endif
608
#if defined(BOTAN_HAS_DIFFIE_HELLMAN)
609
            else if(algo == "DH") {
34✔
610
               bench_dh(provider, msec);
1✔
611
            }
612
#endif
613
#if defined(BOTAN_HAS_DSA)
614
            else if(algo == "DSA") {
33✔
615
               bench_dsa(provider, msec);
1✔
616
            }
617
#endif
618
#if defined(BOTAN_HAS_ELGAMAL)
619
            else if(algo == "ElGamal") {
32✔
620
               bench_elgamal(provider, msec);
1✔
621
            }
622
#endif
623
#if defined(BOTAN_HAS_ECDH)
624
            else if(algo == "ECDH") {
31✔
625
               bench_ecdh(ecc_groups, provider, msec);
1✔
626
            }
627
#endif
628
#if defined(BOTAN_HAS_X25519)
629
            else if(algo == "X25519") {
30✔
630
               bench_x25519(provider, msec);
1✔
631
            }
632
#endif
633
#if defined(BOTAN_HAS_X448)
634
            else if(algo == "X448") {
29✔
635
               bench_x448(provider, msec);
1✔
636
            }
637
#endif
638
#if defined(BOTAN_HAS_MCELIECE)
639
            else if(algo == "McEliece") {
28✔
640
               bench_mceliece(provider, msec);
1✔
641
            }
642
#endif
643
#if defined(BOTAN_HAS_KYBER) || defined(BOTAN_HAS_KYBER_90S)
644
            else if(algo == "Kyber") {
27✔
645
               bench_kyber(provider, msec);
1✔
646
            }
647
#endif
648
#if defined(BOTAN_HAS_DILITHIUM) || defined(BOTAN_HAS_DILITHIUM_AES)
649
            else if(algo == "Dilithium") {
26✔
650
               bench_dilithium(provider, msec);
1✔
651
            }
652
#endif
653
#if defined(BOTAN_HAS_XMSS_RFC8391)
654
            else if(algo == "XMSS") {
25✔
655
               bench_xmss(provider, msec);
1✔
656
            }
657
#endif
658
#if defined(BOTAN_HAS_HSS_LMS)
659
            else if(algo == "HSS-LMS") {
24✔
660
               bench_hss_lms(provider, msec);
×
661
            }
662
#endif
663
#if defined(BOTAN_HAS_SPHINCS_PLUS_WITH_SHA2) || defined(BOTAN_HAS_SPHINCS_PLUS_WITH_SHAKE)
664
            else if(algo == "SPHINCS+") {
24✔
665
               bench_sphincs_plus(provider, msec);
1✔
666
            }
667
#endif
668
#if defined(BOTAN_HAS_FRODOKEM)
669
            else if(algo == "FrodoKEM") {
23✔
670
               bench_frodokem(provider, msec);
×
671
            }
672
#endif
673
#if defined(BOTAN_HAS_SCRYPT)
674
            else if(algo == "scrypt") {
23✔
675
               bench_scrypt(provider, msec);
1✔
676
            }
677
#endif
678
#if defined(BOTAN_HAS_ARGON2)
679
            else if(algo == "argon2") {
22✔
680
               bench_argon2(provider, msec);
1✔
681
            }
682
#endif
683
#if defined(BOTAN_HAS_BCRYPT)
684
            else if(algo == "bcrypt") {
21✔
685
               bench_bcrypt();
1✔
686
            }
687
#endif
688
#if defined(BOTAN_HAS_PASSHASH9)
689
            else if(algo == "passhash9") {
20✔
690
               bench_passhash9();
1✔
691
            }
692
#endif
693
#if defined(BOTAN_HAS_ZFEC)
694
            else if(algo == "zfec") {
19✔
695
               bench_zfec(msec);
1✔
696
            }
697
#endif
698
#if defined(BOTAN_HAS_POLY_DBL)
699
            else if(algo == "poly_dbl") {
18✔
700
               bench_poly_dbl(msec);
1✔
701
            }
702
#endif
703

704
#if defined(BOTAN_HAS_DL_GROUP)
705
            else if(algo == "modexp") {
17✔
706
               bench_modexp(msec);
1✔
707
            }
708
#endif
709

710
#if defined(BOTAN_HAS_BIGINT)
711
            else if(algo == "mp_mul") {
16✔
712
               bench_mp_mul(msec);
1✔
713
            } else if(algo == "mp_div") {
15✔
714
               bench_mp_div(msec);
1✔
715
            } else if(algo == "mp_div10") {
14✔
716
               bench_mp_div10(msec);
1✔
717
            }
718
#endif
719

720
#if defined(BOTAN_HAS_NUMBERTHEORY)
721
            else if(algo == "primality_test") {
13✔
722
               bench_primality_tests(msec);
1✔
723
            } else if(algo == "random_prime") {
12✔
724
               bench_random_prime(msec);
1✔
725
            } else if(algo == "inverse_mod") {
11✔
726
               bench_inverse_mod(msec);
1✔
727
            } else if(algo == "bn_redc") {
10✔
728
               bench_bn_redc(msec);
1✔
729
            } else if(algo == "nistp_redc") {
9✔
730
               bench_nistp_redc(msec);
1✔
731
            }
732
#endif
733

734
#if defined(BOTAN_HAS_FPE_FE1)
735
            else if(algo == "fpe_fe1") {
8✔
736
               bench_fpe_fe1(msec);
1✔
737
            }
738
#endif
739

740
#if defined(BOTAN_HAS_RFC3394_KEYWRAP)
741
            else if(algo == "rfc3394") {
7✔
742
               bench_rfc3394(msec);
1✔
743
            }
744
#endif
745

746
#if defined(BOTAN_HAS_BASE64_CODEC)
747
            else if(algo == "base64") {
6✔
748
               bench_base64(msec, buf_sizes);
×
749
            }
750
#endif
751
#if defined(BOTAN_HAS_HEX_CODEC)
752
            else if(algo == "hex") {
6✔
753
               bench_hex(msec, buf_sizes);
×
754
            }
755
#endif
756

757
#if defined(BOTAN_HAS_ECC_GROUP)
758
            else if(algo == "ecc_mult") {
6✔
759
               bench_ecc_mult(ecc_groups, msec);
1✔
760
            } else if(algo == "ecc_init") {
5✔
761
               bench_ecc_init(ecc_groups, msec);
1✔
762
            } else if(algo == "os2ecp") {
4✔
763
               bench_os2ecp(ecc_groups, msec);
1✔
764
            }
765
#endif
766
#if defined(BOTAN_HAS_EC_HASH_TO_CURVE)
767
            else if(algo == "ec_h2c") {
3✔
768
               bench_ec_h2c(msec);
1✔
769
            }
770
#endif
771
            else if(algo == "RNG") {
2✔
772
#if defined(BOTAN_HAS_AUTO_SEEDING_RNG)
773
               Botan::AutoSeeded_RNG auto_rng;
1✔
774
               bench_rng(auto_rng, "AutoSeeded_RNG (with reseed)", msec, buf_sizes);
1✔
775
#endif
776

777
#if defined(BOTAN_HAS_SYSTEM_RNG)
778
               bench_rng(Botan::system_rng(), "System_RNG", msec, buf_sizes);
1✔
779
#endif
780

781
#if defined(BOTAN_HAS_PROCESSOR_RNG)
782
               if(Botan::Processor_RNG::available()) {
1✔
783
                  Botan::Processor_RNG hwrng;
1✔
784
                  bench_rng(hwrng, "Processor_RNG", msec, buf_sizes);
2✔
785
               }
1✔
786
#endif
787

788
#if defined(BOTAN_HAS_HMAC_DRBG)
789
               for(std::string hash : {"SHA-256", "SHA-384", "SHA-512"}) {
4✔
790
                  Botan::HMAC_DRBG hmac_drbg(hash);
3✔
791
                  bench_rng(hmac_drbg, hmac_drbg.name(), msec, buf_sizes);
3✔
792
               }
3✔
793
#endif
794

795
#if defined(BOTAN_HAS_CHACHA_RNG)
796
               // Provide a dummy seed
797
               Botan::ChaCha_RNG chacha_rng(Botan::secure_vector<uint8_t>(32));
1✔
798
               bench_rng(chacha_rng, "ChaCha_RNG", msec, buf_sizes);
1✔
799
#endif
800

801
            } else if(algo == "entropy") {
2✔
802
               bench_entropy_sources(msec);
1✔
803
            } else {
804
               if(verbose() || !using_defaults) {
×
805
                  error_output() << "Unknown algorithm '" << algo << "'\n";
×
806
               }
807
            }
46✔
808
         }
809

810
         if(m_json) {
30✔
811
            output() << m_json->print();
2✔
812
         }
813
         if(m_summary) {
30✔
814
            output() << m_summary->print() << "\n";
3✔
815
         }
816

817
         if(verbose() && m_clock_speed == 0 && m_cycles_consumed > 0 && m_ns_taken > 0) {
30✔
818
            const double seconds = static_cast<double>(m_ns_taken) / 1000000000;
×
819
            const double Hz = static_cast<double>(m_cycles_consumed) / seconds;
×
820
            const double MHz = Hz / 1000000;
×
821
            output() << "\nEstimated clock speed " << MHz << " MHz\n";
×
822
         }
823
      }
105✔
824

825
   private:
826
      size_t m_clock_speed = 0;
827
      double m_clock_cycle_ratio = 0.0;
828
      uint64_t m_cycles_consumed = 0;
829
      uint64_t m_ns_taken = 0;
830
      std::unique_ptr<Summary> m_summary;
831
      std::unique_ptr<JSON_Output> m_json;
832

833
      void record_result(const std::unique_ptr<Timer>& t) {
447✔
834
         m_ns_taken += t->value();
447✔
835
         m_cycles_consumed += t->cycles_consumed();
447✔
836
         if(m_json) {
447✔
837
            m_json->add(*t);
2✔
838
         } else {
839
            output() << t->to_string() << std::flush;
890✔
840
            if(m_summary) {
445✔
841
               m_summary->add(*t);
2✔
842
            }
843
         }
844
      }
447✔
845

846
      template <typename T>
847
      using bench_fn = std::function<void(T&, std::string, std::chrono::milliseconds, const std::vector<size_t>&)>;
848

849
      template <typename T>
850
      void bench_providers_of(const std::string& algo,
7✔
851
                              const std::string& provider, /* user request, if any */
852
                              const std::chrono::milliseconds runtime,
853
                              const std::vector<size_t>& buf_sizes,
854
                              bench_fn<T> bench_one) {
855
         for(const auto& prov : T::providers(algo)) {
14✔
856
            if(provider.empty() || provider == prov) {
7✔
857
               auto p = T::create(algo, prov);
7✔
858

859
               if(p) {
7✔
860
                  bench_one(*p, prov, runtime, buf_sizes);
14✔
861
               }
862
            }
7✔
863
         }
864
      }
7✔
865

866
      std::unique_ptr<Timer> make_timer(const std::string& name,
451✔
867
                                        uint64_t event_mult = 1,
868
                                        const std::string& what = "",
869
                                        const std::string& provider = "",
870
                                        size_t buf_size = 0) {
871
         return std::make_unique<Timer>(name, provider, what, event_mult, buf_size, m_clock_cycle_ratio, m_clock_speed);
148✔
872
      }
873

874
      std::unique_ptr<Timer> make_timer(const std::string& algo, const std::string& provider, const std::string& what) {
216✔
875
         return make_timer(algo, 1, what, provider, 0);
124✔
876
      }
877

878
#if defined(BOTAN_HAS_BLOCK_CIPHER)
879
      void bench_block_cipher(Botan::BlockCipher& cipher,
4✔
880
                              const std::string& provider,
881
                              std::chrono::milliseconds runtime,
882
                              const std::vector<size_t>& buf_sizes) {
883
         auto ks_timer = make_timer(cipher.name(), provider, "key schedule");
8✔
884

885
         const Botan::SymmetricKey key(rng(), cipher.maximum_keylength());
4✔
886
         ks_timer->run([&]() { cipher.set_key(key); });
8✔
887

888
         const size_t bs = cipher.block_size();
4✔
889
         std::set<size_t> buf_sizes_in_blocks;
4✔
890
         for(size_t buf_size : buf_sizes) {
9✔
891
            if(buf_size % bs == 0) {
5✔
892
               buf_sizes_in_blocks.insert(buf_size);
5✔
893
            } else {
894
               buf_sizes_in_blocks.insert(buf_size + bs - (buf_size % bs));
×
895
            }
896
         }
897

898
         for(size_t buf_size : buf_sizes_in_blocks) {
9✔
899
            std::vector<uint8_t> buffer(buf_size);
5✔
900
            const size_t mult = std::max<size_t>(1, 65536 / buf_size);
5✔
901
            const size_t blocks = buf_size / bs;
5✔
902

903
            auto encrypt_timer = make_timer(cipher.name(), mult * buffer.size(), "encrypt", provider, buf_size);
10✔
904
            auto decrypt_timer = make_timer(cipher.name(), mult * buffer.size(), "decrypt", provider, buf_size);
10✔
905

906
            encrypt_timer->run_until_elapsed(runtime, [&]() {
5✔
907
               for(size_t i = 0; i != mult; ++i) {
18,132✔
908
                  cipher.encrypt_n(&buffer[0], &buffer[0], blocks);
18,048✔
909
               }
910
            });
84✔
911
            record_result(encrypt_timer);
5✔
912

913
            decrypt_timer->run_until_elapsed(runtime, [&]() {
5✔
914
               for(size_t i = 0; i != mult; ++i) {
17,107✔
915
                  cipher.decrypt_n(&buffer[0], &buffer[0], blocks);
17,024✔
916
               }
917
            });
83✔
918
            record_result(decrypt_timer);
5✔
919
         }
5✔
920
      }
8✔
921
#endif
922

923
#if defined(BOTAN_HAS_STREAM_CIPHER)
924
      void bench_stream_cipher(Botan::StreamCipher& cipher,
1✔
925
                               const std::string& provider,
926
                               const std::chrono::milliseconds runtime,
927
                               const std::vector<size_t>& buf_sizes) {
928
         for(auto buf_size : buf_sizes) {
2✔
929
            const Botan::SymmetricKey key(rng(), cipher.maximum_keylength());
1✔
930
            cipher.set_key(key);
1✔
931

932
            if(cipher.valid_iv_length(12)) {
1✔
933
               const Botan::InitializationVector iv(rng(), 12);
1✔
934
               cipher.set_iv(iv.begin(), iv.size());
1✔
935
            }
1✔
936

937
            Botan::secure_vector<uint8_t> buffer = rng().random_vec(buf_size);
1✔
938

939
            const size_t mult = std::max<size_t>(1, 65536 / buf_size);
1✔
940

941
            auto encrypt_timer = make_timer(cipher.name(), mult * buffer.size(), "encrypt", provider, buf_size);
2✔
942

943
            encrypt_timer->run_until_elapsed(runtime, [&]() {
1✔
944
               for(size_t i = 0; i != mult; ++i) {
975✔
945
                  cipher.encipher(buffer);
960✔
946
               }
947
            });
15✔
948

949
            record_result(encrypt_timer);
1✔
950

951
            if(verbose()) {
1✔
952
               auto ks_timer = make_timer(cipher.name(), buffer.size(), "write_keystream", provider, buf_size);
×
953

954
               while(ks_timer->under(runtime)) {
×
955
                  ks_timer->run([&]() { cipher.write_keystream(buffer.data(), buffer.size()); });
×
956
               }
957
               record_result(ks_timer);
×
958
            }
×
959
         }
3✔
960
      }
1✔
961
#endif
962

963
#if defined(BOTAN_HAS_HASH)
964
      void bench_hash(Botan::HashFunction& hash,
1✔
965
                      const std::string& provider,
966
                      const std::chrono::milliseconds runtime,
967
                      const std::vector<size_t>& buf_sizes) {
968
         std::vector<uint8_t> output(hash.output_length());
1✔
969

970
         for(auto buf_size : buf_sizes) {
2✔
971
            Botan::secure_vector<uint8_t> buffer = rng().random_vec(buf_size);
1✔
972

973
            const size_t mult = std::max<size_t>(1, 65536 / buf_size);
1✔
974

975
            auto timer = make_timer(hash.name(), mult * buffer.size(), "hash", provider, buf_size);
2✔
976
            timer->run_until_elapsed(runtime, [&]() {
1✔
977
               for(size_t i = 0; i != mult; ++i) {
260✔
978
                  hash.update(buffer);
256✔
979
                  hash.final(output.data());
512✔
980
               }
981
            });
4✔
982
            record_result(timer);
1✔
983
         }
2✔
984
      }
1✔
985
#endif
986

987
#if defined(BOTAN_HAS_XOF)
988
      void bench_xof(Botan::XOF& xof,
×
989
                     const std::string& provider,
990
                     const std::chrono::milliseconds runtime,
991
                     const std::vector<size_t>& buf_sizes) {
992
         for(auto buf_size : buf_sizes) {
×
993
            Botan::secure_vector<uint8_t> in = rng().random_vec(buf_size);
×
994
            Botan::secure_vector<uint8_t> out(buf_size);
×
995

996
            auto in_timer = make_timer(xof.name(), in.size(), "input", provider, buf_size);
×
997
            in_timer->run_until_elapsed(runtime / 2, [&]() { xof.update(in); });
×
998

999
            auto out_timer = make_timer(xof.name(), out.size(), "output", provider, buf_size);
×
1000
            out_timer->run_until_elapsed(runtime / 2, [&] { xof.output(out); });
×
1001

1002
            record_result(in_timer);
×
1003
            record_result(out_timer);
×
1004
         }
×
1005
      }
×
1006
#endif
1007

1008
#if defined(BOTAN_HAS_MAC)
1009
      void bench_mac(Botan::MessageAuthenticationCode& mac,
1✔
1010
                     const std::string& provider,
1011
                     const std::chrono::milliseconds runtime,
1012
                     const std::vector<size_t>& buf_sizes) {
1013
         std::vector<uint8_t> output(mac.output_length());
1✔
1014

1015
         for(auto buf_size : buf_sizes) {
2✔
1016
            Botan::secure_vector<uint8_t> buffer = rng().random_vec(buf_size);
1✔
1017
            const size_t mult = std::max<size_t>(1, 65536 / buf_size);
1✔
1018

1019
            const Botan::SymmetricKey key(rng(), mac.maximum_keylength());
1✔
1020
            mac.set_key(key);
1✔
1021
            mac.start(nullptr, 0);
1✔
1022

1023
            auto timer = make_timer(mac.name(), mult * buffer.size(), "mac", provider, buf_size);
2✔
1024
            timer->run_until_elapsed(runtime, [&]() {
1✔
1025
               for(size_t i = 0; i != mult; ++i) {
195✔
1026
                  mac.update(buffer);
192✔
1027
                  mac.final(output.data());
384✔
1028
               }
1029
            });
3✔
1030

1031
            record_result(timer);
1✔
1032
         }
3✔
1033
      }
1✔
1034
#endif
1035

1036
#if defined(BOTAN_HAS_CIPHER_MODES)
1037
      void bench_cipher_mode(Botan::Cipher_Mode& enc,
1✔
1038
                             Botan::Cipher_Mode& dec,
1039
                             const std::chrono::milliseconds runtime,
1040
                             const std::vector<size_t>& buf_sizes) {
1041
         auto ks_timer = make_timer(enc.name(), enc.provider(), "key schedule");
2✔
1042

1043
         const Botan::SymmetricKey key(rng(), enc.key_spec().maximum_keylength());
1✔
1044

1045
         ks_timer->run([&]() { enc.set_key(key); });
2✔
1046
         ks_timer->run([&]() { dec.set_key(key); });
2✔
1047

1048
         record_result(ks_timer);
1✔
1049

1050
         for(auto buf_size : buf_sizes) {
2✔
1051
            Botan::secure_vector<uint8_t> buffer = rng().random_vec(buf_size);
1✔
1052
            const size_t mult = std::max<size_t>(1, 65536 / buf_size);
1✔
1053

1054
            auto encrypt_timer = make_timer(enc.name(), mult * buffer.size(), "encrypt", enc.provider(), buf_size);
2✔
1055
            auto decrypt_timer = make_timer(dec.name(), mult * buffer.size(), "decrypt", dec.provider(), buf_size);
2✔
1056

1057
            Botan::secure_vector<uint8_t> iv = rng().random_vec(enc.default_nonce_length());
1✔
1058

1059
            if(buf_size >= enc.minimum_final_size()) {
1✔
1060
               encrypt_timer->run_until_elapsed(runtime, [&]() {
2✔
1061
                  for(size_t i = 0; i != mult; ++i) {
260✔
1062
                     enc.start(iv);
256✔
1063
                     enc.finish(buffer);
256✔
1064
                     buffer.resize(buf_size);  // remove any tag or padding
256✔
1065
                  }
1066
               });
4✔
1067

1068
               while(decrypt_timer->under(runtime)) {
5✔
1069
                  if(!iv.empty()) {
4✔
1070
                     iv[iv.size() - 1] += 1;
4✔
1071
                  }
1072

1073
                  // Create a valid ciphertext/tag for decryption to run on
1074
                  buffer.resize(buf_size);
4✔
1075
                  enc.start(iv);
4✔
1076
                  enc.finish(buffer);
4✔
1077

1078
                  Botan::secure_vector<uint8_t> dbuffer;
4✔
1079

1080
                  decrypt_timer->run([&]() {
4✔
1081
                     for(size_t i = 0; i != mult; ++i) {
260✔
1082
                        dbuffer = buffer;
256✔
1083
                        dec.start(iv);
256✔
1084
                        dec.finish(dbuffer);
256✔
1085
                     }
1086
                  });
4✔
1087
               }
4✔
1088
            }
1089
            record_result(encrypt_timer);
1✔
1090
            record_result(decrypt_timer);
1✔
1091
         }
2✔
1092
      }
1✔
1093
#endif
1094

1095
      void bench_rng(Botan::RandomNumberGenerator& rng,
7✔
1096
                     const std::string& rng_name,
1097
                     const std::chrono::milliseconds runtime,
1098
                     const std::vector<size_t>& buf_sizes) {
1099
         for(auto buf_size : buf_sizes) {
14✔
1100
            Botan::secure_vector<uint8_t> buffer(buf_size);
7✔
1101
            const size_t mult = std::max<size_t>(1, 65536 / buf_size);
7✔
1102

1103
#if defined(BOTAN_HAS_SYSTEM_RNG)
1104
            rng.reseed_from_rng(Botan::system_rng(), 256);
7✔
1105
#endif
1106

1107
            auto timer = make_timer(rng_name, mult * buffer.size(), "generate", "", buf_size);
7✔
1108
            timer->run_until_elapsed(runtime, [&]() {
7✔
1109
               for(size_t i = 0; i != mult; ++i) {
1,885✔
1110
                  rng.randomize(buffer.data(), buffer.size());
1,856✔
1111
               }
1112
            });
29✔
1113

1114
            record_result(timer);
7✔
1115
         }
14✔
1116
      }
7✔
1117

1118
      void bench_entropy_sources(const std::chrono::milliseconds /*unused*/) {
1✔
1119
         Botan::Entropy_Sources& srcs = Botan::Entropy_Sources::global_sources();
1✔
1120

1121
         for(auto src : srcs.enabled_sources()) {
5✔
1122
            size_t entropy_bits = 0;
4✔
1123
            Botan_Tests::SeedCapturing_RNG rng;
4✔
1124

1125
            auto timer = make_timer(src, "", "bytes");
8✔
1126
            timer->run([&]() { entropy_bits = srcs.poll_just(rng, src); });
8✔
1127

1128
            size_t compressed_size = 0;
4✔
1129

1130
#if defined(BOTAN_HAS_ZLIB)
1131
            auto comp = Botan::Compression_Algorithm::create("zlib");
4✔
1132

1133
            if(comp) {
4✔
1134
               Botan::secure_vector<uint8_t> compressed;
4✔
1135
               compressed.assign(rng.seed_material().begin(), rng.seed_material().end());
4✔
1136
               comp->start(9);
4✔
1137
               comp->finish(compressed);
4✔
1138

1139
               compressed_size = compressed.size();
4✔
1140
            }
4✔
1141
#endif
1142

1143
            std::ostringstream msg;
4✔
1144

1145
            msg << "Entropy source " << src << " output " << rng.seed_material().size() << " bytes"
4✔
1146
                << " estimated entropy " << entropy_bits << " in " << timer->milliseconds() << " ms";
4✔
1147

1148
            if(compressed_size > 0) {
4✔
1149
               msg << " output compressed to " << compressed_size << " bytes";
4✔
1150
            }
1151

1152
            msg << " total samples " << rng.samples() << "\n";
4✔
1153

1154
            timer->set_custom_msg(msg.str());
8✔
1155

1156
            record_result(timer);
4✔
1157
         }
9✔
1158
      }
1✔
1159

1160
#if defined(BOTAN_HAS_ECC_GROUP)
1161
      void bench_ecc_init(const std::vector<std::string>& groups, const std::chrono::milliseconds runtime) {
1✔
1162
         for(std::string group_name : groups) {
7✔
1163
            auto timer = make_timer(group_name + " initialization");
12✔
1164

1165
            while(timer->under(runtime)) {
12✔
1166
               Botan::EC_Group::clear_registered_curve_data();
6✔
1167
               timer->run([&]() { Botan::EC_Group::from_name(group_name); });
12✔
1168
            }
1169

1170
            record_result(timer);
6✔
1171
         }
6✔
1172
      }
1✔
1173

1174
      void bench_ecc_mult(const std::vector<std::string>& groups, const std::chrono::milliseconds runtime) {
1✔
1175
         for(const std::string& group_name : groups) {
7✔
1176
            const auto group = Botan::EC_Group::from_name(group_name);
6✔
1177

1178
            auto bp_timer = make_timer(group_name + " base point");
12✔
1179
            auto vp_timer = make_timer(group_name + " variable point");
12✔
1180

1181
            std::vector<Botan::BigInt> ws;
6✔
1182

1183
            auto g = Botan::EC_AffinePoint::generator(group);
6✔
1184

1185
            while(bp_timer->under(runtime) && vp_timer->under(runtime)) {
14✔
1186
               const auto k = Botan::EC_Scalar::random(group, rng());
8✔
1187

1188
               const auto r1 = bp_timer->run([&]() { return Botan::EC_AffinePoint::g_mul(k, rng(), ws); });
16✔
1189

1190
               const auto r2 = vp_timer->run([&]() { return g.mul(k, rng(), ws); });
16✔
1191

1192
               BOTAN_ASSERT_EQUAL(
8✔
1193
                  r1.serialize_uncompressed(), r2.serialize_uncompressed(), "Same result for multiplication");
1194
            }
8✔
1195

1196
            record_result(bp_timer);
6✔
1197
            record_result(vp_timer);
6✔
1198
         }
6✔
1199
      }
1✔
1200

1201
      void bench_os2ecp(const std::vector<std::string>& groups, const std::chrono::milliseconds runtime) {
1✔
1202
         for(const std::string& group_name : groups) {
7✔
1203
            auto uncmp_timer = make_timer("OS2ECP uncompressed " + group_name);
12✔
1204
            auto cmp_timer = make_timer("OS2ECP compressed " + group_name);
12✔
1205

1206
            const auto ec_group = Botan::EC_Group::from_name(group_name);
6✔
1207

1208
            while(uncmp_timer->under(runtime) && cmp_timer->under(runtime)) {
127✔
1209
               const Botan::BigInt k(rng(), 256);
121✔
1210
               const Botan::EC_Point p = ec_group.get_base_point() * k;
121✔
1211
               const std::vector<uint8_t> os_cmp = p.encode(Botan::EC_Point_Format::Compressed);
121✔
1212
               const std::vector<uint8_t> os_uncmp = p.encode(Botan::EC_Point_Format::Uncompressed);
121✔
1213

1214
               uncmp_timer->run([&]() { ec_group.OS2ECP(os_uncmp); });
242✔
1215
               cmp_timer->run([&]() { ec_group.OS2ECP(os_cmp); });
242✔
1216
            }
242✔
1217

1218
            record_result(uncmp_timer);
6✔
1219
            record_result(cmp_timer);
6✔
1220
         }
6✔
1221
      }
1✔
1222

1223
#endif
1224

1225
#if defined(BOTAN_HAS_EC_HASH_TO_CURVE)
1226
      void bench_ec_h2c(const std::chrono::milliseconds runtime) {
1✔
1227
         for(std::string group_name : {"secp256r1", "secp384r1", "secp521r1"}) {
4✔
1228
            auto h2c_ro_timer = make_timer(group_name + "-RO", "", "hash to curve");
6✔
1229
            auto h2c_nu_timer = make_timer(group_name + "-NU", "", "hash to curve");
6✔
1230

1231
            const auto group = Botan::EC_Group::from_name(group_name);
3✔
1232

1233
            const std::string hash_fn = "SHA-256";
3✔
1234

1235
            while(h2c_ro_timer->under(runtime)) {
14✔
1236
               const auto input = rng().random_array<32>();
11✔
1237
               const auto domain_sep = rng().random_array<32>();
11✔
1238

1239
               h2c_ro_timer->run(
11✔
1240
                  [&]() { return Botan::EC_AffinePoint::hash_to_curve_ro(group, hash_fn, input, domain_sep); });
11✔
1241

1242
               h2c_nu_timer->run(
11✔
1243
                  [&]() { return Botan::EC_AffinePoint::hash_to_curve_nu(group, hash_fn, input, domain_sep); });
11✔
1244
            }
1245

1246
            record_result(h2c_ro_timer);
3✔
1247
            record_result(h2c_nu_timer);
3✔
1248
         }
3✔
1249
      }
1✔
1250
#endif
1251

1252
#if defined(BOTAN_HAS_PCURVES)
1253

1254
      void bench_pcurves(const std::vector<std::string>& groups, const std::chrono::milliseconds runtime) {
×
1255
         for(const auto& group_name : groups) {
×
1256
            if(auto curve = Botan::PCurve::PrimeOrderCurve::from_name(group_name)) {
×
1257
               auto base_timer = make_timer(group_name + " pcurve base mul");
×
1258
               auto var_timer = make_timer(group_name + " pcurve var mul");
×
1259
               auto mul2_setup_timer = make_timer(group_name + " pcurve mul2 setup");
×
1260
               auto mul2_timer = make_timer(group_name + " pcurve mul2");
×
1261

1262
               auto scalar_invert = make_timer(group_name + " pcurve scalar invert");
×
1263
               auto to_affine = make_timer(group_name + " pcurve proj->affine");
×
1264

1265
               auto g = curve->generator();
×
1266
               auto h = curve->mul(g, curve->random_scalar(rng()), rng()).to_affine();
×
1267
               auto gh_tab = curve->mul2_setup(g, h);
×
1268

1269
               while(base_timer->under(runtime)) {
×
1270
                  const auto scalar = curve->random_scalar(rng());
×
1271
                  base_timer->run([&]() { return curve->mul_by_g(scalar, rng()).to_affine(); });
×
1272
               }
×
1273

1274
               while(var_timer->under(runtime)) {
×
1275
                  const auto scalar = curve->random_scalar(rng());
×
1276
                  var_timer->run([&]() { return curve->mul(h, scalar, rng()).to_affine(); });
×
1277
               }
×
1278

1279
               while(mul2_setup_timer->under(runtime)) {
×
1280
                  mul2_setup_timer->run([&]() { return curve->mul2_setup(g, h); });
×
1281
               }
1282

1283
               while(mul2_timer->under(runtime)) {
×
1284
                  const auto scalar = curve->random_scalar(rng());
×
1285
                  const auto scalar2 = curve->random_scalar(rng());
×
1286
                  mul2_timer->run([&]() -> std::optional<Botan::PCurve::PrimeOrderCurve::AffinePoint> {
×
1287
                     if(auto pt = curve->mul2_vartime(*gh_tab, scalar, scalar2)) {
×
1288
                        return pt->to_affine();
×
1289
                     } else {
1290
                        return {};
×
1291
                     }
×
1292
                  });
1293
               }
×
1294

1295
               auto pt = curve->mul(g, curve->random_scalar(rng()), rng());
×
1296
               to_affine->run_until_elapsed(runtime, [&]() { pt.to_affine(); });
×
1297

1298
               while(scalar_invert->under(runtime)) {
×
1299
                  const auto scalar = curve->random_scalar(rng());
×
1300
                  scalar_invert->run([&]() { scalar.invert(); });
×
1301
               }
×
1302

1303
               record_result(base_timer);
×
1304
               record_result(var_timer);
×
1305
               record_result(mul2_setup_timer);
×
1306
               record_result(mul2_timer);
×
1307
               record_result(to_affine);
×
1308
               record_result(scalar_invert);
×
1309
            }
×
1310
         }
1311
      }
×
1312

1313
      void bench_pcurve_ecdsa(const std::vector<std::string>& groups, const std::chrono::milliseconds runtime) {
×
1314
         for(const auto& group_name : groups) {
×
1315
            auto curve = Botan::PCurve::PrimeOrderCurve::from_name(group_name);
×
1316
            if(!curve) {
×
1317
               continue;
×
1318
            }
1319

1320
            // Setup (not timed)
1321
            const auto g = curve->generator();
×
1322
            const auto x = curve->random_scalar(rng());
×
1323
            const auto y = curve->mul_by_g(x, rng()).to_affine();
×
1324
            const auto e = curve->random_scalar(rng());
×
1325

1326
            const auto gy_tab = curve->mul2_setup(g, y);
×
1327

1328
            auto b = curve->random_scalar(rng());
×
1329
            auto b_inv = b.invert();
×
1330

1331
            auto sign_timer = make_timer("ECDSA sign pcurves " + group_name);
×
1332
            auto verify_timer = make_timer("ECDSA verify pcurves " + group_name);
×
1333

1334
            while(sign_timer->under(runtime)) {
×
1335
               sign_timer->start();
×
1336

1337
               const auto signature = [&]() {
×
1338
                  const auto k = curve->random_scalar(rng());
×
1339
                  const auto r = curve->base_point_mul_x_mod_order(k, rng());
×
1340
                  const auto k_inv = (b * k).invert() * b;
×
1341
                  b = b.square();
×
1342
                  b_inv = b_inv.square();
×
1343
                  const auto be = b * e;
×
1344
                  const auto bx = b * x;
×
1345
                  const auto bxr_e = (bx * r) + be;
×
1346
                  const auto s = (k_inv * bxr_e) * b_inv;
×
1347

1348
                  return Botan::concat(r.serialize(), s.serialize());
×
1349
               }();
×
1350

1351
               sign_timer->stop();
×
1352

1353
               verify_timer->start();
×
1354

1355
               auto result = [&](std::span<const uint8_t> sig) {
×
1356
                  const size_t scalar_bytes = curve->scalar_bytes();
×
1357
                  if(sig.size() != 2 * scalar_bytes) {
×
1358
                     return false;
1359
                  }
1360

1361
                  const auto r = curve->deserialize_scalar(sig.first(scalar_bytes));
×
1362
                  const auto s = curve->deserialize_scalar(sig.last(scalar_bytes));
×
1363

1364
                  if(r && s) {
×
1365
                     if(r->is_zero() || s->is_zero()) {
×
1366
                        return false;
×
1367
                     }
1368

1369
                     auto w = s->invert();
×
1370

1371
                     auto u1 = e * w;
×
1372
                     auto u2 = *r * w;
×
1373

1374
                     return curve->mul2_vartime_x_mod_order_eq(*gy_tab, *r, u1, u2);
×
1375
                  }
×
1376

1377
                  return false;
1378
               }(signature);
×
1379

1380
               BOTAN_ASSERT(result, "ECDSA-pcurves signature ok");
×
1381

1382
               verify_timer->stop();
×
1383
            }
×
1384

1385
            record_result(sign_timer);
×
1386
            record_result(verify_timer);
×
1387
         }
×
1388
      }
×
1389

1390
      void bench_pcurve_ecdh(const std::vector<std::string>& groups, const std::chrono::milliseconds runtime) {
×
1391
         for(const auto& group_name : groups) {
×
1392
            auto curve = Botan::PCurve::PrimeOrderCurve::from_name(group_name);
×
1393
            if(!curve) {
×
1394
               continue;
×
1395
            }
1396

1397
            auto ka_timer = make_timer("ECDH agree pcurves " + group_name);
×
1398

1399
            auto agree = [&](const Botan::PCurve::PrimeOrderCurve::Scalar& sk, std::span<const uint8_t> pt_bytes) {
×
1400
               const auto pt = curve->deserialize_point(pt_bytes);
×
1401
               if(pt) {
×
1402
                  return curve->mul(*pt, sk, rng()).to_affine().serialize();
×
1403
               } else {
1404
                  return std::vector<uint8_t>();
×
1405
               }
1406
            };
×
1407

1408
            while(ka_timer->under(runtime)) {
×
1409
               const auto g = curve->generator();
×
1410
               const auto x1 = curve->random_scalar(rng());
×
1411
               const auto x2 = curve->random_scalar(rng());
×
1412

1413
               const auto y1 = curve->mul_by_g(x1, rng()).to_affine().serialize();
×
1414
               const auto y2 = curve->mul_by_g(x2, rng()).to_affine().serialize();
×
1415

1416
               ka_timer->start();
×
1417
               const auto ss1 = agree(x1, y2);
×
1418
               ka_timer->stop();
×
1419

1420
               ka_timer->start();
×
1421
               const auto ss2 = agree(x1, y2);
×
1422
               ka_timer->stop();
×
1423

1424
               BOTAN_ASSERT(ss1 == ss2, "Key agreement worked");
×
1425
            }
×
1426

1427
            record_result(ka_timer);
×
1428
         }
×
1429
      }
×
1430

1431
#endif
1432

1433
#if defined(BOTAN_HAS_FPE_FE1)
1434

1435
      void bench_fpe_fe1(const std::chrono::milliseconds runtime) {
1✔
1436
         const auto n = Botan::BigInt::from_u64(1000000000000000);
1✔
1437

1438
         auto enc_timer = make_timer("FPE_FE1 encrypt");
2✔
1439
         auto dec_timer = make_timer("FPE_FE1 decrypt");
2✔
1440

1441
         const Botan::SymmetricKey key(rng(), 32);
1✔
1442
         const std::vector<uint8_t> tweak(8);  // 8 zeros
1✔
1443

1444
         auto x = Botan::BigInt::one();
1✔
1445

1446
         Botan::FPE_FE1 fpe_fe1(n);
1✔
1447
         fpe_fe1.set_key(key);
1✔
1448

1449
         while(enc_timer->under(runtime)) {
6✔
1450
            enc_timer->start();
5✔
1451
            x = fpe_fe1.encrypt(x, tweak.data(), tweak.size());
5✔
1452
            enc_timer->stop();
5✔
1453
         }
1454

1455
         for(size_t i = 0; i != enc_timer->events(); ++i) {
6✔
1456
            dec_timer->start();
5✔
1457
            x = fpe_fe1.decrypt(x, tweak.data(), tweak.size());
5✔
1458
            dec_timer->stop();
5✔
1459
         }
1460

1461
         BOTAN_ASSERT(x == 1, "FPE works");
1✔
1462

1463
         record_result(enc_timer);
1✔
1464
         record_result(dec_timer);
1✔
1465
      }
4✔
1466
#endif
1467

1468
#if defined(BOTAN_HAS_RFC3394_KEYWRAP)
1469

1470
      void bench_rfc3394(const std::chrono::milliseconds runtime) {
1✔
1471
         auto wrap_timer = make_timer("RFC3394 AES-256 key wrap");
2✔
1472
         auto unwrap_timer = make_timer("RFC3394 AES-256 key unwrap");
2✔
1473

1474
         const Botan::SymmetricKey kek(rng(), 32);
1✔
1475
         Botan::secure_vector<uint8_t> key(64, 0);
1✔
1476

1477
         while(wrap_timer->under(runtime)) {
98✔
1478
            wrap_timer->start();
97✔
1479
            key = Botan::rfc3394_keywrap(key, kek);
194✔
1480
            wrap_timer->stop();
97✔
1481

1482
            unwrap_timer->start();
97✔
1483
            key = Botan::rfc3394_keyunwrap(key, kek);
194✔
1484
            unwrap_timer->stop();
97✔
1485

1486
            key[0] += 1;
97✔
1487
         }
1488

1489
         record_result(wrap_timer);
1✔
1490
         record_result(unwrap_timer);
1✔
1491
      }
2✔
1492
#endif
1493

1494
#if defined(BOTAN_HAS_BIGINT)
1495

1496
      void bench_mp_mul(const std::chrono::milliseconds runtime) {
1✔
1497
         std::chrono::milliseconds runtime_per_size = runtime;
1✔
1498
         for(size_t bits : {256, 384, 512, 768, 1024, 1536, 2048, 3072, 4096}) {
10✔
1499
            auto mul_timer = make_timer("BigInt mul " + std::to_string(bits));
18✔
1500
            auto sqr_timer = make_timer("BigInt sqr " + std::to_string(bits));
18✔
1501

1502
            const Botan::BigInt y(rng(), bits);
9✔
1503
            Botan::secure_vector<Botan::word> ws;
9✔
1504

1505
            while(mul_timer->under(runtime_per_size)) {
8,559✔
1506
               Botan::BigInt x(rng(), bits);
8,550✔
1507

1508
               sqr_timer->start();
8,550✔
1509
               x.square(ws);
8,550✔
1510
               sqr_timer->stop();
8,550✔
1511

1512
               x.mask_bits(bits);
8,550✔
1513

1514
               mul_timer->start();
8,550✔
1515
               x.mul(y, ws);
8,550✔
1516
               mul_timer->stop();
8,550✔
1517
            }
8,550✔
1518

1519
            record_result(mul_timer);
9✔
1520
            record_result(sqr_timer);
9✔
1521
         }
18✔
1522
      }
1✔
1523

1524
      void bench_mp_div(const std::chrono::milliseconds runtime) {
1✔
1525
         std::chrono::milliseconds runtime_per_size = runtime;
1✔
1526

1527
         for(size_t n_bits : {256, 384, 512, 768, 1024, 1536, 2048, 3072, 4096}) {
10✔
1528
            const size_t q_bits = n_bits / 2;
9✔
1529
            const std::string bit_descr = std::to_string(n_bits) + "/" + std::to_string(q_bits);
27✔
1530

1531
            auto div_timer = make_timer("BigInt div " + bit_descr);
18✔
1532
            auto ct_div_timer = make_timer("BigInt ct_div " + bit_descr);
18✔
1533

1534
            Botan::BigInt y;
9✔
1535
            Botan::BigInt x;
9✔
1536
            Botan::secure_vector<Botan::word> ws;
9✔
1537

1538
            Botan::BigInt q1, r1, q2, r2;
9✔
1539

1540
            while(ct_div_timer->under(runtime_per_size)) {
9✔
1541
               x.randomize(rng(), n_bits);
96✔
1542
               y.randomize(rng(), q_bits);
96✔
1543

1544
               div_timer->start();
96✔
1545
               Botan::vartime_divide(x, y, q1, r1);
96✔
1546
               div_timer->stop();
96✔
1547

1548
               ct_div_timer->start();
96✔
1549
               Botan::ct_divide(x, y, q2, r2);
96✔
1550
               ct_div_timer->stop();
96✔
1551

1552
               BOTAN_ASSERT_EQUAL(q1, q2, "Quotient ok");
96✔
1553
               BOTAN_ASSERT_EQUAL(r1, r2, "Remainder ok");
201✔
1554
            }
1555

1556
            record_result(div_timer);
9✔
1557
            record_result(ct_div_timer);
9✔
1558
         }
54✔
1559
      }
1✔
1560

1561
      void bench_mp_div10(const std::chrono::milliseconds runtime) {
1✔
1562
         std::chrono::milliseconds runtime_per_size = runtime;
1✔
1563

1564
         for(size_t n_bits : {256, 384, 512, 768, 1024, 1536, 2048, 3072, 4096}) {
10✔
1565
            const std::string bit_descr = std::to_string(n_bits) + "/10";
18✔
1566

1567
            auto div_timer = make_timer("BigInt div " + bit_descr);
18✔
1568
            auto ct_div_timer = make_timer("BigInt ct_div " + bit_descr);
18✔
1569

1570
            Botan::BigInt x;
9✔
1571
            Botan::secure_vector<Botan::word> ws;
9✔
1572

1573
            const auto ten = Botan::BigInt::from_word(10);
9✔
1574
            Botan::BigInt q1, r1, q2;
9✔
1575
            Botan::word r2;
9✔
1576

1577
            while(ct_div_timer->under(runtime_per_size)) {
9✔
1578
               x.randomize(rng(), n_bits);
677✔
1579

1580
               div_timer->start();
677✔
1581
               Botan::vartime_divide(x, ten, q1, r1);
677✔
1582
               div_timer->stop();
677✔
1583

1584
               ct_div_timer->start();
677✔
1585
               Botan::ct_divide_word(x, 10, q2, r2);
677✔
1586
               ct_div_timer->stop();
677✔
1587

1588
               BOTAN_ASSERT_EQUAL(q1, q2, "Quotient ok");
677✔
1589
               BOTAN_ASSERT_EQUAL(r1, r2, "Remainder ok");
1,363✔
1590
            }
1591

1592
            record_result(div_timer);
9✔
1593
            record_result(ct_div_timer);
9✔
1594
         }
45✔
1595
      }
1✔
1596

1597
#endif
1598

1599
#if defined(BOTAN_HAS_DL_GROUP)
1600

1601
      void bench_modexp(const std::chrono::milliseconds runtime) {
1✔
1602
         for(size_t group_bits : {1024, 1536, 2048, 3072, 4096}) {
6✔
1603
            const std::string group_bits_str = std::to_string(group_bits);
5✔
1604
            const Botan::DL_Group group("modp/srp/" + group_bits_str);
5✔
1605

1606
            const size_t e_bits = Botan::dl_exponent_size(group_bits);
5✔
1607
            const size_t f_bits = group_bits - 1;
5✔
1608

1609
            const Botan::BigInt random_e(rng(), e_bits);
5✔
1610
            const Botan::BigInt random_f(rng(), f_bits);
5✔
1611

1612
            auto e_timer = make_timer(group_bits_str + " short exponent");
10✔
1613
            auto f_timer = make_timer(group_bits_str + "  full exponent");
10✔
1614

1615
            while(f_timer->under(runtime)) {
11✔
1616
               e_timer->run([&]() { group.power_g_p(random_e); });
12✔
1617
               f_timer->run([&]() { group.power_g_p(random_f); });
12✔
1618
            }
1619

1620
            record_result(e_timer);
5✔
1621
            record_result(f_timer);
5✔
1622
         }
20✔
1623
      }
6✔
1624
#endif
1625

1626
#if defined(BOTAN_HAS_NUMBERTHEORY)
1627
      void bench_nistp_redc(const std::chrono::milliseconds runtime) {
1✔
1628
         Botan::secure_vector<Botan::word> ws;
1✔
1629

1630
         auto p192_timer = make_timer("P-192 redc");
2✔
1631
         Botan::BigInt r192(rng(), 192 * 2 - 1);
1✔
1632
         while(p192_timer->under(runtime)) {
6,733✔
1633
            Botan::BigInt r = r192;
6,732✔
1634
            p192_timer->run([&]() { Botan::redc_p192(r, ws); });
13,464✔
1635
            r192 += 1;
6,732✔
1636
         }
6,732✔
1637
         record_result(p192_timer);
1✔
1638

1639
         auto p224_timer = make_timer("P-224 redc");
2✔
1640
         Botan::BigInt r224(rng(), 224 * 2 - 1);
1✔
1641
         while(p224_timer->under(runtime)) {
6,835✔
1642
            Botan::BigInt r = r224;
6,834✔
1643
            p224_timer->run([&]() { Botan::redc_p224(r, ws); });
13,668✔
1644
            r224 += 1;
6,834✔
1645
         }
6,834✔
1646
         record_result(p224_timer);
1✔
1647

1648
         auto p256_timer = make_timer("P-256 redc");
2✔
1649
         Botan::BigInt r256(rng(), 256 * 2 - 1);
1✔
1650
         while(p256_timer->under(runtime)) {
6,569✔
1651
            Botan::BigInt r = r256;
6,568✔
1652
            p256_timer->run([&]() { Botan::redc_p256(r, ws); });
13,136✔
1653
            r256 += 1;
6,568✔
1654
         }
6,568✔
1655
         record_result(p256_timer);
1✔
1656

1657
         auto p384_timer = make_timer("P-384 redc");
2✔
1658
         Botan::BigInt r384(rng(), 384 * 2 - 1);
1✔
1659
         while(p384_timer->under(runtime)) {
5,838✔
1660
            Botan::BigInt r = r384;
5,837✔
1661
            p384_timer->run([&]() { Botan::redc_p384(r384, ws); });
11,674✔
1662
            r384 += 1;
5,837✔
1663
         }
5,837✔
1664
         record_result(p384_timer);
1✔
1665

1666
         auto p521_timer = make_timer("P-521 redc");
2✔
1667
         Botan::BigInt r521(rng(), 521 * 2 - 1);
1✔
1668
         while(p521_timer->under(runtime)) {
3,975✔
1669
            Botan::BigInt r = r521;
3,974✔
1670
            p521_timer->run([&]() { Botan::redc_p521(r521, ws); });
7,948✔
1671
            r521 += 1;
3,974✔
1672
         }
3,974✔
1673
         record_result(p521_timer);
1✔
1674
      }
6✔
1675

1676
      void bench_bn_redc(const std::chrono::milliseconds runtime) {
1✔
1677
         for(size_t bitsize : {512, 1024, 2048, 4096}) {
5✔
1678
            Botan::BigInt p(rng(), bitsize);
4✔
1679

1680
            std::string bit_str = std::to_string(bitsize);
4✔
1681
            auto barrett_timer = make_timer("Barrett-" + bit_str);
8✔
1682
            auto schoolbook_timer = make_timer("Schoolbook-" + bit_str);
8✔
1683

1684
            Botan::Modular_Reducer mod_p(p);
4✔
1685

1686
            while(schoolbook_timer->under(runtime)) {
122✔
1687
               const Botan::BigInt x(rng(), p.bits() * 2 - 2);
118✔
1688

1689
               const Botan::BigInt r1 = barrett_timer->run([&] { return mod_p.reduce(x); });
236✔
1690
               const Botan::BigInt r2 = schoolbook_timer->run([&] { return x % p; });
236✔
1691

1692
               BOTAN_ASSERT(r1 == r2, "Computed different results");
118✔
1693
            }
354✔
1694

1695
            record_result(barrett_timer);
4✔
1696
            record_result(schoolbook_timer);
4✔
1697
         }
8✔
1698
      }
1✔
1699

1700
      void bench_inverse_mod(const std::chrono::milliseconds runtime) {
1✔
1701
         for(size_t bits : {256, 384, 512, 1024, 2048}) {
6✔
1702
            const std::string bit_str = std::to_string(bits);
5✔
1703

1704
            auto timer = make_timer("inverse_mod-" + bit_str);
10✔
1705
            auto gcd_timer = make_timer("gcd-" + bit_str);
10✔
1706

1707
            while(timer->under(runtime) && gcd_timer->under(runtime)) {
15✔
1708
               const Botan::BigInt x(rng(), bits - 1);
10✔
1709
               Botan::BigInt mod(rng(), bits);
10✔
1710

1711
               const Botan::BigInt x_inv = timer->run([&] { return Botan::inverse_mod(x, mod); });
20✔
1712

1713
               const Botan::BigInt g = gcd_timer->run([&] { return gcd(x, mod); });
20✔
1714

1715
               if(x_inv == 0) {
10✔
1716
                  BOTAN_ASSERT(g != 1, "Inversion only fails if gcd(x, mod) > 1");
4✔
1717
               } else {
1718
                  BOTAN_ASSERT(g == 1, "Inversion succeeds only if gcd != 1");
6✔
1719
                  const Botan::BigInt check = (x_inv * x) % mod;
6✔
1720
                  BOTAN_ASSERT_EQUAL(check, 1, "Const time inversion correct");
6✔
1721
               }
6✔
1722
            }
38✔
1723

1724
            record_result(timer);
5✔
1725
            record_result(gcd_timer);
5✔
1726
         }
5✔
1727
      }
1✔
1728

1729
      void bench_primality_tests(const std::chrono::milliseconds runtime) {
1✔
1730
         for(size_t bits : {256, 512, 1024}) {
4✔
1731
            auto mr_timer = make_timer("Miller-Rabin-" + std::to_string(bits));
6✔
1732
            auto bpsw_timer = make_timer("Bailie-PSW-" + std::to_string(bits));
6✔
1733
            auto lucas_timer = make_timer("Lucas-" + std::to_string(bits));
6✔
1734

1735
            Botan::BigInt n = Botan::random_prime(rng(), bits);
3✔
1736

1737
            while(lucas_timer->under(runtime)) {
6✔
1738
               Botan::Modular_Reducer mod_n(n);
3✔
1739

1740
               mr_timer->run([&]() { return Botan::is_miller_rabin_probable_prime(n, mod_n, rng(), 2); });
6✔
1741

1742
               bpsw_timer->run([&]() { return Botan::is_bailie_psw_probable_prime(n, mod_n); });
6✔
1743

1744
               lucas_timer->run([&]() { return Botan::is_lucas_probable_prime(n, mod_n); });
6✔
1745

1746
               n += 2;
3✔
1747
            }
3✔
1748

1749
            record_result(mr_timer);
3✔
1750
            record_result(bpsw_timer);
3✔
1751
            record_result(lucas_timer);
3✔
1752
         }
3✔
1753
      }
1✔
1754

1755
      void bench_random_prime(const std::chrono::milliseconds runtime) {
1✔
1756
         const auto coprime = Botan::BigInt::from_word(0x10001);
1✔
1757

1758
         for(size_t bits : {256, 384, 512, 768, 1024, 1536}) {
7✔
1759
            auto genprime_timer = make_timer("random_prime " + std::to_string(bits));
12✔
1760
            auto gensafe_timer = make_timer("random_safe_prime " + std::to_string(bits));
12✔
1761
            auto is_prime_timer = make_timer("is_prime " + std::to_string(bits));
12✔
1762

1763
            while(gensafe_timer->under(runtime)) {
12✔
1764
               const Botan::BigInt p = genprime_timer->run([&] { return Botan::random_prime(rng(), bits, coprime); });
12✔
1765

1766
               if(!is_prime_timer->run([&] { return Botan::is_prime(p, rng(), 64, true); })) {
12✔
1767
                  error_output() << "Generated prime " << p << " which failed a primality test";
×
1768
               }
1769

1770
               const Botan::BigInt sg = gensafe_timer->run([&] { return Botan::random_safe_prime(rng(), bits); });
12✔
1771

1772
               if(!is_prime_timer->run([&] { return Botan::is_prime(sg, rng(), 64, true); })) {
12✔
1773
                  error_output() << "Generated safe prime " << sg << " which failed a primality test";
×
1774
               }
1775

1776
               if(!is_prime_timer->run([&] { return Botan::is_prime(sg / 2, rng(), 64, true); })) {
18✔
1777
                  error_output() << "Generated prime " << sg / 2 << " which failed a primality test";
×
1778
               }
1779

1780
               // Now test p+2, p+4, ... which may or may not be prime
1781
               for(size_t i = 2; i <= 64; i += 2) {
198✔
1782
                  is_prime_timer->run([&]() { Botan::is_prime(p + i, rng(), 64, true); });
576✔
1783
               }
1784
            }
12✔
1785

1786
            record_result(genprime_timer);
6✔
1787
            record_result(gensafe_timer);
6✔
1788
            record_result(is_prime_timer);
6✔
1789
         }
6✔
1790
      }
1✔
1791
#endif
1792

1793
#if defined(BOTAN_HAS_PUBLIC_KEY_CRYPTO)
1794
      void bench_pk_enc(const Botan::Private_Key& key,
4✔
1795
                        const std::string& nm,
1796
                        const std::string& provider,
1797
                        const std::string& padding,
1798
                        std::chrono::milliseconds msec) {
1799
         std::vector<uint8_t> plaintext, ciphertext;
4✔
1800

1801
         Botan::PK_Encryptor_EME enc(key, rng(), padding, provider);
4✔
1802
         Botan::PK_Decryptor_EME dec(key, rng(), padding, provider);
4✔
1803

1804
         auto enc_timer = make_timer(nm + " " + padding, provider, "encrypt");
8✔
1805
         auto dec_timer = make_timer(nm + " " + padding, provider, "decrypt");
8✔
1806

1807
         while(enc_timer->under(msec) || dec_timer->under(msec)) {
12✔
1808
            // Generate a new random ciphertext to decrypt
1809
            if(ciphertext.empty() || enc_timer->under(msec)) {
4✔
1810
               rng().random_vec(plaintext, enc.maximum_input_size());
4✔
1811
               ciphertext = enc_timer->run([&]() { return enc.encrypt(plaintext, rng()); });
8✔
1812
            }
1813

1814
            if(dec_timer->under(msec)) {
4✔
1815
               const auto dec_pt = dec_timer->run([&]() { return dec.decrypt(ciphertext); });
12✔
1816

1817
               if(!(Botan::unlock(dec_pt) == plaintext))  // sanity check
4✔
1818
               {
1819
                  error_output() << "Bad roundtrip in PK encrypt/decrypt bench\n";
×
1820
               }
1821
            }
4✔
1822
         }
1823

1824
         record_result(enc_timer);
4✔
1825
         record_result(dec_timer);
4✔
1826
      }
4✔
1827

1828
      void bench_pk_ka(const std::string& algo,
13✔
1829
                       const std::string& nm,
1830
                       const std::string& params,
1831
                       const std::string& provider,
1832
                       std::chrono::milliseconds msec) {
1833
         const std::string kdf = "KDF2(SHA-256)";  // arbitrary choice
13✔
1834

1835
         auto keygen_timer = make_timer(nm, provider, "keygen");
26✔
1836

1837
         std::unique_ptr<Botan::Private_Key> key1(
13✔
1838
            keygen_timer->run([&] { return Botan::create_private_key(algo, rng(), params); }));
26✔
1839
         std::unique_ptr<Botan::Private_Key> key2(
13✔
1840
            keygen_timer->run([&] { return Botan::create_private_key(algo, rng(), params); }));
26✔
1841

1842
         record_result(keygen_timer);
13✔
1843

1844
         const Botan::PK_Key_Agreement_Key& ka_key1 = dynamic_cast<const Botan::PK_Key_Agreement_Key&>(*key1);
13✔
1845
         const Botan::PK_Key_Agreement_Key& ka_key2 = dynamic_cast<const Botan::PK_Key_Agreement_Key&>(*key2);
13✔
1846

1847
         Botan::PK_Key_Agreement ka1(ka_key1, rng(), kdf, provider);
13✔
1848
         Botan::PK_Key_Agreement ka2(ka_key2, rng(), kdf, provider);
13✔
1849

1850
         const std::vector<uint8_t> ka1_pub = ka_key1.public_value();
13✔
1851
         const std::vector<uint8_t> ka2_pub = ka_key2.public_value();
13✔
1852

1853
         auto ka_timer = make_timer(nm, provider, "key agreements");
26✔
1854

1855
         while(ka_timer->under(msec)) {
31✔
1856
            Botan::SymmetricKey symkey1 = ka_timer->run([&]() { return ka1.derive_key(32, ka2_pub); });
36✔
1857
            Botan::SymmetricKey symkey2 = ka_timer->run([&]() { return ka2.derive_key(32, ka1_pub); });
36✔
1858

1859
            if(symkey1 != symkey2) {
18✔
1860
               error_output() << "Key agreement mismatch in PK bench\n";
×
1861
            }
1862
         }
36✔
1863

1864
         record_result(ka_timer);
13✔
1865
      }
39✔
1866

1867
      void bench_pk_kem(const Botan::Private_Key& key,
11✔
1868
                        const std::string& nm,
1869
                        const std::string& provider,
1870
                        const std::string& kdf,
1871
                        std::chrono::milliseconds msec) {
1872
         Botan::PK_KEM_Decryptor dec(key, rng(), kdf, provider);
11✔
1873
         Botan::PK_KEM_Encryptor enc(key, kdf, provider);
11✔
1874

1875
         auto kem_enc_timer = make_timer(nm, provider, "KEM encrypt");
22✔
1876
         auto kem_dec_timer = make_timer(nm, provider, "KEM decrypt");
22✔
1877

1878
         while(kem_enc_timer->under(msec) && kem_dec_timer->under(msec)) {
53✔
1879
            Botan::secure_vector<uint8_t> salt = rng().random_vec(16);
42✔
1880

1881
            kem_enc_timer->start();
42✔
1882
            const auto kem_result = enc.encrypt(rng(), 64, salt);
42✔
1883
            kem_enc_timer->stop();
42✔
1884

1885
            kem_dec_timer->start();
42✔
1886
            Botan::secure_vector<uint8_t> dec_shared_key = dec.decrypt(kem_result.encapsulated_shared_key(), 64, salt);
42✔
1887
            kem_dec_timer->stop();
42✔
1888

1889
            if(kem_result.shared_key() != dec_shared_key) {
42✔
1890
               error_output() << "KEM mismatch in PK bench\n";
×
1891
            }
1892
         }
84✔
1893

1894
         record_result(kem_enc_timer);
11✔
1895
         record_result(kem_dec_timer);
11✔
1896
      }
11✔
1897

1898
      void bench_pk_sig_ecc(const std::string& algo,
7✔
1899
                            const std::string& emsa,
1900
                            const std::string& provider,
1901
                            const std::vector<std::string>& params,
1902
                            std::chrono::milliseconds msec) {
1903
         for(std::string grp : params) {
34✔
1904
            const std::string nm = grp.empty() ? algo : Botan::fmt("{}-{}", algo, grp);
27✔
1905

1906
            auto keygen_timer = make_timer(nm, provider, "keygen");
54✔
1907

1908
            std::unique_ptr<Botan::Private_Key> key(
27✔
1909
               keygen_timer->run([&] { return Botan::create_private_key(algo, rng(), grp); }));
54✔
1910

1911
            record_result(keygen_timer);
27✔
1912
            bench_pk_sig(*key, nm, provider, emsa, msec);
27✔
1913
         }
27✔
1914
      }
7✔
1915

1916
      size_t bench_pk_sig(const Botan::Private_Key& key,
42✔
1917
                          const std::string& nm,
1918
                          const std::string& provider,
1919
                          const std::string& padding,
1920
                          std::chrono::milliseconds msec) {
1921
         std::vector<uint8_t> message, signature, bad_signature;
42✔
1922

1923
         Botan::PK_Signer sig(key, rng(), padding, Botan::Signature_Format::Standard, provider);
42✔
1924
         Botan::PK_Verifier ver(key, padding, Botan::Signature_Format::Standard, provider);
42✔
1925

1926
         auto sig_timer = make_timer(nm + " " + padding, provider, "sign");
84✔
1927
         auto ver_timer = make_timer(nm + " " + padding, provider, "verify");
84✔
1928

1929
         size_t invalid_sigs = 0;
42✔
1930

1931
         while(ver_timer->under(msec) || sig_timer->under(msec)) {
244✔
1932
            if(signature.empty() || sig_timer->under(msec)) {
160✔
1933
               /*
1934
               Length here is kind of arbitrary, but 48 bytes fits into a single
1935
               hash block so minimizes hashing overhead versus the PK op itself.
1936
               */
1937
               rng().random_vec(message, 48);
106✔
1938

1939
               signature = sig_timer->run([&]() { return sig.sign_message(message, rng()); });
212✔
1940

1941
               bad_signature = signature;
106✔
1942
               bad_signature[rng().next_byte() % bad_signature.size()] ^= rng().next_nonzero_byte();
106✔
1943
            }
1944

1945
            if(ver_timer->under(msec)) {
160✔
1946
               const bool verified = ver_timer->run([&] { return ver.verify_message(message, signature); });
212✔
1947

1948
               if(!verified) {
106✔
1949
                  invalid_sigs += 1;
×
1950
               }
1951

1952
               const bool verified_bad = ver_timer->run([&] { return ver.verify_message(message, bad_signature); });
212✔
1953

1954
               if(verified_bad) {
106✔
1955
                  error_output() << "Bad signature accepted in " << nm << " signature bench\n";
×
1956
               }
1957
            }
1958
         }
1959

1960
         if(invalid_sigs > 0) {
42✔
1961
            error_output() << invalid_sigs << " generated signatures rejected in " << nm << " signature bench\n";
×
1962
         }
1963

1964
         const size_t events = static_cast<size_t>(std::min(sig_timer->events(), ver_timer->events()));
42✔
1965

1966
         record_result(sig_timer);
42✔
1967
         record_result(ver_timer);
42✔
1968

1969
         return events;
42✔
1970
      }
42✔
1971
#endif
1972

1973
#if defined(BOTAN_HAS_RSA)
1974
      void bench_rsa_keygen(const std::string& provider, std::chrono::milliseconds msec) {
1✔
1975
         for(size_t keylen : {1024, 2048, 3072, 4096}) {
5✔
1976
            const std::string nm = "RSA-" + std::to_string(keylen);
8✔
1977
            auto keygen_timer = make_timer(nm, provider, "keygen");
8✔
1978

1979
            while(keygen_timer->under(msec)) {
8✔
1980
               std::unique_ptr<Botan::Private_Key> key(
4✔
1981
                  keygen_timer->run([&] { return Botan::create_private_key("RSA", rng(), std::to_string(keylen)); }));
8✔
1982

1983
               BOTAN_ASSERT(key->check_key(rng(), true), "Key is ok");
4✔
1984
            }
4✔
1985

1986
            record_result(keygen_timer);
4✔
1987
         }
4✔
1988
      }
1✔
1989

1990
      void bench_rsa(const std::string& provider, std::chrono::milliseconds msec) {
1✔
1991
         for(size_t keylen : {1024, 2048, 3072, 4096}) {
5✔
1992
            const std::string nm = "RSA-" + std::to_string(keylen);
8✔
1993

1994
            auto keygen_timer = make_timer(nm, provider, "keygen");
8✔
1995

1996
            std::unique_ptr<Botan::Private_Key> key(
4✔
1997
               keygen_timer->run([&] { return Botan::create_private_key("RSA", rng(), std::to_string(keylen)); }));
8✔
1998

1999
            record_result(keygen_timer);
4✔
2000

2001
            // Using PKCS #1 padding so OpenSSL provider can play along
2002
            bench_pk_sig(*key, nm, provider, "EMSA-PKCS1-v1_5(SHA-256)", msec);
8✔
2003

2004
            //bench_pk_sig(*key, nm, provider, "PSSR(SHA-256)", msec);
2005
            //bench_pk_enc(*key, nm, provider, "EME-PKCS1-v1_5", msec);
2006
            //bench_pk_enc(*key, nm, provider, "OAEP(SHA-1)", msec);
2007
         }
4✔
2008
      }
1✔
2009
#endif
2010

2011
#if defined(BOTAN_HAS_ECDSA)
2012
      void bench_ecdsa(const std::vector<std::string>& groups,
1✔
2013
                       const std::string& provider,
2014
                       std::chrono::milliseconds msec) {
2015
         return bench_pk_sig_ecc("ECDSA", "SHA-256", provider, groups, msec);
2✔
2016
      }
2017

2018
      void bench_ecdsa_recovery(const std::vector<std::string>& groups,
1✔
2019
                                const std::string& /*unused*/,
2020
                                std::chrono::milliseconds msec) {
2021
         for(const std::string& group_name : groups) {
7✔
2022
            const auto group = Botan::EC_Group::from_name(group_name);
6✔
2023
            auto recovery_timer = make_timer("ECDSA recovery " + group_name);
12✔
2024

2025
            while(recovery_timer->under(msec)) {
14✔
2026
               Botan::ECDSA_PrivateKey key(rng(), group);
8✔
2027

2028
               std::vector<uint8_t> message(group.get_order_bits() / 8);
8✔
2029
               rng().randomize(message.data(), message.size());
8✔
2030

2031
               Botan::PK_Signer signer(key, rng(), "Raw");
8✔
2032
               signer.update(message);
8✔
2033
               std::vector<uint8_t> signature = signer.signature(rng());
8✔
2034

2035
               Botan::PK_Verifier verifier(key, "Raw", Botan::Signature_Format::Standard, "base");
8✔
2036
               verifier.update(message);
8✔
2037
               BOTAN_ASSERT(verifier.check_signature(signature), "Valid signature");
8✔
2038

2039
               Botan::BigInt r(signature.data(), signature.size() / 2);
8✔
2040
               Botan::BigInt s(signature.data() + signature.size() / 2, signature.size() / 2);
8✔
2041

2042
               const uint8_t v = key.recovery_param(message, r, s);
8✔
2043

2044
               recovery_timer->run([&]() {
8✔
2045
                  Botan::ECDSA_PublicKey pubkey(group, message, r, s, v);
8✔
2046
                  BOTAN_ASSERT(pubkey.public_point() == key.public_point(), "Recovered public key");
8✔
2047
               });
8✔
2048
            }
16✔
2049

2050
            record_result(recovery_timer);
6✔
2051
         }
6✔
2052
      }
1✔
2053

2054
#endif
2055

2056
#if defined(BOTAN_HAS_ECKCDSA)
2057
      void bench_eckcdsa(const std::vector<std::string>& groups,
1✔
2058
                         const std::string& provider,
2059
                         std::chrono::milliseconds msec) {
2060
         return bench_pk_sig_ecc("ECKCDSA", "SHA-256", provider, groups, msec);
2✔
2061
      }
2062
#endif
2063

2064
#if defined(BOTAN_HAS_GOST_34_10_2001)
2065
      void bench_gost_3410(const std::string& provider, std::chrono::milliseconds msec) {
1✔
2066
         return bench_pk_sig_ecc("GOST-34.10", "GOST-34.11", provider, {"gost_256A"}, msec);
2✔
2067
      }
2068
#endif
2069

2070
#if defined(BOTAN_HAS_SM2)
2071
      void bench_sm2(const std::vector<std::string>& groups,
1✔
2072
                     const std::string& provider,
2073
                     std::chrono::milliseconds msec) {
2074
         return bench_pk_sig_ecc("SM2_Sig", "SM3", provider, groups, msec);
2✔
2075
      }
2076
#endif
2077

2078
#if defined(BOTAN_HAS_ECGDSA)
2079
      void bench_ecgdsa(const std::vector<std::string>& groups,
1✔
2080
                        const std::string& provider,
2081
                        std::chrono::milliseconds msec) {
2082
         return bench_pk_sig_ecc("ECGDSA", "SHA-256", provider, groups, msec);
2✔
2083
      }
2084
#endif
2085

2086
#if defined(BOTAN_HAS_ED25519)
2087
      void bench_ed25519(const std::string& provider, std::chrono::milliseconds msec) {
1✔
2088
         return bench_pk_sig_ecc("Ed25519", "Pure", provider, std::vector<std::string>{""}, msec);
3✔
2089
      }
2✔
2090
#endif
2091

2092
#if defined(BOTAN_HAS_ED448)
2093
      void bench_ed448(const std::string& provider, std::chrono::milliseconds msec) {
1✔
2094
         return bench_pk_sig_ecc("Ed448", "Pure", provider, std::vector<std::string>{""}, msec);
3✔
2095
      }
2✔
2096
#endif
2097

2098
#if defined(BOTAN_HAS_DIFFIE_HELLMAN)
2099
      void bench_dh(const std::string& provider, std::chrono::milliseconds msec) {
1✔
2100
         for(size_t bits : {2048, 3072, 4096, 6144, 8192}) {
6✔
2101
            bench_pk_ka("DH", "DH-" + std::to_string(bits), "ffdhe/ietf/" + std::to_string(bits), provider, msec);
20✔
2102
         }
2103
      }
1✔
2104
#endif
2105

2106
#if defined(BOTAN_HAS_DSA)
2107
      void bench_dsa(const std::string& provider, std::chrono::milliseconds msec) {
1✔
2108
         for(size_t bits : {1024, 2048, 3072}) {
4✔
2109
            const std::string nm = "DSA-" + std::to_string(bits);
6✔
2110

2111
            const std::string params = (bits == 1024) ? "dsa/jce/1024" : ("dsa/botan/" + std::to_string(bits));
5✔
2112

2113
            auto keygen_timer = make_timer(nm, provider, "keygen");
6✔
2114

2115
            std::unique_ptr<Botan::Private_Key> key(
3✔
2116
               keygen_timer->run([&] { return Botan::create_private_key("DSA", rng(), params); }));
6✔
2117

2118
            record_result(keygen_timer);
3✔
2119

2120
            bench_pk_sig(*key, nm, provider, "SHA-256", msec);
6✔
2121
         }
3✔
2122
      }
1✔
2123
#endif
2124

2125
#if defined(BOTAN_HAS_ELGAMAL)
2126
      void bench_elgamal(const std::string& provider, std::chrono::milliseconds msec) {
1✔
2127
         for(size_t keylen : {1024, 2048, 3072, 4096}) {
5✔
2128
            const std::string nm = "ElGamal-" + std::to_string(keylen);
8✔
2129

2130
            const std::string params = "modp/ietf/" + std::to_string(keylen);
8✔
2131

2132
            auto keygen_timer = make_timer(nm, provider, "keygen");
8✔
2133

2134
            std::unique_ptr<Botan::Private_Key> key(
4✔
2135
               keygen_timer->run([&] { return Botan::create_private_key("ElGamal", rng(), params); }));
8✔
2136

2137
            record_result(keygen_timer);
4✔
2138

2139
            bench_pk_enc(*key, nm, provider, "EME-PKCS1-v1_5", msec);
8✔
2140
         }
4✔
2141
      }
1✔
2142
#endif
2143

2144
#if defined(BOTAN_HAS_ECDH)
2145
      void bench_ecdh(const std::vector<std::string>& groups,
1✔
2146
                      const std::string& provider,
2147
                      std::chrono::milliseconds msec) {
2148
         for(const std::string& grp : groups) {
7✔
2149
            bench_pk_ka("ECDH", "ECDH-" + grp, grp, provider, msec);
12✔
2150
         }
2151
      }
1✔
2152
#endif
2153

2154
#if defined(BOTAN_HAS_X25519)
2155
      void bench_x25519(const std::string& provider, std::chrono::milliseconds msec) {
1✔
2156
         bench_pk_ka("X25519", "X25519", "", provider, msec);
2✔
2157
      }
1✔
2158
#endif
2159

2160
#if defined(BOTAN_HAS_X448)
2161
      void bench_x448(const std::string& provider, std::chrono::milliseconds msec) {
1✔
2162
         bench_pk_ka("X448", "X448", "", provider, msec);
2✔
2163
      }
1✔
2164
#endif
2165

2166
#if defined(BOTAN_HAS_MCELIECE)
2167
      void bench_mceliece(const std::string& provider, std::chrono::milliseconds msec) {
1✔
2168
         /*
2169
         SL=80 n=1632 t=33 - 59 KB pubkey 140 KB privkey
2170
         SL=107 n=2480 t=45 - 128 KB pubkey 300 KB privkey
2171
         SL=128 n=2960 t=57 - 195 KB pubkey 459 KB privkey
2172
         SL=147 n=3408 t=67 - 265 KB pubkey 622 KB privkey
2173
         SL=191 n=4624 t=95 - 516 KB pubkey 1234 KB privkey
2174
         SL=256 n=6624 t=115 - 942 KB pubkey 2184 KB privkey
2175
         */
2176

2177
         const std::vector<std::pair<size_t, size_t>> mce_params = {
1✔
2178
            {2480, 45}, {2960, 57}, {3408, 67}, {4624, 95}, {6624, 115}};
1✔
2179

2180
         for(auto params : mce_params) {
6✔
2181
            size_t n = params.first;
5✔
2182
            size_t t = params.second;
5✔
2183

2184
            const std::string nm = "McEliece-" + std::to_string(n) + "," + std::to_string(t) +
20✔
2185
                                   " (WF=" + std::to_string(Botan::mceliece_work_factor(n, t)) + ")";
15✔
2186

2187
            auto keygen_timer = make_timer(nm, provider, "keygen");
10✔
2188

2189
            std::unique_ptr<Botan::Private_Key> key =
5✔
2190
               keygen_timer->run([&] { return std::make_unique<Botan::McEliece_PrivateKey>(rng(), n, t); });
10✔
2191

2192
            record_result(keygen_timer);
5✔
2193
            bench_pk_kem(*key, nm, provider, "KDF2(SHA-256)", msec);
10✔
2194
         }
5✔
2195
      }
1✔
2196
#endif
2197

2198
#if defined(BOTAN_HAS_KYBER) || defined(BOTAN_HAS_KYBER_90S)
2199
      void bench_kyber(const std::string& provider, std::chrono::milliseconds msec) {
1✔
2200
         const Botan::KyberMode::Mode all_modes[] = {
1✔
2201
            Botan::KyberMode::Kyber512_R3,
2202
            Botan::KyberMode::Kyber512_90s,
2203
            Botan::KyberMode::Kyber768_R3,
2204
            Botan::KyberMode::Kyber768_90s,
2205
            Botan::KyberMode::Kyber1024_R3,
2206
            Botan::KyberMode::Kyber1024_90s,
2207
         };
2208

2209
         for(auto modet : all_modes) {
7✔
2210
            Botan::KyberMode mode(modet);
6✔
2211

2212
   #if !defined(BOTAN_HAS_KYBER)
2213
            if(mode.is_modern())
2214
               continue;
2215
   #endif
2216

2217
   #if !defined(BOTAN_HAS_KYBER_90S)
2218
            if(mode.is_90s())
2219
               continue;
2220
   #endif
2221

2222
            auto keygen_timer = make_timer(mode.to_string(), provider, "keygen");
12✔
2223

2224
            auto key = keygen_timer->run([&] { return Botan::Kyber_PrivateKey(rng(), mode); });
12✔
2225

2226
            record_result(keygen_timer);
6✔
2227

2228
            bench_pk_kem(key, mode.to_string(), provider, "KDF2(SHA-256)", msec);
12✔
2229
         }
6✔
2230
      }
1✔
2231
#endif
2232

2233
#if defined(BOTAN_HAS_DILITHIUM) || defined(BOTAN_HAS_DILITHIUM_AES)
2234
      void bench_dilithium(const std::string& provider, std::chrono::milliseconds msec) {
1✔
2235
         const Botan::DilithiumMode::Mode all_modes[] = {Botan::DilithiumMode::Dilithium4x4,
1✔
2236
                                                         Botan::DilithiumMode::Dilithium4x4_AES,
2237
                                                         Botan::DilithiumMode::Dilithium6x5,
2238
                                                         Botan::DilithiumMode::Dilithium6x5_AES,
2239
                                                         Botan::DilithiumMode::Dilithium8x7,
2240
                                                         Botan::DilithiumMode::Dilithium8x7_AES};
2241

2242
         for(auto modet : all_modes) {
7✔
2243
            Botan::DilithiumMode mode(modet);
6✔
2244

2245
   #if !defined(BOTAN_HAS_DILITHIUM)
2246
            if(mode.is_modern())
2247
               continue;
2248
   #endif
2249

2250
   #if !defined(BOTAN_HAS_DILITHIUM_AES)
2251
            if(mode.is_aes())
2252
               continue;
2253
   #endif
2254

2255
            auto keygen_timer = make_timer(mode.to_string(), provider, "keygen");
12✔
2256

2257
            auto key = keygen_timer->run([&] { return Botan::Dilithium_PrivateKey(rng(), mode); });
12✔
2258

2259
            record_result(keygen_timer);
6✔
2260

2261
            bench_pk_sig(key, mode.to_string(), provider, "", msec);
12✔
2262
         }
6✔
2263
      }
1✔
2264
#endif
2265

2266
#if defined(BOTAN_HAS_SPHINCS_PLUS_WITH_SHA2) || defined(BOTAN_HAS_SPHINCS_PLUS_WITH_SHAKE)
2267
      void bench_sphincs_plus(const std::string& provider, std::chrono::milliseconds msec) {
1✔
2268
         // Sphincs_Parameter_Set set, Sphincs_Hash_Type hash
2269
         std::vector<std::string> sphincs_params{"SphincsPlus-sha2-128s-r3.1",
1✔
2270
                                                 "SphincsPlus-sha2-128f-r3.1",
2271
                                                 "SphincsPlus-sha2-192s-r3.1",
2272
                                                 "SphincsPlus-sha2-192f-r3.1",
2273
                                                 "SphincsPlus-sha2-256s-r3.1",
2274
                                                 "SphincsPlus-sha2-256f-r3.1",
2275
                                                 "SphincsPlus-shake-128s-r3.1",
2276
                                                 "SphincsPlus-shake-128f-r3.1",
2277
                                                 "SphincsPlus-shake-192s-r3.1",
2278
                                                 "SphincsPlus-shake-192f-r3.1",
2279
                                                 "SphincsPlus-shake-256s-r3.1",
2280
                                                 "SphincsPlus-shake-256f-r3.1"};
14✔
2281

2282
         for(auto params : sphincs_params) {
1✔
2283
            try {
1✔
2284
               auto keygen_timer = make_timer(params, provider, "keygen");
2✔
2285

2286
               std::unique_ptr<Botan::Private_Key> key(
1✔
2287
                  keygen_timer->run([&] { return Botan::create_private_key("SPHINCS+", rng(), params); }));
2✔
2288

2289
               record_result(keygen_timer);
1✔
2290
               if(bench_pk_sig(*key, params, provider, "", msec) == 1) {
1✔
2291
                  break;
2292
               }
2293
            } catch(Botan::Not_Implemented&) {
1✔
2294
               continue;
×
2295
            }
×
2296
         }
1✔
2297
      }
3✔
2298
#endif
2299

2300
#if defined(BOTAN_HAS_FRODOKEM)
2301
      void bench_frodokem(const std::string& provider, std::chrono::milliseconds msec) {
×
2302
         std::vector<Botan::FrodoKEMMode> frodo_modes{
×
2303
            Botan::FrodoKEMMode::FrodoKEM640_SHAKE,
2304
            Botan::FrodoKEMMode::FrodoKEM976_SHAKE,
2305
            Botan::FrodoKEMMode::FrodoKEM1344_SHAKE,
2306
            Botan::FrodoKEMMode::eFrodoKEM640_SHAKE,
2307
            Botan::FrodoKEMMode::eFrodoKEM976_SHAKE,
2308
            Botan::FrodoKEMMode::eFrodoKEM1344_SHAKE,
2309
            Botan::FrodoKEMMode::FrodoKEM640_AES,
2310
            Botan::FrodoKEMMode::FrodoKEM976_AES,
2311
            Botan::FrodoKEMMode::FrodoKEM1344_AES,
2312
            Botan::FrodoKEMMode::eFrodoKEM640_AES,
2313
            Botan::FrodoKEMMode::eFrodoKEM976_AES,
2314
            Botan::FrodoKEMMode::eFrodoKEM1344_AES,
2315
         };
×
2316

2317
         for(auto modet : frodo_modes) {
×
2318
            if(!modet.is_available()) {
×
2319
               continue;
×
2320
            }
2321

2322
            Botan::FrodoKEMMode mode(modet);
×
2323

2324
            auto keygen_timer = make_timer(mode.to_string(), provider, "keygen");
×
2325

2326
            auto key = keygen_timer->run([&] { return Botan::FrodoKEM_PrivateKey(rng(), mode); });
×
2327

2328
            record_result(keygen_timer);
×
2329

2330
            bench_pk_kem(key, mode.to_string(), provider, "KDF2(SHA-256)", msec);
×
2331
         }
×
2332
      }
×
2333
#endif
2334

2335
#if defined(BOTAN_HAS_XMSS_RFC8391)
2336
      void bench_xmss(const std::string& provider, std::chrono::milliseconds msec) {
1✔
2337
         /*
2338
         We only test H10 signatures here since already they are quite slow (a
2339
         few seconds per signature). On a fast machine, H16 signatures take 1-2
2340
         minutes to generate and H20 signatures take 5-10 minutes to generate
2341
         */
2342
         std::vector<std::string> xmss_params{
1✔
2343
            "XMSS-SHA2_10_256",
2344
            "XMSS-SHAKE_10_256",
2345
            "XMSS-SHA2_10_512",
2346
            "XMSS-SHAKE_10_512",
2347
         };
6✔
2348

2349
         for(std::string params : xmss_params) {
1✔
2350
            auto keygen_timer = make_timer(params, provider, "keygen");
2✔
2351

2352
            std::unique_ptr<Botan::Private_Key> key(
1✔
2353
               keygen_timer->run([&] { return Botan::create_private_key("XMSS", rng(), params); }));
2✔
2354

2355
            record_result(keygen_timer);
1✔
2356
            if(bench_pk_sig(*key, params, provider, "", msec) == 1) {
1✔
2357
               break;
2358
            }
2359
         }
1✔
2360
      }
3✔
2361
#endif
2362

2363
#if defined(BOTAN_HAS_HSS_LMS)
2364
      void bench_hss_lms(const std::string& provider, std::chrono::milliseconds msec) {
×
2365
         // At first we compare instances with multiple hash functions. LMS trees with
2366
         // height 10 are suitable, since they can be used for enough signatures and are
2367
         // fast enough for speed testing.
2368
         // Afterward, setups with multiple HSS layers are tested
2369
         std::vector<std::string> hss_lms_instances{"SHA-256,HW(10,1)",
×
2370
                                                    "SHAKE-256(256),HW(10,1)",
2371
                                                    "SHAKE-256(192),HW(10,1)",
2372
                                                    "Truncated(SHA-256,192),HW(10,1)",
2373
                                                    "SHA-256,HW(10,1),HW(10,1)",
2374
                                                    "SHA-256,HW(10,1),HW(10,1),HW(10,1)"};
×
2375

2376
         for(const auto& params : hss_lms_instances) {
×
2377
            auto keygen_timer = make_timer(params, provider, "keygen");
×
2378

2379
            std::unique_ptr<Botan::Private_Key> key(
×
2380
               keygen_timer->run([&] { return Botan::create_private_key("HSS-LMS", rng(), params); }));
×
2381

2382
            record_result(keygen_timer);
×
2383
            if(bench_pk_sig(*key, params, provider, "", msec) == 1) {
×
2384
               break;
2385
            }
2386
         }
×
2387
      }
×
2388
#endif
2389

2390
#if defined(BOTAN_HAS_ZFEC)
2391
      void bench_zfec(std::chrono::milliseconds msec) {
1✔
2392
         const size_t k = 4;
1✔
2393
         const size_t n = 16;
1✔
2394

2395
         Botan::ZFEC zfec(k, n);
1✔
2396

2397
         const size_t share_size = 256 * 1024;
1✔
2398

2399
         std::vector<uint8_t> input(share_size * k);
1✔
2400
         rng().randomize(input.data(), input.size());
1✔
2401

2402
         std::vector<uint8_t> output(share_size * n);
1✔
2403

2404
         auto enc_fn = [&](size_t share, const uint8_t buf[], size_t len) {
17✔
2405
            std::memcpy(&output[share * share_size], buf, len);
16✔
2406
         };
17✔
2407

2408
         auto enc_timer =
1✔
2409
            make_timer("zfec " + std::to_string(k) + "/" + std::to_string(n), input.size(), "encode", "", input.size());
4✔
2410

2411
         enc_timer->run_until_elapsed(msec, [&]() { zfec.encode(input.data(), input.size(), enc_fn); });
3✔
2412

2413
         record_result(enc_timer);
1✔
2414

2415
         auto dec_timer =
1✔
2416
            make_timer("zfec " + std::to_string(k) + "/" + std::to_string(n), input.size(), "decode", "", input.size());
4✔
2417

2418
         std::map<size_t, const uint8_t*> shares;
1✔
2419
         for(size_t i = 0; i != n; ++i) {
17✔
2420
            shares[i] = &output[share_size * i];
16✔
2421
         }
2422

2423
         // remove data shares to make decoding maximally expensive:
2424
         while(shares.size() != k) {
13✔
2425
            shares.erase(shares.begin());
12✔
2426
         }
2427

2428
         std::vector<uint8_t> recovered(share_size * k);
1✔
2429

2430
         auto dec_fn = [&](size_t share, const uint8_t buf[], size_t len) {
5✔
2431
            std::memcpy(&recovered[share * share_size], buf, len);
4✔
2432
         };
5✔
2433

2434
         dec_timer->run_until_elapsed(msec, [&]() { zfec.decode_shares(shares, share_size, dec_fn); });
3✔
2435

2436
         record_result(dec_timer);
1✔
2437

2438
         if(recovered != input) {
1✔
2439
            error_output() << "ZFEC recovery failed\n";
×
2440
         }
2441
      }
1✔
2442

2443
#endif
2444

2445
#if defined(BOTAN_HAS_POLY_DBL)
2446
      void bench_poly_dbl(std::chrono::milliseconds msec) {
1✔
2447
         for(size_t sz : {8, 16, 24, 32, 64, 128}) {
7✔
2448
            auto be_timer = make_timer("poly_dbl_be_" + std::to_string(sz));
12✔
2449
            auto le_timer = make_timer("poly_dbl_le_" + std::to_string(sz));
12✔
2450

2451
            std::vector<uint8_t> buf(sz);
6✔
2452
            rng().randomize(buf.data(), sz);
6✔
2453

2454
            be_timer->run_until_elapsed(msec, [&]() { Botan::poly_double_n(buf.data(), buf.data(), sz); });
33,418✔
2455
            le_timer->run_until_elapsed(msec, [&]() { Botan::poly_double_n_le(buf.data(), buf.data(), sz); });
47,555✔
2456

2457
            record_result(be_timer);
6✔
2458
            record_result(le_timer);
6✔
2459
         }
6✔
2460
      }
1✔
2461
#endif
2462

2463
#if defined(BOTAN_HAS_BCRYPT)
2464

2465
      void bench_bcrypt() {
1✔
2466
         const std::string password = "not a very good password";
1✔
2467

2468
         for(uint8_t work_factor = 4; work_factor <= 14; ++work_factor) {
12✔
2469
            auto timer = make_timer("bcrypt wf=" + std::to_string(work_factor));
22✔
2470

2471
            timer->run([&] { Botan::generate_bcrypt(password, rng(), work_factor); });
22✔
2472

2473
            record_result(timer);
11✔
2474
         }
11✔
2475
      }
1✔
2476
#endif
2477

2478
#if defined(BOTAN_HAS_PASSHASH9)
2479

2480
      void bench_passhash9() {
1✔
2481
         const std::string password = "not a very good password";
1✔
2482

2483
         for(uint8_t alg = 0; alg <= 4; ++alg) {
6✔
2484
            if(Botan::is_passhash9_alg_supported(alg) == false) {
5✔
2485
               continue;
×
2486
            }
2487

2488
            for(auto work_factor : {10, 15}) {
15✔
2489
               auto timer = make_timer("passhash9 alg=" + std::to_string(alg) + " wf=" + std::to_string(work_factor));
40✔
2490

2491
               timer->run([&] { Botan::generate_passhash9(password, rng(), static_cast<uint8_t>(work_factor), alg); });
20✔
2492

2493
               record_result(timer);
10✔
2494
            }
10✔
2495
         }
2496
      }
1✔
2497
#endif
2498

2499
#if defined(BOTAN_HAS_SCRYPT)
2500

2501
      void bench_scrypt(const std::string& /*provider*/, std::chrono::milliseconds msec) {
1✔
2502
         auto pwdhash_fam = Botan::PasswordHashFamily::create_or_throw("Scrypt");
1✔
2503

2504
         for(size_t N : {8192, 16384, 32768, 65536}) {
5✔
2505
            for(size_t r : {1, 8, 16}) {
16✔
2506
               for(size_t p : {1}) {
12✔
2507
                  auto pwdhash = pwdhash_fam->from_params(N, r, p);
12✔
2508

2509
                  auto scrypt_timer =
12✔
2510
                     make_timer("scrypt-" + std::to_string(N) + "-" + std::to_string(r) + "-" + std::to_string(p) +
72✔
2511
                                " (" + std::to_string(pwdhash->total_memory_usage() / (1024 * 1024)) + " MiB)");
48✔
2512

2513
                  uint8_t out[64];
12✔
2514
                  uint8_t salt[8];
12✔
2515
                  rng().randomize(salt, sizeof(salt));
12✔
2516

2517
                  while(scrypt_timer->under(msec)) {
24✔
2518
                     scrypt_timer->run([&] {
12✔
2519
                        pwdhash->derive_key(out, sizeof(out), "password", 8, salt, sizeof(salt));
12✔
2520

2521
                        Botan::copy_mem(salt, out, 8);
12✔
2522
                     });
12✔
2523
                  }
2524

2525
                  record_result(scrypt_timer);
12✔
2526

2527
                  if(scrypt_timer->events() == 1) {
12✔
2528
                     break;
2529
                  }
2530
               }
24✔
2531
            }
2532
         }
2533
      }
1✔
2534

2535
#endif
2536

2537
#if defined(BOTAN_HAS_ARGON2)
2538

2539
      void bench_argon2(const std::string& /*provider*/, std::chrono::milliseconds msec) {
1✔
2540
         auto pwhash_fam = Botan::PasswordHashFamily::create_or_throw("Argon2id");
1✔
2541

2542
         for(size_t M : {8 * 1024, 64 * 1024, 256 * 1024}) {
4✔
2543
            for(size_t t : {1, 4}) {
9✔
2544
               for(size_t p : {1, 4}) {
18✔
2545
                  auto pwhash = pwhash_fam->from_params(M, t, p);
12✔
2546
                  auto timer = make_timer(pwhash->to_string());
24✔
2547

2548
                  uint8_t out[64];
12✔
2549
                  uint8_t salt[16];
12✔
2550
                  rng().randomize(salt, sizeof(salt));
12✔
2551

2552
                  while(timer->under(msec)) {
24✔
2553
                     timer->run([&] { pwhash->derive_key(out, sizeof(out), "password", 8, salt, sizeof(salt)); });
24✔
2554
                  }
2555

2556
                  record_result(timer);
12✔
2557
               }
24✔
2558
            }
2559
         }
2560
      }
1✔
2561

2562
#endif
2563

2564
#if defined(BOTAN_HAS_BASE64_CODEC)
2565
      void bench_base64(std::chrono::milliseconds msec, const std::vector<size_t>& buf_sizes) {
×
2566
         for(size_t buf_size : buf_sizes) {
×
2567
            std::vector<uint8_t> ibuf(buf_size);
×
2568
            std::vector<uint8_t> rbuf(buf_size);
×
2569
            const size_t olen = Botan::base64_encode_max_output(ibuf.size());
×
2570

2571
            auto enc_timer = make_timer("base64", ibuf.size(), "encode", "", ibuf.size());
×
2572

2573
            auto dec_timer = make_timer("base64", olen, "decode", "", olen);
×
2574

2575
            while(enc_timer->under(msec) && dec_timer->under(msec)) {
×
2576
               rng().randomize(ibuf);
×
2577

2578
               std::string b64 = enc_timer->run([&]() { return Botan::base64_encode(ibuf); });
×
2579

2580
               dec_timer->run([&]() { Botan::base64_decode(rbuf.data(), b64); });
×
2581
               BOTAN_ASSERT(rbuf == ibuf, "Encode/decode round trip ok");
×
2582
            }
×
2583

2584
            record_result(enc_timer);
×
2585
            record_result(dec_timer);
×
2586
         }
×
2587
      }
×
2588
#endif
2589

2590
#if defined(BOTAN_HAS_HEX_CODEC)
2591
      void bench_hex(std::chrono::milliseconds msec, const std::vector<size_t>& buf_sizes) {
×
2592
         for(size_t buf_size : buf_sizes) {
×
2593
            std::vector<uint8_t> ibuf(buf_size);
×
2594
            std::vector<uint8_t> rbuf(buf_size);
×
2595
            const size_t olen = 2 * buf_size;
×
2596

2597
            auto enc_timer = make_timer("hex", ibuf.size(), "encode", "", ibuf.size());
×
2598

2599
            auto dec_timer = make_timer("hex", olen, "decode", "", olen);
×
2600

2601
            while(enc_timer->under(msec) && dec_timer->under(msec)) {
×
2602
               rng().randomize(ibuf);
×
2603

2604
               std::string hex = enc_timer->run([&]() { return Botan::hex_encode(ibuf); });
×
2605

2606
               dec_timer->run([&]() { Botan::hex_decode(rbuf.data(), hex); });
×
2607
               BOTAN_ASSERT(rbuf == ibuf, "Encode/decode round trip ok");
×
2608
            }
×
2609

2610
            record_result(enc_timer);
×
2611
            record_result(dec_timer);
×
2612
         }
×
2613
      }
×
2614
#endif
2615
};
2616

2617
BOTAN_REGISTER_COMMAND("speed", Speed);
34✔
2618

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

© 2026 Coveralls, Inc