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

randombit / botan / 12969367069

25 Jan 2025 11:33PM UTC coverage: 91.224% (-0.003%) from 91.227%
12969367069

Pull #4593

github

web-flow
Merge 212e6285e into 79027d241
Pull Request #4593: New interface for PKCS8 key encryption

93636 of 102644 relevant lines covered (91.22%)

11516421.43 hits per line

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

74.9
/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
         if(pass.empty()) {
20✔
65
            if(der_out) {
20✔
66
               write_output(Botan::PKCS8::BER_encode(*key));
×
67
            } else {
68
               output() << Botan::PKCS8::PEM_encode(*key);
40✔
69
            }
70
         } else {
71
            auto options = [&]() {
×
72
               std::string cipher = get_arg("cipher");
×
73
               std::string pwhash = get_arg("pbkdf");
×
74
               if(get_arg("pbkdf-iter").empty()) {
×
75
                  const std::chrono::milliseconds pwhash_ms(get_arg_sz("pbkdf-ms"));
×
76
                  return Botan::PKCS8::KeyEncryptionOptions(cipher, pwhash, pwhash_ms);
×
77
               } else {
78
                  return Botan::PKCS8::KeyEncryptionOptions(cipher, pwhash, get_arg_sz("pbkdf-iter"));
×
79
               }
80
            }();
×
81

82
            auto pkcs8 = Botan::PKCS8::encrypt_private_key(*key, pass, rng(), options);
×
83

84
            if(der_out) {
×
85
               write_output(pkcs8.as_bytes());
×
86
            } else {
87
               output() << pkcs8.as_pem();
×
88
            }
89
         }
×
90
      }
40✔
91
};
92

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

95
   #if defined(BOTAN_TARGET_OS_HAS_FILESYSTEM)
96

97
namespace {
98

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

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

121
}  // namespace
122

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

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

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

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

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

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

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

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

152
namespace {
153

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

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

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

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

176
}  // namespace
177

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

318
            if(pass_out.empty()) {
4✔
319
               if(der_out) {
2✔
320
                  write_output(Botan::PKCS8::BER_encode(*key));
×
321
               } else {
322
                  output() << Botan::PKCS8::PEM_encode(*key);
4✔
323
               }
324
            } else {
325
               auto options = [&]() {
×
326
                  std::string cipher = get_arg("cipher");
2✔
327
                  std::string pwhash = get_arg("pbkdf");
2✔
328
                  if(get_arg("pbkdf-iter").empty()) {
2✔
329
                     const std::chrono::milliseconds pwhash_ms(get_arg_sz("pbkdf-ms"));
2✔
330
                     return Botan::PKCS8::KeyEncryptionOptions(cipher, pwhash, pwhash_ms);
2✔
331
                  } else {
332
                     return Botan::PKCS8::KeyEncryptionOptions(cipher, pwhash, get_arg_sz("pbkdf-iter"));
×
333
                  }
334
               }();
4✔
335

336
               auto pkcs8 = Botan::PKCS8::encrypt_private_key(*key, pass_out, rng(), options);
2✔
337

338
               if(der_out) {
2✔
339
                  write_output(pkcs8.as_bytes());
1✔
340
               } else {
341
                  output() << pkcs8.as_pem();
2✔
342
               }
343
            }
4✔
344
         }
4✔
345
      }
18✔
346
};
347

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

350
   #endif
351

352
   #if defined(BOTAN_HAS_ECC_GROUP)
353

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

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

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

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

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

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

381
   #endif
382

383
   #if defined(BOTAN_HAS_DL_GROUP)
384

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

491
   #endif
492

493
}  // namespace Botan_CLI
494

495
#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