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

randombit / botan / 16510618243

25 Jul 2025 12:16AM UTC coverage: 90.699% (+0.006%) from 90.693%
16510618243

Pull #4593

github

web-flow
Merge d70034dd9 into 72deba42e
Pull Request #4593: New interface for PKCS8 key encryption

99992 of 110246 relevant lines covered (90.7%)

12219641.55 hits per line

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

86.79
/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,300✔
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,300✔
39

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

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

46
      try {
46,000✔
47
         if(!result.test_eq("incorrect signature invalid", verifier.verify_message(message, bad_sig), false)) {
46,000✔
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
   }
46,000✔
55
}
2,300✔
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;
317✔
68
   size_t ciphertext_rejected = 0;
317✔
69

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

201
   auto pubkey = load_public_key(vars);
13,082✔
202

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

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

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

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

226
      if(verifier) {
52,328✔
227
         try {
8,832✔
228
            const bool verified = verifier->verify_message(message, signature);
8,832✔
229

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

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

245
   return result;
26,164✔
246
}
52,328✔
247

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

381
      result.test_eq(dec_provider, "decryption of KAT", decrypted, plaintext);
398✔
382
      check_invalid_ciphertexts(result, *decryptor, plaintext, ciphertext, this->rng());
199✔
383
      decryptors.push_back(std::move(decryptor));
199✔
384
   }
995✔
385

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

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

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

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

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

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

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

424
   return result;
398✔
425
}
995✔
426

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

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

434
   auto privkey = load_private_key(vars);
42✔
435

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

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

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

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

456
   return result;
42✔
457
}
126✔
458

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

465
   Test::Result result(algo_name() + "/" + kdf + " KEM");
50✔
466

467
   auto privkey = load_private_key(vars);
10✔
468

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

472
   auto pubkey = privkey->public_key();
10✔
473

474
   const size_t desired_key_len = K.size();
10✔
475

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

484
   Fixed_Output_RNG fixed_output_rng(vars.get_req_bin("R"));
20✔
485

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

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

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

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

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

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

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

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

516
   result.test_eq("decrypted K matches", decr_shared_key, K);
20✔
517

518
   return result;
10✔
519
}
50✔
520

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

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

527
   auto privkey = load_our_key(header, vars);
784✔
528

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

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

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

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

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

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

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

557
   return result;
784✔
558
}
2,352✔
559

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

566
namespace {
567

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

577
   auto passphrase = Test::random_password(rng);
222✔
578

579
   auto options = Botan::PKCS8::KeyEncryptionOptions(cipher, pwhash, std::chrono::milliseconds(1));
222✔
580

581
   auto pkcs8 = Botan::PKCS8::encrypt_private_key(key, passphrase, rng, options);
222✔
582

583
   try {
222✔
584
      Botan::DataSource_Memory data_src(pkcs8.as_pem());
222✔
585

586
      auto loaded = Botan::PKCS8::load_key(data_src, passphrase);
222✔
587

588
      result.confirm("recovered private key from encrypted blob", loaded != nullptr);
444✔
589
      result.test_eq("reloaded key has same type", loaded->algo_name(), key.algo_name());
444✔
590
      result.test_eq("reloaded key has same encoding", loaded->private_key_info(), raw_pkcs8);
666✔
591
   } catch(std::exception& e) {
444✔
592
      result.test_failure("roundtrip encrypted PEM private key", e.what());
×
593
   }
×
594

595
   try {
222✔
596
      Botan::DataSource_Memory data_src(pkcs8.as_bytes());
222✔
597

598
      auto loaded = Botan::PKCS8::load_key(data_src, passphrase);
222✔
599

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

609
}  // namespace
610

611
std::vector<Test::Result> PK_Key_Generation_Test::run() {
21✔
612
   std::vector<Test::Result> results;
21✔
613

614
   for(const auto& param : keygen_params()) {
132✔
615
      const auto algorithm_name = algo_name(param);
111✔
616
      const std::string report_name = Botan::fmt("{}{}", algorithm_name, (param.empty() ? param : " " + param));
115✔
617

618
      Test::Result result(report_name + " keygen");
111✔
619

620
      const std::vector<std::string> providers = possible_providers(algorithm_name);
111✔
621

622
      if(providers.empty()) {
111✔
623
         result.note_missing("provider key generation " + algorithm_name);
×
624
      }
625

626
      result.start_timer();
111✔
627
      for(auto&& prov : providers) {
222✔
628
         auto key_p = Botan::create_private_key(algorithm_name, this->rng(), param, prov);
111✔
629

630
         if(key_p == nullptr) {
111✔
631
            continue;
×
632
         }
633

634
         const Botan::Private_Key& key = *key_p;
111✔
635

636
         try {
111✔
637
            result.confirm("Key passes self tests", key.check_key(this->rng(), true));
222✔
638
         } catch(Botan::Lookup_Error&) {}
×
639

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

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

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

657
         result.test_gte("Key has reasonable estimated strength (lower)", key.estimated_strength(), 64);
111✔
658
         result.test_lt("Key has reasonable estimated strength (upper)", key.estimated_strength(), 512);
111✔
659

660
         auto public_key = key.public_key();
111✔
661

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

664
         result.test_eq(
333✔
665
            "public_key has same encoding", Botan::X509::PEM_encode(key), Botan::X509::PEM_encode(*public_key));
222✔
666

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

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

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

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

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

714
         // Test PEM public key round trips OK
715
         try {
111✔
716
            Botan::DataSource_Memory data_src(Botan::X509::PEM_encode(*public_key));
111✔
717
            auto loaded = Botan::X509::load_key(data_src);
111✔
718

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

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

729
         // Test DER public key round trips OK
730
         try {
111✔
731
            const auto ber = public_key->subject_public_key();
111✔
732
            Botan::DataSource_Memory data_src(ber);
111✔
733
            auto loaded = Botan::X509::load_key(data_src);
111✔
734

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

742
         // Test PEM private key round trips OK
743
         try {
111✔
744
            const auto ber = key.private_key_info();
111✔
745
            Botan::DataSource_Memory data_src(ber);
111✔
746
            auto loaded = Botan::PKCS8::load_key(data_src);
111✔
747

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

755
         try {
111✔
756
            Botan::DataSource_Memory data_src(Botan::PKCS8::BER_encode(key));
111✔
757
            auto loaded = Botan::PKCS8::load_key(data_src);
111✔
758

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

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

767
         test_pbe_roundtrip(result, key, "AES-128/CBC", "SHA-256", this->rng());
222✔
768
   #endif
769

770
   #if defined(BOTAN_HAS_PKCS5_PBES2) && defined(BOTAN_HAS_AES) && defined(BOTAN_HAS_SCRYPT)
771

772
         test_pbe_roundtrip(result, key, "AES-128/CBC", "Scrypt", this->rng());
222✔
773
   #endif
774
      }
333✔
775

776
      result.end_timer();
111✔
777

778
      results.push_back(result);
111✔
779
   }
132✔
780

781
   return results;
21✔
782
}
×
783

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

787
   if(header != "Valid" && header != "Invalid") {
9✔
788
      throw Test_Error("Unexpected header for PK_Key_Validity_Test");
×
789
   }
790

791
   const bool expected_valid = (header == "Valid");
9✔
792
   auto pubkey = load_public_key(vars);
9✔
793

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

796
   result.test_eq("Expected validation result", tested_valid, expected_valid);
9✔
797

798
   return result;
9✔
799
}
9✔
800

801
PK_Key_Generation_Stability_Test::PK_Key_Generation_Stability_Test(const std::string& algo,
2✔
802
                                                                   const std::string& test_src) :
2✔
803
      PK_Test(algo, test_src, "Rng,RngSeed,Key", "KeyParams,RngParams") {}
6✔
804

805
Test::Result PK_Key_Generation_Stability_Test::run_one_test(const std::string& /*header*/, const VarMap& vars) {
3✔
806
   const std::string key_param = vars.get_opt_str("KeyParams", "");
6✔
807
   const std::string rng_algo = vars.get_req_str("Rng");
3✔
808
   const std::string rng_params = vars.get_opt_str("RngParams", "");
6✔
809
   const std::vector<uint8_t> rng_seed = vars.get_req_bin("RngSeed");
3✔
810
   const std::vector<uint8_t> expected_key = vars.get_req_bin("Key");
3✔
811

812
   std::ostringstream report_name;
3✔
813

814
   report_name << algo_name();
6✔
815
   if(!key_param.empty()) {
3✔
816
      report_name << " " << key_param;
3✔
817
   }
818
   report_name << " keygen stability";
3✔
819

820
   Test::Result result(report_name.str());
3✔
821

822
   result.start_timer();
3✔
823

824
   std::unique_ptr<Botan::RandomNumberGenerator> rng;
3✔
825

826
   #if defined(BOTAN_HAS_HMAC_DRBG)
827
   if(rng_algo == "HMAC_DRBG") {
3✔
828
      rng = std::make_unique<Botan::HMAC_DRBG>(rng_params);
1✔
829
   }
830
   #endif
831

832
   if(rng_algo == "Fixed") {
3✔
833
      if(!rng_params.empty()) {
2✔
834
         throw Test_Error("Expected empty RngParams for Fixed RNG");
×
835
      }
836
      rng = std::make_unique<Fixed_Output_RNG>();
4✔
837
   }
838

839
   if(rng) {
3✔
840
      rng->add_entropy(rng_seed.data(), rng_seed.size());
3✔
841

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

855
   result.end_timer();
3✔
856

857
   return result;
3✔
858
}
9✔
859

860
/**
861
 * @brief Some general tests for minimal API sanity for signing/verification.
862
 */
863
class PK_API_Sign_Test : public Text_Based_Test {
864
   public:
865
      PK_API_Sign_Test() : Text_Based_Test("pubkey/api_sign.vec", "AlgoParams,SigParams", "Provider") {}
2✔
866

867
   protected:
868
      Test::Result run_one_test(const std::string& algorithm, const VarMap& vars) final {
14✔
869
         const std::string algo_params = vars.get_req_str("AlgoParams");
14✔
870
         const std::string sig_params = vars.get_req_str("SigParams");
14✔
871
         const std::string verify_params = vars.get_opt_str("VerifyParams", sig_params);
14✔
872
         const std::string provider = vars.get_opt_str("Provider", "base");
28✔
873

874
         std::ostringstream test_name;
14✔
875
         test_name << "Sign/verify API tests " << algorithm;
14✔
876
         if(!algo_params.empty()) {
14✔
877
            test_name << '(' << algo_params << ')';
12✔
878
         }
879
         if(!sig_params.empty()) {
14✔
880
            test_name << '/' << sig_params;
11✔
881
         }
882
         Test::Result result(test_name.str());
14✔
883

884
         auto privkey = [&]() -> std::unique_ptr<Botan::Private_Key> {
42✔
885
            try {
14✔
886
               return Botan::create_private_key(algorithm, this->rng(), algo_params, provider);
14✔
887
            } catch(Botan::Not_Implemented&) {}
×
888

889
            return nullptr;
×
890
         }();
14✔
891

892
         if(!privkey) {
14✔
893
            result.test_note(Botan::fmt(
×
894
               "Skipping Sign/verify API tests for {}({}) with provider {}", algorithm, algo_params, provider));
895
            return result;
×
896
         }
897

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

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

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

921
         result.test_is_nonempty("PK_Signer should report some hash", signer->hash_function());
28✔
922
         result.test_is_nonempty("PK_Verifier should report some hash", verifier->hash_function());
28✔
923

924
         result.test_eq(
42✔
925
            "PK_Signer and PK_Verifier report the same hash", signer->hash_function(), verifier->hash_function());
28✔
926

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

936
         return result;
14✔
937
      }
28✔
938

939
      bool skip_this_test([[maybe_unused]] const std::string& header, const VarMap& /*vars*/) override {
14✔
940
   #if !defined(BOTAN_HAS_SLH_DSA_WITH_SHA2)
941
         if(header == "SLH-DSA") {
942
            return true;
943
         }
944
   #endif
945
         return false;
14✔
946
      }
947
};
948

949
BOTAN_REGISTER_TEST("pubkey", "pk_api_sign", PK_API_Sign_Test);
950

951
/**
952
 * @brief Testing PK key decoding
953
 */
954
class PK_Key_Decoding_Test : public Text_Based_Test {
955
   public:
956
      PK_Key_Decoding_Test() : Text_Based_Test("pubkey/key_encoding.vec", "Key") {}
2✔
957

958
   protected:
959
      Test::Result run_one_test(const std::string& /*header*/, const VarMap& vars) final {
1✔
960
         const auto key = vars.get_req_bin("Key");
1✔
961

962
         Test::Result result("PK Key Decoding");
1✔
963

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

977
         return result;
1✔
978
      }
1✔
979
};
980

981
BOTAN_REGISTER_TEST("pubkey", "pk_key_decoding", PK_Key_Decoding_Test);
982

983
}  // namespace Botan_Tests
984

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