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

randombit / botan / 16393801904

19 Jul 2025 11:30PM UTC coverage: 90.637% (-0.07%) from 90.708%
16393801904

push

github

web-flow
Merge pull request #4998 from randombit/jack/fix-clang-tidy-readability-isolate-declaration

Enable and fix clang-tidy warning readability-isolate-declaration

99942 of 110266 relevant lines covered (90.64%)

12231283.62 hits per line

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

88.89
/src/lib/pubkey/pkcs8.cpp
1
/*
2
* PKCS #8
3
* (C) 1999-2010,2014,2018 Jack Lloyd
4
*
5
* Botan is released under the Simplified BSD License (see license.txt)
6
*/
7

8
#include <botan/pkcs8.h>
9

10
#include <botan/asn1_obj.h>
11
#include <botan/assert.h>
12
#include <botan/ber_dec.h>
13
#include <botan/der_enc.h>
14
#include <botan/pem.h>
15
#include <botan/pk_algs.h>
16
#include <botan/rng.h>
17
#include <botan/internal/fmt.h>
18
#include <botan/internal/scan_name.h>
19

20
#if defined(BOTAN_HAS_PKCS5_PBES2)
21
   #include <botan/internal/pbes2.h>
22
#endif
23

24
namespace Botan::PKCS8 {
25

26
namespace {
27

28
/*
29
* Get info from an EncryptedPrivateKeyInfo
30
*/
31
secure_vector<uint8_t> PKCS8_extract(DataSource& source, AlgorithmIdentifier& pbe_alg_id) {
499✔
32
   secure_vector<uint8_t> key_data;
499✔
33

34
   BER_Decoder(source).start_sequence().decode(pbe_alg_id).decode(key_data, ASN1_Type::OctetString).verify_end();
998✔
35

36
   return key_data;
499✔
37
}
×
38

39
/*
40
* PEM decode and/or decrypt a private key
41
*/
42
secure_vector<uint8_t> PKCS8_decode(DataSource& source,
4,785✔
43
                                    const std::function<std::string()>& get_passphrase,
44
                                    AlgorithmIdentifier& pk_alg_id,
45
                                    bool is_encrypted) {
46
   AlgorithmIdentifier pbe_alg_id;
4,785✔
47
   secure_vector<uint8_t> key_data;
4,785✔
48
   secure_vector<uint8_t> key;
4,785✔
49

50
   try {
4,785✔
51
      if(ASN1::maybe_BER(source) && !PEM_Code::matches(source)) {
4,785✔
52
         if(is_encrypted) {
2,169✔
53
            key_data = PKCS8_extract(source, pbe_alg_id);
506✔
54
         } else {
55
            // todo read more efficiently
56
            while(auto b = source.read_byte()) {
1,204,504✔
57
               key_data.push_back(*b);
1,202,588✔
58
            }
1,202,588✔
59
         }
60
      } else {
61
         std::string label;
2,615✔
62
         key_data = PEM_Code::decode(source, label);
5,168✔
63

64
         // todo remove autodetect for pem as well?
65
         if(label == "PRIVATE KEY") {
2,553✔
66
            is_encrypted = false;
67
         } else if(label == "ENCRYPTED PRIVATE KEY") {
274✔
68
            DataSource_Memory key_source(key_data);
336✔
69
            key_data = PKCS8_extract(key_source, pbe_alg_id);
492✔
70
         } else {
246✔
71
            throw PKCS8_Exception(fmt("Unknown PEM label '{}'", label));
28✔
72
         }
73
      }
2,615✔
74

75
      if(key_data.empty()) {
4,694✔
76
         throw PKCS8_Exception("No key data found");
×
77
      }
78
   } catch(Decoding_Error& e) {
91✔
79
      throw Decoding_Error("PKCS #8 private key decoding", e);
83✔
80
   }
83✔
81

82
   try {
4,694✔
83
      if(is_encrypted) {
4,694✔
84
         if(pbe_alg_id.oid().to_formatted_string() != "PBE-PKCS5v20") {
499✔
85
            throw PKCS8_Exception(fmt("Unknown PBE type {}", pbe_alg_id.oid()));
×
86
         }
87

88
#if defined(BOTAN_HAS_PKCS5_PBES2)
89
         key = pbes2_decrypt(key_data, get_passphrase(), pbe_alg_id.parameters());
1,497✔
90
#else
91
         BOTAN_UNUSED(get_passphrase);
92
         throw Decoding_Error("Private key is encrypted but PBES2 was disabled in build");
93
#endif
94
      } else {
95
         key = key_data;
4,195✔
96
      }
97

98
      BER_Decoder(key)
9,388✔
99
         .start_sequence()
4,600✔
100
         .decode_and_check<size_t>(0, "Unknown PKCS #8 version number")
9,099✔
101
         .decode(pk_alg_id)
4,499✔
102
         .decode(key, ASN1_Type::OctetString)
4,359✔
103
         .discard_remaining()
4,359✔
104
         .end_cons();
4,359✔
105
   } catch(std::exception& e) {
335✔
106
      throw Decoding_Error("PKCS #8 private key decoding", e);
335✔
107
   }
335✔
108
   return key;
8,718✔
109
}
5,211✔
110

111
}  // namespace
112

113
/*
114
* PEM encode a PKCS #8 private key, unencrypted
115
*/
116
std::string PEM_encode(const Private_Key& key) {
61✔
117
   return PEM_Code::encode(key.private_key_info(), "PRIVATE KEY");
183✔
118
}
119

120
#if defined(BOTAN_HAS_PKCS5_PBES2)
121

122
namespace {
123

124
std::pair<std::string, std::string> choose_pbe_params(std::string_view pbe_algo, std::string_view key_algo) {
470✔
125
   if(pbe_algo.empty()) {
470✔
126
      /*
127
      * For algorithms where we are using a non-RFC format anyway, default to
128
      * SIV or GCM. For others (RSA, ECDSA, ...) default to something widely
129
      * compatible.
130
      */
131
      const bool nonstandard_pk = (key_algo == "McEliece" || key_algo == "XMSS");
26✔
132

133
      if(nonstandard_pk) {
26✔
134
   #if defined(BOTAN_HAS_AEAD_SIV) && defined(BOTAN_HAS_SHA2_64)
135
         return std::make_pair("AES-256/SIV", "SHA-512");
×
136
   #elif defined(BOTAN_HAS_AEAD_GCM) && defined(BOTAN_HAS_SHA2_64)
137
         return std::make_pair("AES-256/GCM", "SHA-512");
138
   #endif
139
      }
140

141
      // Default is something compatible with everyone else
142
      return std::make_pair("AES-256/CBC", "SHA-256");
26✔
143
   }
144

145
   SCAN_Name request(pbe_algo);
444✔
146

147
   if(request.arg_count() != 2 || (request.algo_name() != "PBE-PKCS5v20" && request.algo_name() != "PBES2")) {
444✔
148
      throw Invalid_Argument(fmt("Unsupported PBE '{}'", pbe_algo));
×
149
   }
150

151
   return std::make_pair(request.arg(0), request.arg(1));
888✔
152
}
444✔
153

154
}  // namespace
155

156
#endif
157

158
/*
159
* BER encode a PKCS #8 private key, encrypted
160
*/
161
std::vector<uint8_t> BER_encode(const Private_Key& key,
470✔
162
                                RandomNumberGenerator& rng,
163
                                std::string_view pass,
164
                                std::chrono::milliseconds msec,
165
                                std::string_view pbe_algo) {
166
#if defined(BOTAN_HAS_PKCS5_PBES2)
167
   const auto pbe_params = choose_pbe_params(pbe_algo, key.algo_name());
470✔
168

169
   const std::pair<AlgorithmIdentifier, std::vector<uint8_t>> pbe_info =
470✔
170
      pbes2_encrypt_msec(PKCS8::BER_encode(key), pass, msec, nullptr, pbe_params.first, pbe_params.second, rng);
470✔
171

172
   std::vector<uint8_t> output;
470✔
173
   DER_Encoder der(output);
470✔
174
   der.start_sequence().encode(pbe_info.first).encode(pbe_info.second, ASN1_Type::OctetString).end_cons();
470✔
175

176
   return output;
940✔
177
#else
178
   BOTAN_UNUSED(key, rng, pass, msec, pbe_algo);
179
   throw Encoding_Error("PKCS8::BER_encode cannot encrypt because PBES2 was disabled in build");
180
#endif
181
}
940✔
182

183
/*
184
* PEM encode a PKCS #8 private key, encrypted
185
*/
186
std::string PEM_encode(const Private_Key& key,
242✔
187
                       RandomNumberGenerator& rng,
188
                       std::string_view pass,
189
                       std::chrono::milliseconds msec,
190
                       std::string_view pbe_algo) {
191
   if(pass.empty()) {
242✔
192
      return PEM_encode(key);
×
193
   }
194

195
   return PEM_Code::encode(PKCS8::BER_encode(key, rng, pass, msec, pbe_algo), "ENCRYPTED PRIVATE KEY");
726✔
196
}
197

198
/*
199
* BER encode a PKCS #8 private key, encrypted
200
*/
201
std::vector<uint8_t> BER_encode_encrypted_pbkdf_iter(const Private_Key& key,
44✔
202
                                                     RandomNumberGenerator& rng,
203
                                                     std::string_view pass,
204
                                                     size_t pbkdf_iterations,
205
                                                     std::string_view cipher,
206
                                                     std::string_view pbkdf_hash) {
207
#if defined(BOTAN_HAS_PKCS5_PBES2)
208
   const std::pair<AlgorithmIdentifier, std::vector<uint8_t>> pbe_info =
44✔
209
      pbes2_encrypt_iter(key.private_key_info(),
44✔
210
                         pass,
211
                         pbkdf_iterations,
212
                         cipher.empty() ? "AES-256/CBC" : cipher,
44✔
213
                         pbkdf_hash.empty() ? "SHA-256" : pbkdf_hash,
44✔
214
                         rng);
88✔
215

216
   std::vector<uint8_t> output;
44✔
217
   DER_Encoder der(output);
44✔
218
   der.start_sequence().encode(pbe_info.first).encode(pbe_info.second, ASN1_Type::OctetString).end_cons();
44✔
219

220
   return output;
44✔
221

222
#else
223
   BOTAN_UNUSED(key, rng, pass, pbkdf_iterations, cipher, pbkdf_hash);
224
   throw Encoding_Error("PKCS8::BER_encode_encrypted_pbkdf_iter cannot encrypt because PBES2 disabled in build");
225
#endif
226
}
44✔
227

228
/*
229
* PEM encode a PKCS #8 private key, encrypted
230
*/
231
std::string PEM_encode_encrypted_pbkdf_iter(const Private_Key& key,
22✔
232
                                            RandomNumberGenerator& rng,
233
                                            std::string_view pass,
234
                                            size_t pbkdf_iterations,
235
                                            std::string_view cipher,
236
                                            std::string_view pbkdf_hash) {
237
   return PEM_Code::encode(PKCS8::BER_encode_encrypted_pbkdf_iter(key, rng, pass, pbkdf_iterations, cipher, pbkdf_hash),
22✔
238
                           "ENCRYPTED PRIVATE KEY");
44✔
239
}
240

241
/*
242
* BER encode a PKCS #8 private key, encrypted
243
*/
244
std::vector<uint8_t> BER_encode_encrypted_pbkdf_msec(const Private_Key& key,
19✔
245
                                                     RandomNumberGenerator& rng,
246
                                                     std::string_view pass,
247
                                                     std::chrono::milliseconds pbkdf_msec,
248
                                                     size_t* pbkdf_iterations,
249
                                                     std::string_view cipher,
250
                                                     std::string_view pbkdf_hash) {
251
#if defined(BOTAN_HAS_PKCS5_PBES2)
252
   const std::pair<AlgorithmIdentifier, std::vector<uint8_t>> pbe_info =
19✔
253
      pbes2_encrypt_msec(key.private_key_info(),
19✔
254
                         pass,
255
                         pbkdf_msec,
256
                         pbkdf_iterations,
257
                         cipher.empty() ? "AES-256/CBC" : cipher,
19✔
258
                         pbkdf_hash.empty() ? "SHA-256" : pbkdf_hash,
19✔
259
                         rng);
38✔
260

261
   std::vector<uint8_t> output;
19✔
262
   DER_Encoder(output)
38✔
263
      .start_sequence()
19✔
264
      .encode(pbe_info.first)
19✔
265
      .encode(pbe_info.second, ASN1_Type::OctetString)
19✔
266
      .end_cons();
19✔
267

268
   return output;
19✔
269
#else
270
   BOTAN_UNUSED(key, rng, pass, pbkdf_msec, pbkdf_iterations, cipher, pbkdf_hash);
271
   throw Encoding_Error("BER_encode_encrypted_pbkdf_msec cannot encrypt because PBES2 disabled in build");
272
#endif
273
}
19✔
274

275
/*
276
* PEM encode a PKCS #8 private key, encrypted
277
*/
278
std::string PEM_encode_encrypted_pbkdf_msec(const Private_Key& key,
4✔
279
                                            RandomNumberGenerator& rng,
280
                                            std::string_view pass,
281
                                            std::chrono::milliseconds pbkdf_msec,
282
                                            size_t* pbkdf_iterations,
283
                                            std::string_view cipher,
284
                                            std::string_view pbkdf_hash) {
285
   return PEM_Code::encode(
4✔
286
      PKCS8::BER_encode_encrypted_pbkdf_msec(key, rng, pass, pbkdf_msec, pbkdf_iterations, cipher, pbkdf_hash),
4✔
287
      "ENCRYPTED PRIVATE KEY");
8✔
288
}
289

290
namespace {
291

292
/*
293
* Extract a private key (encrypted/unencrypted) and return it
294
*/
295
std::unique_ptr<Private_Key> load_key(DataSource& source,
4,785✔
296
                                      const std::function<std::string()>& get_pass,
297
                                      bool is_encrypted) {
298
   AlgorithmIdentifier alg_id;
4,785✔
299
   secure_vector<uint8_t> pkcs8_key = PKCS8_decode(source, get_pass, alg_id, is_encrypted);
4,785✔
300

301
   const std::string alg_name = alg_id.oid().human_name_or_empty();
4,359✔
302
   if(alg_name.empty()) {
4,359✔
303
      throw PKCS8_Exception(fmt("Unknown algorithm OID {}", alg_id.oid()));
4✔
304
   }
305

306
   return load_private_key(alg_id, pkcs8_key);
7,739✔
307
}
9,144✔
308

309
}  // namespace
310

311
/*
312
* Extract an encrypted private key and return it
313
*/
314
std::unique_ptr<Private_Key> load_key(DataSource& source, const std::function<std::string()>& get_pass) {
11✔
315
   return load_key(source, get_pass, true);
11✔
316
}
317

318
std::unique_ptr<Private_Key> load_key(std::span<const uint8_t> source,
×
319
                                      const std::function<std::string()>& get_passphrase) {
320
   Botan::DataSource_Memory ds(source);
×
321
   return load_key(ds, get_passphrase);
×
322
}
×
323

324
std::unique_ptr<Private_Key> load_key(std::span<const uint8_t> source, std::string_view pass) {
×
325
   Botan::DataSource_Memory ds(source);
×
326
   return load_key(ds, pass);
×
327
}
×
328

329
std::unique_ptr<Private_Key> load_key(std::span<const uint8_t> source) {
14✔
330
   Botan::DataSource_Memory ds(source);
14✔
331
   return load_key(ds);
14✔
332
}
14✔
333

334
/*
335
* Extract an encrypted private key and return it
336
*/
337
std::unique_ptr<Private_Key> load_key(DataSource& source, std::string_view pass) {
528✔
338
   return load_key(
528✔
339
      source, [pass]() { return std::string(pass); }, true);
1,545✔
340
}
341

342
/*
343
* Extract an unencrypted private key and return it
344
*/
345
std::unique_ptr<Private_Key> load_key(DataSource& source) {
4,246✔
346
   auto fail_fn = []() -> std::string {
4,246✔
347
      throw PKCS8_Exception("Internal error: Attempt to read password for unencrypted key");
×
348
   };
349

350
   return load_key(source, fail_fn, false);
7,087✔
351
}
352

353
}  // namespace Botan::PKCS8
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