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

randombit / botan / 5123321399

30 May 2023 04:06PM UTC coverage: 92.213% (+0.004%) from 92.209%
5123321399

Pull #3558

github

web-flow
Merge dd72f7389 into 057bcbc35
Pull Request #3558: Add braces around all if/else statements

75602 of 81986 relevant lines covered (92.21%)

11859779.3 hits per line

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

76.21
/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() :
20✔
42
            Command(
43
               "keygen --algo=RSA --params= --passphrase= --cipher= --pbkdf= --pbkdf-ms=300 --pbkdf-iter= --provider= --der-out") {
20✔
44
      }
20✔
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 {
19✔
51
         const std::string algo = get_arg("algo");
19✔
52
         const std::string params = get_arg("params");
19✔
53
         const std::string provider = get_arg("provider");
19✔
54

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

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

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

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

66
         if(der_out) {
19✔
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()) {
19✔
80
               output() << Botan::PKCS8::PEM_encode(*key);
57✔
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
      }
42✔
92
};
93

94
BOTAN_REGISTER_COMMAND("keygen", PK_Keygen);
20✔
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;
7✔
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))
17✔
138
                                                                   : Botan::X509::load_key(key_file));
9✔
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) { err_string = e.what(); }
3✔
162

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

170
   throw CLI_Error("Loading private key failed (" + err_string + ")");
×
171
}
3✔
172

173
}  // namespace
174

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

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

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

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

187
         auto key = load_private_key(key_file, passphrase);
3✔
188

189
         const std::string hash_fn = get_arg("hash");
3✔
190

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

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

197
         auto format = Botan::Signature_Format::Standard;
3✔
198

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

207
         const std::string provider = get_arg("provider");
3✔
208

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

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

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

216
         if(key->stateful_operation()) {
3✔
217
            std::ofstream updated_key(key_file);
2✔
218
            if(passphrase.empty()) {
2✔
219
               updated_key << Botan::PKCS8::PEM_encode(*key);
6✔
220
            } else {
221
               updated_key << Botan::PKCS8::PEM_encode(*key, rng(), passphrase);
×
222
            }
223
         }
2✔
224

225
         output() << Botan::base64_encode(sig) << "\n";
6✔
226
      }
9✔
227
};
228

229
BOTAN_REGISTER_COMMAND("sign", PK_Sign);
4✔
230

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

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

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

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

247
         const std::string hash_fn = get_arg("hash");
4✔
248

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

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

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

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

268
         const Botan::secure_vector<uint8_t> signature =
4✔
269
            Botan::base64_decode(this->slurp_file_as_str(get_arg("signature")));
10✔
270

271
         const bool valid = verifier.check_signature(signature);
4✔
272

273
         output() << "Signature is " << (valid ? "valid" : "invalid") << "\n";
5✔
274
      }
8✔
275
};
276

277
BOTAN_REGISTER_COMMAND("verify", PK_Verify);
5✔
278

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

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

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

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

294
         Botan::DataSource_Memory key_src(slurp_file(key_file));
18✔
295
         std::unique_ptr<Botan::Private_Key> key;
9✔
296

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

303
         const std::chrono::milliseconds pbkdf_ms(get_arg_sz("pbkdf-ms"));
9✔
304
         const bool der_out = flag_set("der-out");
9✔
305

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

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

344
BOTAN_REGISTER_COMMAND("pkcs8", PKCS8_Tool);
10✔
345

346
   #endif
347

348
   #if defined(BOTAN_HAS_ECC_GROUP)
349

350
class EC_Group_Info final : public Command {
351
   public:
352
      EC_Group_Info() : Command("ec_group_info --pem name") {}
6✔
353

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

356
      std::string description() const override {
1✔
357
         return "Print raw elliptic curve domain parameters of the standardized curve name";
1✔
358
      }
359

360
      void go() override {
2✔
361
         Botan::EC_Group ec_group(get_arg("name"));
4✔
362

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

375
BOTAN_REGISTER_COMMAND("ec_group_info", EC_Group_Info);
3✔
376

377
   #endif
378

379
   #if defined(BOTAN_HAS_DL_GROUP)
380

381
class DL_Group_Info final : public Command {
382
   public:
383
      DL_Group_Info() : Command("dl_group_info --pem name") {}
16✔
384

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

387
      std::string description() const override {
1✔
388
         return "Print raw Diffie-Hellman parameters (p,g) of the standardized DH group name";
1✔
389
      }
390

391
      void go() override {
7✔
392
         Botan::DL_Group dl_group(get_arg("name"));
14✔
393

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

403
BOTAN_REGISTER_COMMAND("dl_group_info", DL_Group_Info);
8✔
404

405
class PK_Workfactor final : public Command {
406
   public:
407
      PK_Workfactor() : Command("pk_workfactor --type=rsa bits") {}
12✔
408

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

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

413
      void go() override {
5✔
414
         const size_t bits = get_arg_sz("bits");
5✔
415
         const std::string type = get_arg("type");
5✔
416

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

429
BOTAN_REGISTER_COMMAND("pk_workfactor", PK_Workfactor);
6✔
430

431
class Gen_DL_Group final : public Command {
432
   public:
433
      Gen_DL_Group() : Command("gen_dl_group --pbits=2048 --qbits=0 --seed= --type=subgroup") {}
6✔
434

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

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

439
      void go() override {
2✔
440
         const size_t pbits = get_arg_sz("pbits");
2✔
441
         const size_t qbits = get_arg_sz("qbits");
2✔
442

443
         const std::string type = get_arg("type");
2✔
444
         const std::string seed_str = get_arg("seed");
2✔
445

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

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

479
         } else {
480
            throw CLI_Usage_Error("Invalid DL type '" + type + "'");
×
481
         }
482
      }
2✔
483
};
484

485
BOTAN_REGISTER_COMMAND("gen_dl_group", Gen_DL_Group);
3✔
486

487
   #endif
488

489
}  // namespace Botan_CLI
490

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

© 2025 Coveralls, Inc