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

randombit / botan / 12991133942

27 Jan 2025 02:24PM UTC coverage: 91.246% (-0.008%) from 91.254%
12991133942

push

github

web-flow
Merge pull request #4592 from randombit/jack/split-key-prework

Some initial refactoring for splitting public and private keys

93966 of 102981 relevant lines covered (91.25%)

11558329.57 hits per line

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

74.8
/src/cli/pubkey.cpp
1
/*
2
* (C) 2010,2014,2015,2019 Jack Lloyd
3
* (C) 2019 Matthias Gierlings
4
* (C) 2015 René Korthaus
5
*
6
* Botan is released under the Simplified BSD License (see license.txt)
7
*/
8

9
#include "cli.h"
10

11
#if defined(BOTAN_HAS_PUBLIC_KEY_CRYPTO)
12

13
   #include <botan/base64.h>
14
   #include <botan/hex.h>
15
   #include <botan/rng.h>
16

17
   #include <botan/data_src.h>
18
   #include <botan/hash.h>
19
   #include <botan/pk_algs.h>
20
   #include <botan/pk_keys.h>
21
   #include <botan/pkcs8.h>
22
   #include <botan/pubkey.h>
23
   #include <botan/x509_key.h>
24
   #include <botan/internal/workfactor.h>
25

26
   #include <fstream>
27
   #include <sstream>
28

29
   #if defined(BOTAN_HAS_DL_GROUP)
30
      #include <botan/dl_group.h>
31
   #endif
32

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

37
namespace Botan_CLI {
38

39
class PK_Keygen final : public Command {
40
   public:
41
      PK_Keygen() :
21✔
42
            Command(
43
               "keygen --algo=RSA --params= --passphrase= --cipher= --pbkdf= --pbkdf-ms=300 --pbkdf-iter= --provider= --der-out") {
21✔
44
      }
21✔
45

46
      std::string group() const override { return "pubkey"; }
1✔
47

48
      std::string description() const override { return "Generate a PKCS #8 private key"; }
1✔
49

50
      void go() override {
20✔
51
         const std::string algo = get_arg("algo");
20✔
52
         const std::string params = get_arg("params");
20✔
53
         const std::string provider = get_arg("provider");
20✔
54

55
         std::unique_ptr<Botan::Private_Key> key = Botan::create_private_key(algo, rng(), params, provider);
20✔
56

57
         if(!key) {
20✔
58
            throw CLI_Error_Unsupported("keygen", algo);
×
59
         }
60

61
         const std::string pass = get_passphrase_arg("Key passphrase", "passphrase");
40✔
62
         const bool der_out = flag_set("der-out");
20✔
63

64
         const std::chrono::milliseconds pbkdf_ms(get_arg_sz("pbkdf-ms"));
20✔
65

66
         if(der_out) {
20✔
67
            if(pass.empty()) {
×
68
               write_output(Botan::PKCS8::BER_encode(*key));
×
69
            } else {
70
               if(get_arg("pbkdf-iter").empty()) {
×
71
                  write_output(Botan::PKCS8::BER_encode_encrypted_pbkdf_msec(
×
72
                     *key, rng(), pass, pbkdf_ms, nullptr, get_arg("cipher"), get_arg("pbkdf")));
×
73
               } else {
74
                  write_output(Botan::PKCS8::BER_encode_encrypted_pbkdf_iter(
×
75
                     *key, rng(), pass, get_arg_sz("pbkdf-iter"), get_arg("cipher"), get_arg("pbkdf")));
×
76
               }
77
            }
78
         } else {
79
            if(pass.empty()) {
20✔
80
               output() << Botan::PKCS8::PEM_encode(*key);
40✔
81
            } else {
82
               if(get_arg("pbkdf-iter").empty()) {
×
83
                  output() << Botan::PKCS8::PEM_encode_encrypted_pbkdf_msec(
×
84
                     *key, rng(), pass, pbkdf_ms, nullptr, get_arg("cipher"), get_arg("pbkdf"));
×
85
               } else {
86
                  output() << Botan::PKCS8::PEM_encode_encrypted_pbkdf_iter(
×
87
                     *key, rng(), pass, get_arg_sz("pbkdf-iter"), get_arg("cipher"), get_arg("pbkdf"));
×
88
               }
89
            }
90
         }
91
      }
40✔
92
};
93

94
BOTAN_REGISTER_COMMAND("keygen", PK_Keygen);
21✔
95

96
   #if defined(BOTAN_TARGET_OS_HAS_FILESYSTEM)
97

98
namespace {
99

100
std::string choose_sig_padding(const std::string& key, const std::string& padding, const std::string& hash) {
7✔
101
   if(key == "RSA") {
7✔
102
      std::ostringstream oss;
×
103
      if(padding.empty()) {
×
104
         oss << "PSS";
×
105
      } else {
106
         oss << padding;
×
107
      }
108

109
      oss << "(" << hash << ")";
×
110
      return oss.str();
×
111
   } else if(padding.empty()) {
7✔
112
      return hash;
7✔
113
   } else if(hash.empty()) {
×
114
      return padding;
×
115
   } else {
116
      std::ostringstream oss;
×
117
      oss << padding << "(" << hash << ")";
×
118
      return oss.str();
×
119
   }
×
120
}
121

122
}  // namespace
123

124
class PK_Fingerprint final : public Command {
125
   public:
126
      PK_Fingerprint() : Command("fingerprint --no-fsname --algo=SHA-256 *keys") {}
16✔
127

128
      std::string group() const override { return "pubkey"; }
1✔
129

130
      std::string description() const override { return "Calculate a public key fingerprint"; }
1✔
131

132
      void go() override {
7✔
133
         const std::string hash_algo = get_arg("algo");
7✔
134
         const bool no_fsname = flag_set("no-fsname");
7✔
135

136
         for(const std::string& key_file : get_arg_list("keys")) {
15✔
137
            std::unique_ptr<Botan::Public_Key> key(key_file == "-" ? Botan::X509::load_key(this->slurp_file("-", 4096))
18✔
138
                                                                   : Botan::X509::load_key(key_file));
8✔
139

140
            const std::string fprint = key->fingerprint_public(hash_algo);
8✔
141

142
            if(no_fsname || key_file == "-") {
8✔
143
               output() << fprint << "\n";
7✔
144
            } else {
145
               output() << key_file << ": " << fprint << "\n";
1✔
146
            }
147
         }
23✔
148
      }
7✔
149
};
150

151
BOTAN_REGISTER_COMMAND("fingerprint", PK_Fingerprint);
8✔
152

153
namespace {
154

155
std::unique_ptr<Botan::Private_Key> load_private_key(const std::string& key_filename, const std::string& passphrase) {
3✔
156
   std::string err_string;
3✔
157

158
   try {
3✔
159
      Botan::DataSource_Stream input(key_filename);
3✔
160
      return Botan::PKCS8::load_key(input, passphrase);
3✔
161
   } catch(Botan::Exception& e) {
3✔
162
      err_string = e.what();
×
163
   }
×
164

165
   if(passphrase.empty()) {
×
166
      try {
×
167
         Botan::DataSource_Stream input(key_filename);
×
168
         return Botan::PKCS8::load_key(input);
×
169
      } catch(Botan::Exception& e) {
×
170
         err_string = e.what();
×
171
      }
×
172
   }
173

174
   throw CLI_Error("Loading private key failed (" + err_string + ")");
×
175
}
3✔
176

177
}  // namespace
178

179
class PK_Sign final : public Command {
180
   public:
181
      PK_Sign() : Command("sign --der-format --passphrase= --hash=SHA-256 --padding= --provider= key file") {}
8✔
182

183
      std::string group() const override { return "pubkey"; }
1✔
184

185
      std::string description() const override { return "Sign arbitrary data"; }
1✔
186

187
      void go() override {
3✔
188
         const std::string key_file = get_arg("key");
3✔
189
         const std::string passphrase = get_passphrase_arg("Passphrase for " + key_file, "passphrase");
6✔
190

191
         auto key = load_private_key(key_file, passphrase);
3✔
192

193
         const std::string hash_fn = get_arg("hash");
3✔
194

195
         if(!hash_fn.empty() && !Botan::HashFunction::create(hash_fn)) {
6✔
196
            throw CLI_Error_Unsupported("hashing", hash_fn);
×
197
         }
198

199
         const std::string sig_padding = choose_sig_padding(key->algo_name(), get_arg("padding"), hash_fn);
6✔
200

201
         auto format = Botan::Signature_Format::Standard;
3✔
202

203
         if(flag_set("der-format")) {
3✔
204
            if(!key->_signature_element_size_for_DER_encoding()) {
×
205
               throw CLI_Usage_Error("Key type " + key->algo_name() +
×
206
                                     " does not support DER formatting for signatures");
×
207
            }
208
            format = Botan::Signature_Format::DerSequence;
209
         }
210

211
         const std::string provider = get_arg("provider");
3✔
212

213
         Botan::PK_Signer signer(*key, rng(), sig_padding, format, provider);
3✔
214

215
         auto onData = [&signer](const uint8_t b[], size_t l) { signer.update(b, l); };
3✔
216
         Command::read_file(get_arg("file"), onData);
6✔
217

218
         std::vector<uint8_t> sig{signer.signature(rng())};
3✔
219

220
         if(key->stateful_operation()) {
3✔
221
            std::ofstream updated_key(key_file);
2✔
222
            if(passphrase.empty()) {
2✔
223
               updated_key << Botan::PKCS8::PEM_encode(*key);
4✔
224
            } else {
225
               updated_key << Botan::PKCS8::PEM_encode(*key, rng(), passphrase);
×
226
            }
227
         }
2✔
228

229
         output() << Botan::base64_encode(sig) << "\n";
6✔
230
      }
6✔
231
};
232

233
BOTAN_REGISTER_COMMAND("sign", PK_Sign);
4✔
234

235
class PK_Verify final : public Command {
236
   public:
237
      PK_Verify() : Command("verify --der-format --hash=SHA-256 --padding= pubkey file signature") {}
10✔
238

239
      std::string group() const override { return "pubkey"; }
1✔
240

241
      std::string description() const override {
1✔
242
         return "Verify the authenticity of the given file with the provided signature";
1✔
243
      }
244

245
      void go() override {
4✔
246
         auto key = Botan::X509::load_key(get_arg("pubkey"));
8✔
247
         if(!key) {
4✔
248
            throw CLI_Error("Unable to load public key");
×
249
         }
250

251
         const std::string hash_fn = get_arg("hash");
4✔
252

253
         if(!hash_fn.empty() && !Botan::HashFunction::create(hash_fn)) {
8✔
254
            throw CLI_Error_Unsupported("hashing", hash_fn);
×
255
         }
256

257
         const std::string sig_padding = choose_sig_padding(key->algo_name(), get_arg("padding"), hash_fn);
8✔
258

259
         auto format = Botan::Signature_Format::Standard;
4✔
260
         if(flag_set("der-format")) {
4✔
261
            if(key->message_parts() == 1) {
×
262
               throw CLI_Usage_Error("Key type " + key->algo_name() +
×
263
                                     " does not support DER formatting for signatures");
×
264
            }
265
            format = Botan::Signature_Format::DerSequence;
266
         }
267

268
         Botan::PK_Verifier verifier(*key, sig_padding, format);
4✔
269
         auto onData = [&verifier](const uint8_t b[], size_t l) { verifier.update(b, l); };
4✔
270
         Command::read_file(get_arg("file"), onData);
8✔
271

272
         const Botan::secure_vector<uint8_t> signature =
4✔
273
            Botan::base64_decode(this->slurp_file_as_str(get_arg("signature")));
8✔
274

275
         const bool valid = verifier.check_signature(signature);
4✔
276

277
         output() << "Signature is " << (valid ? "valid" : "invalid") << "\n";
5✔
278
      }
8✔
279
};
280

281
BOTAN_REGISTER_COMMAND("verify", PK_Verify);
5✔
282

283
class PKCS8_Tool final : public Command {
284
   public:
285
      PKCS8_Tool() :
10✔
286
            Command(
287
               "pkcs8 --pass-in= --pub-out --der-out --pass-out= --cipher= --pbkdf= --pbkdf-ms=300 --pbkdf-iter= key") {
10✔
288
      }
10✔
289

290
      std::string group() const override { return "pubkey"; }
1✔
291

292
      std::string description() const override { return "Open a PKCS #8 formatted key"; }
1✔
293

294
      void go() override {
9✔
295
         const std::string key_file = get_arg("key");
9✔
296
         const std::string pass_in = get_passphrase_arg("Password for " + key_file, "pass-in");
18✔
297

298
         Botan::DataSource_Memory key_src(slurp_file(key_file));
18✔
299
         std::unique_ptr<Botan::Private_Key> key;
9✔
300

301
         if(pass_in.empty()) {
9✔
302
            key = Botan::PKCS8::load_key(key_src);
7✔
303
         } else {
304
            key = Botan::PKCS8::load_key(key_src, pass_in);
2✔
305
         }
306

307
         const std::chrono::milliseconds pbkdf_ms(get_arg_sz("pbkdf-ms"));
9✔
308
         const bool der_out = flag_set("der-out");
9✔
309

310
         if(flag_set("pub-out")) {
9✔
311
            auto pk = key->public_key();
5✔
312
            if(der_out) {
5✔
313
               write_output(Botan::X509::BER_encode(*pk));
2✔
314
            } else {
315
               output() << Botan::X509::PEM_encode(*pk);
8✔
316
            }
317
         } else {
5✔
318
            const std::string pass_out = get_passphrase_arg("Passphrase to encrypt key", "pass-out");
8✔
319

320
            if(der_out) {
4✔
321
               if(pass_out.empty()) {
1✔
322
                  write_output(Botan::PKCS8::BER_encode(*key));
×
323
               } else {
324
                  if(get_arg("pbkdf-iter").empty()) {
1✔
325
                     write_output(Botan::PKCS8::BER_encode_encrypted_pbkdf_msec(
2✔
326
                        *key, rng(), pass_out, pbkdf_ms, nullptr, get_arg("cipher"), get_arg("pbkdf")));
3✔
327
                  } else {
328
                     write_output(Botan::PKCS8::BER_encode_encrypted_pbkdf_iter(
×
329
                        *key, rng(), pass_out, get_arg_sz("pbkdf-iter"), get_arg("cipher"), get_arg("pbkdf")));
×
330
                  }
331
               }
332
            } else {
333
               if(pass_out.empty()) {
3✔
334
                  output() << Botan::PKCS8::PEM_encode(*key);
4✔
335
               } else {
336
                  if(get_arg("pbkdf-iter").empty()) {
1✔
337
                     output() << Botan::PKCS8::PEM_encode_encrypted_pbkdf_msec(
3✔
338
                        *key, rng(), pass_out, pbkdf_ms, nullptr, get_arg("cipher"), get_arg("pbkdf"));
4✔
339
                  } else {
340
                     output() << Botan::PKCS8::PEM_encode_encrypted_pbkdf_iter(
×
341
                        *key, rng(), pass_out, get_arg_sz("pbkdf-iter"), get_arg("cipher"), get_arg("pbkdf"));
×
342
                  }
343
               }
344
            }
345
         }
4✔
346
      }
18✔
347
};
348

349
BOTAN_REGISTER_COMMAND("pkcs8", PKCS8_Tool);
10✔
350

351
   #endif
352

353
   #if defined(BOTAN_HAS_ECC_GROUP)
354

355
class EC_Group_Info final : public Command {
356
   public:
357
      EC_Group_Info() : Command("ec_group_info --pem name") {}
6✔
358

359
      std::string group() const override { return "pubkey"; }
1✔
360

361
      std::string description() const override {
1✔
362
         return "Print raw elliptic curve domain parameters of the standardized curve name";
1✔
363
      }
364

365
      void go() override {
2✔
366
         const auto ec_group = Botan::EC_Group::from_name(get_arg("name"));
4✔
367

368
         if(flag_set("pem")) {
2✔
369
            output() << ec_group.PEM_encode();
2✔
370
         } else {
371
            output() << "P = " << std::hex << ec_group.get_p() << "\n"
1✔
372
                     << "A = " << std::hex << ec_group.get_a() << "\n"
1✔
373
                     << "B = " << std::hex << ec_group.get_b() << "\n"
1✔
374
                     << "N = " << std::hex << ec_group.get_order() << "\n"
1✔
375
                     << "G = " << ec_group.get_g_x() << "," << ec_group.get_g_y() << "\n";
1✔
376
         }
377
      }
2✔
378
};
379

380
BOTAN_REGISTER_COMMAND("ec_group_info", EC_Group_Info);
3✔
381

382
   #endif
383

384
   #if defined(BOTAN_HAS_DL_GROUP)
385

386
class DL_Group_Info final : public Command {
387
   public:
388
      DL_Group_Info() : Command("dl_group_info --pem name") {}
16✔
389

390
      std::string group() const override { return "pubkey"; }
1✔
391

392
      std::string description() const override {
1✔
393
         return "Print raw Diffie-Hellman parameters (p,g) of the standardized DH group name";
1✔
394
      }
395

396
      void go() override {
7✔
397
         auto dl_group = Botan::DL_Group::from_name(get_arg("name"));
14✔
398

399
         if(flag_set("pem")) {
7✔
400
            output() << dl_group.PEM_encode(Botan::DL_Group_Format::ANSI_X9_42_DH_PARAMETERS);
×
401
         } else {
402
            output() << "P = " << std::hex << dl_group.get_p() << "\n"
7✔
403
                     << "G = " << dl_group.get_g() << "\n";
7✔
404
         }
405
      }
7✔
406
};
407

408
BOTAN_REGISTER_COMMAND("dl_group_info", DL_Group_Info);
8✔
409

410
class PK_Workfactor final : public Command {
411
   public:
412
      PK_Workfactor() : Command("pk_workfactor --type=rsa bits") {}
12✔
413

414
      std::string group() const override { return "pubkey"; }
1✔
415

416
      std::string description() const override { return "Provide estimate of strength of public key based on size"; }
1✔
417

418
      void go() override {
5✔
419
         const size_t bits = get_arg_sz("bits");
5✔
420
         const std::string type = get_arg("type");
5✔
421

422
         if(type == "rsa") {
5✔
423
            output() << Botan::if_work_factor(bits) << "\n";
3✔
424
         } else if(type == "dl") {
2✔
425
            output() << Botan::dl_work_factor(bits) << "\n";
1✔
426
         } else if(type == "dl_exp") {
1✔
427
            output() << Botan::dl_exponent_size(bits) << "\n";
1✔
428
         } else {
429
            throw CLI_Usage_Error("Unknown type for pk_workfactor (rsa, dl, dl_exp)");
×
430
         }
431
      }
5✔
432
};
433

434
BOTAN_REGISTER_COMMAND("pk_workfactor", PK_Workfactor);
6✔
435

436
class Gen_DL_Group final : public Command {
437
   public:
438
      Gen_DL_Group() : Command("gen_dl_group --pbits=2048 --qbits=0 --seed= --type=subgroup") {}
6✔
439

440
      std::string group() const override { return "pubkey"; }
1✔
441

442
      std::string description() const override { return "Generate ANSI X9.42 encoded Diffie-Hellman group parameters"; }
1✔
443

444
      void go() override {
2✔
445
         const size_t pbits = get_arg_sz("pbits");
2✔
446
         const size_t qbits = get_arg_sz("qbits");
2✔
447

448
         const std::string type = get_arg("type");
2✔
449
         const std::string seed_str = get_arg("seed");
2✔
450

451
         if(type == "strong") {
2✔
452
            if(!seed_str.empty()) {
×
453
               throw CLI_Usage_Error("Seed only supported for DSA param gen");
×
454
            }
455
            Botan::DL_Group grp(rng(), Botan::DL_Group::Strong, pbits);
×
456
            output() << grp.PEM_encode(Botan::DL_Group_Format::ANSI_X9_42);
×
457
         } else if(type == "subgroup") {
2✔
458
            if(!seed_str.empty()) {
1✔
459
               throw CLI_Usage_Error("Seed only supported for DSA param gen");
×
460
            }
461
            Botan::DL_Group grp(rng(), Botan::DL_Group::Prime_Subgroup, pbits, qbits);
1✔
462
            output() << grp.PEM_encode(Botan::DL_Group_Format::ANSI_X9_42);
2✔
463
         } else if(type == "dsa") {
2✔
464
            size_t dsa_qbits = qbits;
1✔
465
            if(dsa_qbits == 0) {
1✔
466
               if(pbits == 1024) {
1✔
467
                  dsa_qbits = 160;
468
               } else if(pbits == 2048 || pbits == 3072) {
×
469
                  dsa_qbits = 256;
470
               } else {
471
                  throw CLI_Usage_Error("Invalid DSA p/q sizes");
×
472
               }
473
            }
474

475
            if(seed_str.empty()) {
1✔
476
               Botan::DL_Group grp(rng(), Botan::DL_Group::DSA_Kosherizer, pbits, dsa_qbits);
1✔
477
               output() << grp.PEM_encode(Botan::DL_Group_Format::ANSI_X9_57);
2✔
478
            } else {
1✔
479
               const std::vector<uint8_t> seed = Botan::hex_decode(seed_str);
×
480
               Botan::DL_Group grp(rng(), seed, pbits, dsa_qbits);
×
481
               output() << grp.PEM_encode(Botan::DL_Group_Format::ANSI_X9_57);
×
482
            }
×
483

484
         } else {
485
            throw CLI_Usage_Error("Invalid DL type '" + type + "'");
×
486
         }
487
      }
2✔
488
};
489

490
BOTAN_REGISTER_COMMAND("gen_dl_group", Gen_DL_Group);
3✔
491

492
   #endif
493

494
}  // namespace Botan_CLI
495

496
#endif
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