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

randombit / botan / 13394769715

18 Feb 2025 03:11PM UTC coverage: 91.645% (+0.008%) from 91.637%
13394769715

push

github

web-flow
Merge pull request #4698 from Rohde-Schwarz/fix/assertion_in_signature

FIX: setting 'DER' format explicitly on `PK_Signer` trips assertion

94996 of 103656 relevant lines covered (91.65%)

11192395.07 hits per line

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

86.74
/src/tests/test_pubkey.cpp
1
/*
2
* (C) 2009,2015 Jack Lloyd
3
* (C) 2017 Ribose Inc
4
*
5
* Botan is released under the Simplified BSD License (see license.txt)
6
*/
7

8
#include "test_pubkey.h"
9

10
#if defined(BOTAN_HAS_PUBLIC_KEY_CRYPTO)
11

12
   #include "test_rng.h"
13

14
   #include <botan/data_src.h>
15
   #include <botan/hex.h>
16
   #include <botan/pk_algs.h>
17
   #include <botan/pkcs8.h>
18
   #include <botan/pubkey.h>
19
   #include <botan/x509_key.h>
20
   #include <botan/internal/fmt.h>
21
   #include <botan/internal/stl_util.h>
22

23
   #if defined(BOTAN_HAS_HMAC_DRBG)
24
      #include <botan/hmac_drbg.h>
25
   #endif
26

27
   #include <array>
28

29
namespace Botan_Tests {
30

31
namespace {
32

33
void check_invalid_signatures(Test::Result& result,
2,298✔
34
                              Botan::PK_Verifier& verifier,
35
                              const std::vector<uint8_t>& message,
36
                              const std::vector<uint8_t>& signature,
37
                              Botan::RandomNumberGenerator& rng) {
38
   const size_t tests_to_run = (Test::run_long_tests() ? 20 : 5);
2,298✔
39

40
   const std::vector<uint8_t> zero_sig(signature.size());
2,298✔
41
   result.test_eq("all zero signature invalid", verifier.verify_message(message, zero_sig), false);
2,298✔
42

43
   for(size_t i = 0; i < tests_to_run; ++i) {
48,258✔
44
      const std::vector<uint8_t> bad_sig = Test::mutate_vec(signature, rng);
45,960✔
45

46
      try {
45,960✔
47
         if(!result.test_eq("incorrect signature invalid", verifier.verify_message(message, bad_sig), false)) {
45,960✔
48
            result.test_note("Accepted invalid signature " + Botan::hex_encode(bad_sig));
×
49
         }
50
      } catch(std::exception& e) {
×
51
         result.test_note("Accepted invalid signature " + Botan::hex_encode(bad_sig));
×
52
         result.test_failure("Modified signature rejected with exception", e.what());
×
53
      }
×
54
   }
45,960✔
55
}
2,298✔
56

57
}  // namespace
58

59
// Exposed for DLIES tests
60
void check_invalid_ciphertexts(Test::Result& result,
317✔
61
                               Botan::PK_Decryptor& decryptor,
62
                               const std::vector<uint8_t>& plaintext,
63
                               const std::vector<uint8_t>& ciphertext,
64
                               Botan::RandomNumberGenerator& rng) {
65
   const size_t tests_to_run = (Test::run_long_tests() ? 20 : 5);
317✔
66

67
   size_t ciphertext_accepted = 0, ciphertext_rejected = 0;
317✔
68

69
   for(size_t i = 0; i < tests_to_run; ++i) {
6,657✔
70
      const std::vector<uint8_t> bad_ctext = Test::mutate_vec(ciphertext, rng);
6,340✔
71

72
      try {
6,340✔
73
         const Botan::secure_vector<uint8_t> decrypted = decryptor.decrypt(bad_ctext);
6,340✔
74
         ++ciphertext_accepted;
3,228✔
75

76
         if(!result.test_ne("incorrect ciphertext different", decrypted, plaintext)) {
6,456✔
77
            result.test_eq("used corrupted ciphertext", bad_ctext, ciphertext);
×
78
         }
79
      } catch(std::exception&) {
6,340✔
80
         ++ciphertext_rejected;
3,112✔
81
      }
3,112✔
82
   }
6,340✔
83

84
   result.test_note("Accepted " + std::to_string(ciphertext_accepted) + " invalid ciphertexts, rejected " +
1,268✔
85
                    std::to_string(ciphertext_rejected));
317✔
86
}
317✔
87

88
std::string PK_Test::choose_padding(const VarMap& vars, const std::string& pad_hdr) {
15,284✔
89
   if(!pad_hdr.empty()) {
15,284✔
90
      return pad_hdr;
1,836✔
91
   }
92
   return vars.get_opt_str("Padding", this->default_padding(vars));
26,896✔
93
}
94

95
std::vector<std::string> PK_Test::possible_providers(const std::string& /*params*/) {
17,524✔
96
   return Test::provider_filter({"base", "commoncrypto", "openssl", "tpm"});
17,524✔
97
}
98

99
Test::Result PK_Signature_Generation_Test::run_one_test(const std::string& pad_hdr, const VarMap& vars) {
1,257✔
100
   const std::vector<uint8_t> message = vars.get_req_bin("Msg");
1,257✔
101
   const std::vector<uint8_t> signature = vars.get_req_bin("Signature");
1,257✔
102
   const std::string padding = choose_padding(vars, pad_hdr);
1,257✔
103

104
   std::ostringstream test_name;
1,257✔
105
   test_name << algo_name();
2,514✔
106
   if(vars.has_key("Group")) {
2,514✔
107
      test_name << "-" << vars.get_req_str("Group");
254✔
108
   }
109
   test_name << "/" << padding << " signature generation";
1,257✔
110

111
   Test::Result result(test_name.str());
1,257✔
112

113
   std::unique_ptr<Botan::Private_Key> privkey;
1,257✔
114
   try {
1,257✔
115
      privkey = load_private_key(vars);
1,257✔
116
   } catch(Botan::Lookup_Error& e) {
×
117
      result.note_missing(e.what());
×
118
      return result;
×
119
   }
×
120

121
   result.confirm("private key claims to support signatures",
2,514✔
122
                  privkey->supports_operation(Botan::PublicKeyOperation::Signature));
1,257✔
123

124
   auto pubkey = Botan::X509::load_key(Botan::X509::BER_encode(*privkey->public_key()));
2,514✔
125

126
   result.confirm("public key claims to support signatures",
2,514✔
127
                  pubkey->supports_operation(Botan::PublicKeyOperation::Signature));
1,257✔
128

129
   std::vector<std::unique_ptr<Botan::PK_Verifier>> verifiers;
1,257✔
130

131
   for(const auto& verify_provider : possible_providers(algo_name())) {
7,542✔
132
      std::unique_ptr<Botan::PK_Verifier> verifier;
5,028✔
133

134
      try {
5,028✔
135
         verifier =
5,028✔
136
            std::make_unique<Botan::PK_Verifier>(*pubkey, padding, Botan::Signature_Format::Standard, verify_provider);
6,285✔
137
      } catch(Botan::Lookup_Error&) {
3,771✔
138
         //result.test_note("Skipping verifying with " + verify_provider);
139
         continue;
3,771✔
140
      }
3,771✔
141

142
      result.test_eq("KAT signature valid", verifier->verify_message(message, signature), true);
1,257✔
143

144
      check_invalid_signatures(result, *verifier, message, signature, this->rng());
1,257✔
145

146
      result.test_eq("KAT signature valid (try 2)", verifier->verify_message(message, signature), true);
1,257✔
147

148
      verifiers.push_back(std::move(verifier));
1,257✔
149
   }
6,285✔
150

151
   for(const auto& sign_provider : possible_providers(algo_name())) {
7,542✔
152
      std::unique_ptr<Botan::PK_Signer> signer;
5,028✔
153

154
      std::vector<uint8_t> generated_signature;
5,028✔
155

156
      try {
5,028✔
157
         signer = std::make_unique<Botan::PK_Signer>(
5,028✔
158
            *privkey, this->rng(), padding, Botan::Signature_Format::Standard, sign_provider);
6,285✔
159

160
         if(vars.has_key("Nonce")) {
2,514✔
161
            auto rng = test_rng(vars.get_req_bin("Nonce"));
464✔
162
            generated_signature = signer->sign_message(message, *rng);
464✔
163
         } else {
232✔
164
            generated_signature = signer->sign_message(message, this->rng());
2,050✔
165
         }
166

167
         result.test_lte(
1,257✔
168
            "Generated signature within announced bound", generated_signature.size(), signer->signature_length());
169
      } catch(Botan::Lookup_Error&) {
3,771✔
170
         //result.test_note("Skipping signing with " + sign_provider);
171
         continue;
3,771✔
172
      }
3,771✔
173

174
      if(sign_provider == "base") {
1,257✔
175
         result.test_eq("generated signature matches KAT", generated_signature, signature);
2,514✔
176
      } else if(generated_signature != signature) {
×
177
         for(std::unique_ptr<Botan::PK_Verifier>& verifier : verifiers) {
×
178
            if(!result.test_eq(
×
179
                  "generated signature valid", verifier->verify_message(message, generated_signature), true)) {
×
180
               result.test_failure("generated signature", generated_signature);
×
181
            }
182
         }
183
      }
184
   }
6,285✔
185

186
   return result;
1,257✔
187
}
6,285✔
188

189
Botan::Signature_Format PK_Signature_Verification_Test::sig_format() const {
4,864✔
190
   return Botan::Signature_Format::Standard;
4,864✔
191
}
192

193
Test::Result PK_Signature_Verification_Test::run_one_test(const std::string& pad_hdr, const VarMap& vars) {
13,080✔
194
   const std::vector<uint8_t> message = vars.get_req_bin("Msg");
13,080✔
195
   const std::vector<uint8_t> signature = vars.get_req_bin("Signature");
13,080✔
196
   const std::string padding = choose_padding(vars, pad_hdr);
13,080✔
197

198
   const bool expected_valid = (vars.get_opt_sz("Valid", 1) == 1);
13,080✔
199

200
   auto pubkey = load_public_key(vars);
13,080✔
201

202
   std::ostringstream result_name;
13,080✔
203
   result_name << algo_name();
26,160✔
204
   if(vars.has_key("Group")) {
26,160✔
205
      result_name << "-" << vars.get_req_str("Group");
24,260✔
206
   }
207
   if(!padding.empty()) {
13,080✔
208
      result_name << "/" << padding;
13,073✔
209
   }
210
   result_name << " signature verification";
13,080✔
211
   Test::Result result(result_name.str());
13,080✔
212

213
   result.confirm("public key claims to support signatures",
26,160✔
214
                  pubkey->supports_operation(Botan::PublicKeyOperation::Signature));
13,080✔
215

216
   for(const auto& verify_provider : possible_providers(algo_name())) {
78,480✔
217
      std::unique_ptr<Botan::PK_Verifier> verifier;
52,320✔
218

219
      try {
52,320✔
220
         verifier = std::make_unique<Botan::PK_Verifier>(*pubkey, padding, sig_format(), verify_provider);
61,150✔
221
      } catch(Botan::Lookup_Error&) {
43,490✔
222
         //result.test_note("Skipping verifying with " + verify_provider);
223
      }
43,490✔
224

225
      if(verifier) {
52,320✔
226
         try {
8,830✔
227
            const bool verified = verifier->verify_message(message, signature);
8,830✔
228

229
            if(expected_valid) {
8,830✔
230
               result.test_eq("correct signature valid with " + verify_provider, verified, true);
4,514✔
231

232
               if(test_random_invalid_sigs()) {
4,514✔
233
                  check_invalid_signatures(result, *verifier, message, signature, this->rng());
1,039✔
234
               }
235
            } else {
236
               result.confirm("incorrect signature is rejected", verified == false);
8,632✔
237
            }
238
         } catch(std::exception& e) {
×
239
            result.test_failure("verification threw exception", e.what());
×
240
         }
×
241
      }
242
   }
65,400✔
243

244
   return result;
26,160✔
245
}
52,320✔
246

247
Test::Result PK_Signature_NonVerification_Test::run_one_test(const std::string& pad_hdr, const VarMap& vars) {
706✔
248
   const std::string padding = choose_padding(vars, pad_hdr);
706✔
249
   const std::vector<uint8_t> message = vars.get_req_bin("Msg");
706✔
250
   auto pubkey = load_public_key(vars);
706✔
251

252
   const std::vector<uint8_t> invalid_signature = vars.get_req_bin("InvalidSignature");
706✔
253

254
   Test::Result result(algo_name() + "/" + padding + " verify invalid signature");
3,530✔
255

256
   for(const auto& verify_provider : possible_providers(algo_name())) {
4,236✔
257
      std::unique_ptr<Botan::PK_Verifier> verifier;
2,824✔
258

259
      try {
2,824✔
260
         verifier =
2,824✔
261
            std::make_unique<Botan::PK_Verifier>(*pubkey, padding, Botan::Signature_Format::Standard, verify_provider);
3,530✔
262
         result.test_eq("incorrect signature rejected", verifier->verify_message(message, invalid_signature), false);
1,412✔
263
      } catch(Botan::Lookup_Error&) {
2,118✔
264
         result.test_note("Skipping verifying with " + verify_provider);
2,118✔
265
      }
2,118✔
266
   }
3,530✔
267

268
   return result;
706✔
269
}
2,118✔
270

271
std::vector<Test::Result> PK_Sign_Verify_DER_Test::run() {
1✔
272
   const std::vector<uint8_t> message = {'f', 'o', 'o', 'b', 'a', 'r'};
1✔
273
   const std::string padding = m_padding;
1✔
274

275
   auto privkey = key();
1✔
276
   if(!privkey) {
1✔
277
      return {};
×
278
   }
279
   auto pubkey = privkey->public_key();
1✔
280

281
   Test::Result result(algo_name() + "/" + padding + " signature sign/verify using DER format");
5✔
282

283
   for(const auto& provider : possible_providers(algo_name())) {
3✔
284
      std::unique_ptr<Botan::PK_Signer> signer;
1✔
285
      std::unique_ptr<Botan::PK_Verifier> verifier;
1✔
286

287
      try {
1✔
288
         signer = std::make_unique<Botan::PK_Signer>(
1✔
289
            *privkey, this->rng(), padding, Botan::Signature_Format::DerSequence, provider);
2✔
290
         verifier =
1✔
291
            std::make_unique<Botan::PK_Verifier>(*pubkey, padding, Botan::Signature_Format::DerSequence, provider);
2✔
292
      } catch(Botan::Lookup_Error& e) {
×
293
         result.test_note("Skipping sign/verify with " + provider, e.what());
×
294
      }
×
295

296
      if(signer && verifier) {
1✔
297
         try {
1✔
298
            std::vector<uint8_t> generated_signature = signer->sign_message(message, this->rng());
1✔
299
            const bool verified = verifier->verify_message(message, generated_signature);
1✔
300

301
            result.test_eq("correct signature valid with " + provider, verified, true);
1✔
302

303
            if(test_random_invalid_sigs()) {
1✔
304
               check_invalid_signatures(result, *verifier, message, generated_signature, this->rng());
1✔
305
            }
306
         } catch(std::exception& e) {
1✔
307
            result.test_failure("verification threw exception", e.what());
×
308
         }
×
309
      }
310
   }
2✔
311

312
   // Below follows a regression test for a bug introduced in #4592 that caused
313
   // an assertion in PK_Signer when setting the output format explicitly using
314
   // signer.set_output_format(Signature_Format::DerSequence)
315
   try {
1✔
316
      auto signer = Botan::PK_Signer(*privkey, this->rng(), padding /*, not setting DerSequence here */);
1✔
317
      auto verifier = Botan::PK_Verifier(*pubkey, padding /*, not setting DerSequence here */);
1✔
318

319
      // Setting the in/out formats explicitly, to ensure that PK_Signer/Verifier
320
      // handle their internal state properly and not run into an assertion.
321
      signer.set_output_format(Botan::Signature_Format::DerSequence);
1✔
322
      verifier.set_input_format(Botan::Signature_Format::DerSequence);
1✔
323

324
      const auto sig = signer.sign_message(message, this->rng());
1✔
325
      const auto verified = verifier.verify_message(message, sig);
1✔
326

327
      result.confirm("signature checks out", verified);
2✔
328
      if(test_random_invalid_sigs()) {
1✔
329
         check_invalid_signatures(result, verifier, message, sig, this->rng());
1✔
330
      }
331
   } catch(const Botan::Lookup_Error&) {
1✔
332
      result.test_note("Skipping sign/verify regression test");
×
333
   } catch(const std::exception& e) {
×
334
      result.test_failure("regresstion test verification failed", e.what());
×
335
   }
×
336

337
   return {result};
2✔
338
}
5✔
339

340
std::vector<std::string> PK_Sign_Verify_DER_Test::possible_providers(const std::string& algo) {
1✔
341
   std::vector<std::string> pk_provider =
1✔
342
      Botan::probe_provider_private_key(algo, {"base", "commoncrypto", "openssl", "tpm"});
1✔
343
   return Test::provider_filter(pk_provider);
2✔
344
}
1✔
345

346
Test::Result PK_Encryption_Decryption_Test::run_one_test(const std::string& pad_hdr, const VarMap& vars) {
199✔
347
   const std::vector<uint8_t> plaintext = vars.get_req_bin("Msg");
199✔
348
   const std::vector<uint8_t> ciphertext = vars.get_req_bin("Ciphertext");
199✔
349
   const std::string padding = choose_padding(vars, pad_hdr);
199✔
350

351
   Test::Result result(algo_name() + (padding.empty() ? padding : "/" + padding) + " encryption");
796✔
352

353
   auto privkey = load_private_key(vars);
199✔
354

355
   result.confirm("private key claims to support encryption",
398✔
356
                  privkey->supports_operation(Botan::PublicKeyOperation::Encryption));
199✔
357

358
   auto pubkey = privkey->public_key();
199✔
359

360
   std::vector<std::unique_ptr<Botan::PK_Decryptor>> decryptors;
199✔
361

362
   for(const auto& dec_provider : possible_providers(algo_name())) {
1,194✔
363
      std::unique_ptr<Botan::PK_Decryptor> decryptor;
796✔
364

365
      try {
796✔
366
         decryptor = std::make_unique<Botan::PK_Decryptor_EME>(*privkey, this->rng(), padding, dec_provider);
796✔
367
      } catch(Botan::Lookup_Error&) {
597✔
368
         continue;
597✔
369
      }
597✔
370

371
      Botan::secure_vector<uint8_t> decrypted;
199✔
372
      try {
199✔
373
         decrypted = decryptor->decrypt(ciphertext);
199✔
374

375
         result.test_lte("Plaintext within length", decrypted.size(), decryptor->plaintext_length(ciphertext.size()));
398✔
376
      } catch(Botan::Exception& e) {
×
377
         result.test_failure("Failed to decrypt KAT ciphertext", e.what());
×
378
      }
×
379

380
      result.test_eq(dec_provider, "decryption of KAT", decrypted, plaintext);
398✔
381
      check_invalid_ciphertexts(result, *decryptor, plaintext, ciphertext, this->rng());
199✔
382
   }
995✔
383

384
   for(const auto& enc_provider : possible_providers(algo_name())) {
1,194✔
385
      std::unique_ptr<Botan::PK_Encryptor> encryptor;
796✔
386

387
      try {
796✔
388
         encryptor = std::make_unique<Botan::PK_Encryptor_EME>(*pubkey, this->rng(), padding, enc_provider);
796✔
389
      } catch(Botan::Lookup_Error&) {
597✔
390
         continue;
597✔
391
      }
597✔
392

393
      std::unique_ptr<Botan::RandomNumberGenerator> kat_rng;
199✔
394
      if(vars.has_key("Nonce")) {
398✔
395
         kat_rng = test_rng(vars.get_req_bin("Nonce"));
118✔
396
      }
397

398
      if(padding == "Raw") {
199✔
399
         /*
400
         Hack for RSA with no padding since sometimes one more bit will fit in but maximum_input_size
401
         rounds down to nearest byte
402
         */
403
         result.test_lte("Input within accepted bounds", plaintext.size(), encryptor->maximum_input_size() + 1);
292✔
404
      } else {
405
         result.test_lte("Input within accepted bounds", plaintext.size(), encryptor->maximum_input_size());
106✔
406
      }
407

408
      const std::vector<uint8_t> generated_ciphertext = encryptor->encrypt(plaintext, kat_rng ? *kat_rng : this->rng());
199✔
409

410
      result.test_lte(
199✔
411
         "Ciphertext within length", generated_ciphertext.size(), encryptor->ciphertext_length(plaintext.size()));
199✔
412

413
      if(enc_provider == "base") {
199✔
414
         result.test_eq(enc_provider, "generated ciphertext matches KAT", generated_ciphertext, ciphertext);
398✔
415
      } else if(generated_ciphertext != ciphertext) {
×
416
         for(std::unique_ptr<Botan::PK_Decryptor>& dec : decryptors) {
×
417
            result.test_eq("decryption of generated ciphertext", dec->decrypt(generated_ciphertext), plaintext);
×
418
         }
419
      }
420
   }
1,054✔
421

422
   return result;
398✔
423
}
995✔
424

425
Test::Result PK_Decryption_Test::run_one_test(const std::string& pad_hdr, const VarMap& vars) {
42✔
426
   const std::vector<uint8_t> plaintext = vars.get_req_bin("Msg");
42✔
427
   const std::vector<uint8_t> ciphertext = vars.get_req_bin("Ciphertext");
42✔
428
   const std::string padding = choose_padding(vars, pad_hdr);
42✔
429

430
   Test::Result result(algo_name() + (padding.empty() ? padding : "/" + padding) + " decryption");
168✔
431

432
   auto privkey = load_private_key(vars);
42✔
433

434
   for(const auto& dec_provider : possible_providers(algo_name())) {
252✔
435
      std::unique_ptr<Botan::PK_Decryptor> decryptor;
168✔
436

437
      try {
168✔
438
         decryptor = std::make_unique<Botan::PK_Decryptor_EME>(*privkey, this->rng(), padding, dec_provider);
168✔
439
      } catch(Botan::Lookup_Error&) {
126✔
440
         continue;
126✔
441
      }
126✔
442

443
      Botan::secure_vector<uint8_t> decrypted;
42✔
444
      try {
42✔
445
         decrypted = decryptor->decrypt(ciphertext);
42✔
446
      } catch(Botan::Exception& e) {
×
447
         result.test_failure("Failed to decrypt KAT ciphertext", e.what());
×
448
      }
×
449

450
      result.test_eq(dec_provider, "decryption of KAT", decrypted, plaintext);
84✔
451
      check_invalid_ciphertexts(result, *decryptor, plaintext, ciphertext, this->rng());
42✔
452
   }
210✔
453

454
   return result;
42✔
455
}
126✔
456

457
Test::Result PK_KEM_Test::run_one_test(const std::string& /*header*/, const VarMap& vars) {
10✔
458
   const std::vector<uint8_t> K = vars.get_req_bin("K");
10✔
459
   const std::vector<uint8_t> C0 = vars.get_req_bin("C0");
10✔
460
   const std::vector<uint8_t> salt = vars.get_opt_bin("Salt");
10✔
461
   const std::string kdf = vars.get_req_str("KDF");
10✔
462

463
   Test::Result result(algo_name() + "/" + kdf + " KEM");
50✔
464

465
   auto privkey = load_private_key(vars);
10✔
466

467
   result.confirm("private key claims to support KEM",
20✔
468
                  privkey->supports_operation(Botan::PublicKeyOperation::KeyEncapsulation));
10✔
469

470
   auto pubkey = privkey->public_key();
10✔
471

472
   const size_t desired_key_len = K.size();
10✔
473

474
   std::unique_ptr<Botan::PK_KEM_Encryptor> enc;
10✔
475
   try {
10✔
476
      enc = std::make_unique<Botan::PK_KEM_Encryptor>(*pubkey, kdf);
20✔
477
   } catch(Botan::Lookup_Error&) {
×
478
      result.test_note("Skipping due to missing KDF: " + kdf);
×
479
      return result;
×
480
   }
×
481

482
   Fixed_Output_RNG fixed_output_rng(vars.get_req_bin("R"));
20✔
483

484
   const auto kem_result = enc->encrypt(fixed_output_rng, desired_key_len, salt);
10✔
485

486
   result.test_eq("encapsulated key length matches expected",
20✔
487
                  kem_result.encapsulated_shared_key().size(),
10✔
488
                  enc->encapsulated_key_length());
489

490
   result.test_eq(
20✔
491
      "shared key length matches expected", kem_result.shared_key().size(), enc->shared_key_length(desired_key_len));
10✔
492

493
   result.test_eq("C0 matches", kem_result.encapsulated_shared_key(), C0);
20✔
494
   result.test_eq("K matches", kem_result.shared_key(), K);
20✔
495

496
   std::unique_ptr<Botan::PK_KEM_Decryptor> dec;
10✔
497
   try {
10✔
498
      dec = std::make_unique<Botan::PK_KEM_Decryptor>(*privkey, this->rng(), kdf);
20✔
499
   } catch(Botan::Lookup_Error& e) {
×
500
      result.test_note("Skipping test", e.what());
×
501
      return result;
×
502
   }
×
503

504
   result.test_eq("encapsulated key length matches expected",
20✔
505
                  kem_result.encapsulated_shared_key().size(),
10✔
506
                  dec->encapsulated_key_length());
507

508
   const Botan::secure_vector<uint8_t> decr_shared_key =
10✔
509
      dec->decrypt(C0.data(), C0.size(), desired_key_len, salt.data(), salt.size());
10✔
510

511
   result.test_eq(
10✔
512
      "shared key length matches expected", decr_shared_key.size(), dec->shared_key_length(desired_key_len));
513

514
   result.test_eq("decrypted K matches", decr_shared_key, K);
20✔
515

516
   return result;
10✔
517
}
50✔
518

519
Test::Result PK_Key_Agreement_Test::run_one_test(const std::string& header, const VarMap& vars) {
784✔
520
   const std::vector<uint8_t> shared = vars.get_req_bin("K");
784✔
521
   const std::string kdf = vars.get_opt_str("KDF", default_kdf(vars));
1,568✔
522

523
   Test::Result result(algo_name() + "/" + kdf + (header.empty() ? header : " " + header) + " key agreement");
5,292✔
524

525
   auto privkey = load_our_key(header, vars);
784✔
526

527
   result.confirm("private key claims to support key agreement",
1,568✔
528
                  privkey->supports_operation(Botan::PublicKeyOperation::KeyAgreement));
784✔
529

530
   const std::vector<uint8_t> pubkey = load_their_key(header, vars);
784✔
531

532
   const size_t key_len = vars.get_opt_sz("OutLen", 0);
784✔
533

534
   for(const auto& provider : possible_providers(algo_name())) {
4,704✔
535
      std::unique_ptr<Botan::PK_Key_Agreement> kas;
3,136✔
536

537
      try {
3,136✔
538
         kas = std::make_unique<Botan::PK_Key_Agreement>(*privkey, this->rng(), kdf, provider);
3,920✔
539

540
         if(agreement_should_fail(header, vars)) {
784✔
541
            result.test_throws("key agreement fails", [&] { kas->derive_key(key_len, pubkey); });
100✔
542
         } else {
543
            auto derived_key = kas->derive_key(key_len, pubkey).bits_of();
1,518✔
544
            result.test_eq(provider, "agreement", derived_key, shared);
1,518✔
545

546
            if(key_len == 0 && kdf == "Raw") {
759✔
547
               result.test_eq("Expected size", derived_key.size(), kas->agreed_value_size());
1,510✔
548
            }
549
         }
759✔
550
      } catch(Botan::Lookup_Error&) {
2,352✔
551
         //result.test_note("Skipping key agreement with with " + provider);
552
      }
2,352✔
553
   }
3,920✔
554

555
   return result;
784✔
556
}
2,352✔
557

558
std::vector<std::string> PK_Key_Generation_Test::possible_providers(const std::string& algo) {
111✔
559
   std::vector<std::string> pk_provider =
111✔
560
      Botan::probe_provider_private_key(algo, {"base", "commoncrypto", "openssl", "tpm"});
111✔
561
   return Test::provider_filter(pk_provider);
222✔
562
}
111✔
563

564
namespace {
565

566
   #if defined(BOTAN_HAS_PKCS5_PBES2) && defined(BOTAN_HAS_AES) && \
567
      (defined(BOTAN_HAS_SHA2_32) || defined(BOTAN_HAS_SCRYPT))
568
void test_pbe_roundtrip(Test::Result& result,
222✔
569
                        const Botan::Private_Key& key,
570
                        const std::string& pbe_algo,
571
                        Botan::RandomNumberGenerator& rng) {
572
   const auto pkcs8 = key.private_key_info();
222✔
573

574
   auto passphrase = Test::random_password(rng);
222✔
575

576
   try {
222✔
577
      Botan::DataSource_Memory data_src(
222✔
578
         Botan::PKCS8::PEM_encode(key, rng, passphrase, std::chrono::milliseconds(1), pbe_algo));
222✔
579

580
      auto loaded = Botan::PKCS8::load_key(data_src, passphrase);
222✔
581

582
      result.confirm("recovered private key from encrypted blob", loaded != nullptr);
444✔
583
      result.test_eq("reloaded key has same type", loaded->algo_name(), key.algo_name());
444✔
584
      result.test_eq("reloaded key has same encoding", loaded->private_key_info(), pkcs8);
666✔
585
   } catch(std::exception& e) {
444✔
586
      result.test_failure("roundtrip encrypted PEM private key", e.what());
×
587
   }
×
588

589
   try {
222✔
590
      Botan::DataSource_Memory data_src(
222✔
591
         Botan::PKCS8::BER_encode(key, rng, passphrase, std::chrono::milliseconds(1), pbe_algo));
444✔
592

593
      auto loaded = Botan::PKCS8::load_key(data_src, passphrase);
222✔
594

595
      result.confirm("recovered private key from BER blob", loaded != nullptr);
444✔
596
      result.test_eq("reloaded key has same type", loaded->algo_name(), key.algo_name());
444✔
597
      result.test_eq("reloaded key has same encoding", loaded->private_key_info(), pkcs8);
666✔
598
   } catch(std::exception& e) {
444✔
599
      result.test_failure("roundtrip encrypted BER private key", e.what());
×
600
   }
×
601
}
444✔
602
   #endif
603

604
}  // namespace
605

606
std::vector<Test::Result> PK_Key_Generation_Test::run() {
21✔
607
   std::vector<Test::Result> results;
21✔
608

609
   for(const auto& param : keygen_params()) {
132✔
610
      const auto algo = algo_name(param);
111✔
611
      const std::string report_name = Botan::fmt("{}{}", algo, (param.empty() ? param : " " + param));
115✔
612

613
      Test::Result result(report_name + " keygen");
111✔
614

615
      const std::vector<std::string> providers = possible_providers(algo);
111✔
616

617
      if(providers.empty()) {
111✔
618
         result.note_missing("provider key generation " + algo);
×
619
      }
620

621
      result.start_timer();
111✔
622
      for(auto&& prov : providers) {
222✔
623
         auto key_p = Botan::create_private_key(algo, this->rng(), param, prov);
111✔
624

625
         if(key_p == nullptr) {
111✔
626
            continue;
×
627
         }
628

629
         const Botan::Private_Key& key = *key_p;
111✔
630

631
         try {
111✔
632
            result.confirm("Key passes self tests", key.check_key(this->rng(), true));
222✔
633
         } catch(Botan::Lookup_Error&) {}
×
634

635
         const std::string name = key.algo_name();
111✔
636
         result.confirm("Key has a non-empty name", !name.empty());
222✔
637

638
         if(auto oid = Botan::OID::from_name(name)) {
111✔
639
            result.test_success("Keys name maps to an OID");
65✔
640

641
            result.test_eq("Keys name OID is the same as the object oid",
130✔
642
                           oid.value().to_string(),
130✔
643
                           key.object_identifier().to_string());
130✔
644
         } else {
645
            const bool exception = name == "Kyber" || name == "ML-KEM" || name == "ML-DSA" || name == "SLH-DSA" ||
40✔
646
                                   name == "FrodoKEM" || name == "SPHINCS+" || name == "ClassicMcEliece";
151✔
647
            if(!exception) {
×
648
               result.test_failure("Keys name " + name + " does not map to an OID");
×
649
            }
650
         }
×
651

652
         result.test_gte("Key has reasonable estimated strength (lower)", key.estimated_strength(), 64);
111✔
653
         result.test_lt("Key has reasonable estimated strength (upper)", key.estimated_strength(), 512);
111✔
654

655
         auto public_key = key.public_key();
111✔
656

657
         result.test_eq("public_key has same name", public_key->algo_name(), key.algo_name());
222✔
658

659
         result.test_eq(
333✔
660
            "public_key has same encoding", Botan::X509::PEM_encode(key), Botan::X509::PEM_encode(*public_key));
222✔
661

662
         // Test generation of another key pair from a given (abstract) asymmetric key
663
         // KEX algorithms must support that (so that we can generate ephemeral keys in
664
         // an abstract fashion). For other algorithms it's a nice-to-have.
665
         try {
111✔
666
            auto sk2 = public_key->generate_another(this->rng());
111✔
667
            auto pk2 = sk2->public_key();
110✔
668

669
            result.test_eq("new private key has the same name", sk2->algo_name(), key.algo_name());
220✔
670
            result.test_eq("new public key has the same name", pk2->algo_name(), public_key->algo_name());
220✔
671
            result.test_eq(
110✔
672
               "new private key has the same est. strength", sk2->estimated_strength(), key.estimated_strength());
110✔
673
            result.test_eq("new public key has the same est. strength",
110✔
674
                           pk2->estimated_strength(),
110✔
675
                           public_key->estimated_strength());
110✔
676
            result.test_ne("new private keys are different keys", sk2->private_key_bits(), key.private_key_bits());
440✔
677
         } catch(const Botan::Not_Implemented&) {
221✔
678
            result.confirm("KEX algorithms are required to implement 'generate_another'",
2✔
679
                           !public_key->supports_operation(Botan::PublicKeyOperation::KeyAgreement));
1✔
680
         }
1✔
681

682
         // Test that the raw public key can be encoded. This is not supported
683
         // by all algorithms; we expect Not_Implemented for these.
684
         const std::vector<std::string> algos_that_dont_have_a_raw_encoding = {"RSA"};
111✔
685
         try {
111✔
686
            auto raw = public_key->raw_public_key_bits();
111✔
687
            result.test_ne("raw_public_key_bits is not empty", raw.size(), 0);
109✔
688

689
            if(public_key->supports_operation(Botan::PublicKeyOperation::KeyAgreement)) {
109✔
690
               // For KEX algorithms, raw_public_key_bits must be equal to the canonical
691
               // public value obtained by PK_Key_Agreement_Key::public_value().
692
               const auto* ka_key = dynamic_cast<const Botan::PK_Key_Agreement_Key*>(&key);
10✔
693
               result.require("is a key agreement private key", ka_key != nullptr);
10✔
694
               result.test_eq("public_key_bits has same encoding", raw, ka_key->public_value());
30✔
695
            }
696

697
            if(auto raw_pk = public_key_from_raw(param, prov, raw)) {
109✔
698
               result.test_eq("public_key has same type", raw_pk->algo_name(), public_key->algo_name());
218✔
699
               result.test_eq("public_key has same encoding", raw_pk->public_key_bits(), public_key->public_key_bits());
436✔
700
            }
109✔
701
         } catch(const Botan::Not_Implemented&) {
111✔
702
            if(!Botan::value_exists(algos_that_dont_have_a_raw_encoding, public_key->algo_name())) {
2✔
703
               result.test_failure("raw_public_key_bits not implemented for " + public_key->algo_name());
×
704
            } else {
705
               result.test_note("raw_public_key_bits threw Not_Implemented as expected for " + public_key->algo_name());
6✔
706
            }
707
         }
2✔
708

709
         // Test PEM public key round trips OK
710
         try {
111✔
711
            Botan::DataSource_Memory data_src(Botan::X509::PEM_encode(*public_key));
111✔
712
            auto loaded = Botan::X509::load_key(data_src);
111✔
713

714
            result.confirm("recovered public key from private", loaded != nullptr);
222✔
715
            result.test_eq("public key has same type", loaded->algo_name(), key.algo_name());
222✔
716

717
            try {
111✔
718
               result.test_eq("public key passes checks", loaded->check_key(this->rng(), false), true);
222✔
719
            } catch(Botan::Lookup_Error&) {}
×
720
         } catch(std::exception& e) {
222✔
721
            result.test_failure("roundtrip PEM public key", e.what());
×
722
         }
×
723

724
         // Test DER public key round trips OK
725
         try {
111✔
726
            const auto ber = public_key->subject_public_key();
111✔
727
            Botan::DataSource_Memory data_src(ber);
111✔
728
            auto loaded = Botan::X509::load_key(data_src);
111✔
729

730
            result.confirm("recovered public key from private", loaded != nullptr);
222✔
731
            result.test_eq("public key has same type", loaded->algo_name(), key.algo_name());
222✔
732
            result.test_eq("public key has same encoding", loaded->subject_public_key(), ber);
333✔
733
         } catch(std::exception& e) {
333✔
734
            result.test_failure("roundtrip BER public key", e.what());
×
735
         }
×
736

737
         // Test PEM private key round trips OK
738
         try {
111✔
739
            const auto ber = key.private_key_info();
111✔
740
            Botan::DataSource_Memory data_src(ber);
111✔
741
            auto loaded = Botan::PKCS8::load_key(data_src);
111✔
742

743
            result.confirm("recovered private key from PEM blob", loaded != nullptr);
222✔
744
            result.test_eq("reloaded key has same type", loaded->algo_name(), key.algo_name());
222✔
745
            result.test_eq("reloaded key has same encoding", loaded->private_key_info(), ber);
333✔
746
         } catch(std::exception& e) {
333✔
747
            result.test_failure("roundtrip PEM private key", e.what());
×
748
         }
×
749

750
         try {
111✔
751
            Botan::DataSource_Memory data_src(Botan::PKCS8::BER_encode(key));
111✔
752
            auto loaded = Botan::PKCS8::load_key(data_src);
111✔
753

754
            result.confirm("recovered public key from private", loaded != nullptr);
222✔
755
            result.test_eq("public key has same type", loaded->algo_name(), key.algo_name());
222✔
756
         } catch(std::exception& e) {
222✔
757
            result.test_failure("roundtrip BER private key", e.what());
×
758
         }
×
759

760
   #if defined(BOTAN_HAS_PKCS5_PBES2) && defined(BOTAN_HAS_AES) && defined(BOTAN_HAS_SHA2_32)
761

762
         test_pbe_roundtrip(result, key, "PBE-PKCS5v20(AES-128/CBC,SHA-256)", this->rng());
111✔
763
   #endif
764

765
   #if defined(BOTAN_HAS_PKCS5_PBES2) && defined(BOTAN_HAS_AES) && defined(BOTAN_HAS_SCRYPT)
766

767
         test_pbe_roundtrip(result, key, "PBES2(AES-128/CBC,Scrypt)", this->rng());
111✔
768
   #endif
769
      }
333✔
770

771
      result.end_timer();
111✔
772

773
      results.push_back(result);
111✔
774
   }
132✔
775

776
   return results;
21✔
777
}
×
778

779
Test::Result PK_Key_Validity_Test::run_one_test(const std::string& header, const VarMap& vars) {
9✔
780
   Test::Result result(algo_name() + " key validity");
18✔
781

782
   if(header != "Valid" && header != "Invalid") {
9✔
783
      throw Test_Error("Unexpected header for PK_Key_Validity_Test");
×
784
   }
785

786
   const bool expected_valid = (header == "Valid");
9✔
787
   auto pubkey = load_public_key(vars);
9✔
788

789
   const bool tested_valid = pubkey->check_key(this->rng(), true);
9✔
790

791
   result.test_eq("Expected validation result", expected_valid, tested_valid);
9✔
792

793
   return result;
9✔
794
}
9✔
795

796
PK_Key_Generation_Stability_Test::PK_Key_Generation_Stability_Test(const std::string& algo,
2✔
797
                                                                   const std::string& test_src) :
2✔
798
      PK_Test(algo, test_src, "Rng,RngSeed,Key", "KeyParams,RngParams") {}
4✔
799

800
Test::Result PK_Key_Generation_Stability_Test::run_one_test(const std::string&, const VarMap& vars) {
3✔
801
   const std::string key_param = vars.get_opt_str("KeyParams", "");
6✔
802
   const std::string rng_algo = vars.get_req_str("Rng");
3✔
803
   const std::string rng_params = vars.get_opt_str("RngParams", "");
9✔
804
   const std::vector<uint8_t> rng_seed = vars.get_req_bin("RngSeed");
3✔
805
   const std::vector<uint8_t> expected_key = vars.get_req_bin("Key");
3✔
806

807
   std::ostringstream report_name;
3✔
808

809
   report_name << algo_name();
6✔
810
   if(!key_param.empty()) {
3✔
811
      report_name << " " << key_param;
3✔
812
   }
813
   report_name << " keygen stability";
3✔
814

815
   Test::Result result(report_name.str());
3✔
816

817
   result.start_timer();
3✔
818

819
   std::unique_ptr<Botan::RandomNumberGenerator> rng;
3✔
820

821
   #if defined(BOTAN_HAS_HMAC_DRBG)
822
   if(rng_algo == "HMAC_DRBG") {
3✔
823
      rng = std::make_unique<Botan::HMAC_DRBG>(rng_params);
1✔
824
   }
825
   #endif
826

827
   if(rng_algo == "Fixed") {
3✔
828
      if(!rng_params.empty()) {
2✔
829
         throw Test_Error("Expected empty RngParams for Fixed RNG");
×
830
      }
831
      rng = std::make_unique<Fixed_Output_RNG>();
4✔
832
   }
833

834
   if(rng) {
3✔
835
      rng->add_entropy(rng_seed.data(), rng_seed.size());
3✔
836

837
      try {
3✔
838
         auto key = Botan::create_private_key(algo_name(), *rng, key_param);
6✔
839
         if(key) {
3✔
840
            const auto key_bits = key->private_key_info();
3✔
841
            result.test_eq("Generated key matched expected value", key_bits, expected_key);
6✔
842
         }
3✔
843
      } catch(Botan::Exception& e) {
3✔
844
         result.test_note("failed to create key", e.what());
×
845
      }
×
846
   } else {
847
      result.test_note("Skipping test due to unavailable RNG");
×
848
   }
849

850
   result.end_timer();
3✔
851

852
   return result;
3✔
853
}
9✔
854

855
/**
856
 * @brief Some general tests for minimal API sanity for signing/verification.
857
 */
858
class PK_API_Sign_Test : public Text_Based_Test {
859
   public:
860
      PK_API_Sign_Test() : Text_Based_Test("pubkey/api_sign.vec", "AlgoParams,SigParams", "Provider") {}
2✔
861

862
   protected:
863
      Test::Result run_one_test(const std::string& algorithm, const VarMap& vars) final {
14✔
864
         const std::string algo_params = vars.get_req_str("AlgoParams");
14✔
865
         const std::string sig_params = vars.get_req_str("SigParams");
14✔
866
         const std::string verify_params = vars.get_opt_str("VerifyParams", sig_params);
14✔
867
         const std::string provider = vars.get_opt_str("Provider", "base");
28✔
868

869
         std::ostringstream test_name;
14✔
870
         test_name << "Sign/verify API tests " << algorithm;
14✔
871
         if(!algo_params.empty()) {
14✔
872
            test_name << '(' << algo_params << ')';
12✔
873
         }
874
         if(!sig_params.empty()) {
14✔
875
            test_name << '/' << sig_params;
11✔
876
         }
877
         Test::Result result(test_name.str());
14✔
878

879
         auto privkey = [&]() -> std::unique_ptr<Botan::Private_Key> {
42✔
880
            try {
14✔
881
               return Botan::create_private_key(algorithm, this->rng(), algo_params, provider);
14✔
882
            } catch(Botan::Not_Implemented&) {}
×
883

884
            return nullptr;
×
885
         }();
14✔
886

887
         if(!privkey) {
14✔
888
            result.test_note(Botan::fmt(
×
889
               "Skipping Sign/verify API tests for {}({}) with provider {}", algorithm, algo_params, provider));
890
            return result;
×
891
         }
892

893
         auto pubkey = Botan::X509::load_key(Botan::X509::BER_encode(*privkey->public_key()));
28✔
894
         result.confirm("Storing and loading public key works", pubkey != nullptr);
28✔
895

896
         result.confirm("private key claims to support signatures",
28✔
897
                        privkey->supports_operation(Botan::PublicKeyOperation::Signature));
14✔
898
         result.confirm("public key claims to support signatures",
28✔
899
                        pubkey->supports_operation(Botan::PublicKeyOperation::Signature));
14✔
900
         result.test_gt("Public key length must be greater than 0", pubkey->key_length(), 0);
14✔
901
         if(privkey->stateful_operation()) {
14✔
902
            result.confirm("A stateful key reports the number of remaining operations",
4✔
903
                           privkey->remaining_operations().has_value());
4✔
904
         } else {
905
            result.confirm("A stateless key has an unlimited number of remaining operations",
24✔
906
                           !privkey->remaining_operations().has_value());
24✔
907
         }
908

909
         auto signer = std::make_unique<Botan::PK_Signer>(
14✔
910
            *privkey, this->rng(), sig_params, Botan::Signature_Format::Standard, provider);
14✔
911
         auto verifier =
14✔
912
            std::make_unique<Botan::PK_Verifier>(*pubkey, verify_params, Botan::Signature_Format::Standard, provider);
14✔
913
         result.confirm("Creating PK_Signer works", signer != nullptr);
28✔
914
         result.confirm("Creating PK_Signer works", verifier != nullptr);
28✔
915

916
         result.test_is_nonempty("PK_Signer should report some hash", signer->hash_function());
28✔
917
         result.test_is_nonempty("PK_Verifier should report some hash", verifier->hash_function());
28✔
918

919
         result.test_eq(
42✔
920
            "PK_Signer and PK_Verifier report the same hash", signer->hash_function(), verifier->hash_function());
28✔
921

922
         pubkey.reset();
14✔
923
         privkey.reset();
14✔
924
         const std::array<uint8_t, 4> msg{0xde, 0xad, 0xbe, 0xef};
14✔
925
         const auto sig = signer->sign_message(msg, this->rng());
14✔
926
         result.test_gt("Signer should still work if no one else hold a reference to the key", sig.size(), 0);
14✔
927
         result.test_eq("Verifier should still work if no one else hold a reference to the key",
28✔
928
                        verifier->verify_message(msg, sig),
14✔
929
                        true);
930

931
         return result;
14✔
932
      }
28✔
933

934
      bool skip_this_test([[maybe_unused]] const std::string& header, const VarMap&) override {
14✔
935
   #if !defined(BOTAN_HAS_SLH_DSA_WITH_SHA2)
936
         if(header == "SLH-DSA") {
937
            return true;
938
         }
939
   #endif
940
         return false;
14✔
941
      }
942
};
943

944
BOTAN_REGISTER_TEST("pubkey", "pk_api_sign", PK_API_Sign_Test);
945

946
/**
947
 * @brief Testing PK key decoding
948
 */
949
class PK_Key_Decoding_Test : public Text_Based_Test {
950
   public:
951
      PK_Key_Decoding_Test() : Text_Based_Test("pubkey/key_encoding.vec", "Key") {}
2✔
952

953
   protected:
954
      Test::Result run_one_test(const std::string&, const VarMap& vars) final {
1✔
955
         const auto key = vars.get_req_bin("Key");
1✔
956

957
         Test::Result result("PK Key Decoding");
1✔
958

959
         try {
1✔
960
            auto k = Botan::PKCS8::load_key(key);
1✔
961
            result.test_success("Was able to deserialize the key");
2✔
962
         } catch(Botan::Not_Implemented&) {
1✔
963
            result.test_note("Skipping test due to to algorithm being unavailable");
×
964
         } catch(Botan::Exception& e) {
×
965
            if(std::string(e.what()).starts_with("Unknown or unavailable public key algorithm")) {
×
966
               result.test_note("Skipping test due to to algorithm being unavailable");
×
967
            } else {
968
               result.test_failure("Failed to deserialize key", e.what());
×
969
            }
970
         }
×
971

972
         return result;
1✔
973
      }
1✔
974
};
975

976
BOTAN_REGISTER_TEST("pubkey", "pk_key_decoding", PK_Key_Decoding_Test);
977

978
}  // namespace Botan_Tests
979

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