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

randombit / botan / 23926907288

02 Apr 2026 11:34PM UTC coverage: 89.465% (-0.06%) from 89.52%
23926907288

Pull #5514

github

web-flow
Merge cd041e548 into fc221e724
Pull Request #5514: Add BER_Decoder::Limits

105546 of 117974 relevant lines covered (89.47%)

11670616.9 hits per line

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

88.49
/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) {
501✔
32
   secure_vector<uint8_t> key_data;
501✔
33

34
   BER_Decoder(source, BER_Decoder::Limits::DER())
1,002✔
35
      .start_sequence()
501✔
36
      .decode(pbe_alg_id)
501✔
37
      .decode(key_data, ASN1_Type::OctetString)
501✔
38
      .verify_end();
501✔
39

40
   return key_data;
501✔
41
}
×
42

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

54
   try {
4,784✔
55
      if(ASN1::maybe_BER(source) && !PEM_Code::matches(source)) {
4,784✔
56
         if(is_encrypted) {
2,172✔
57
            key_data = PKCS8_extract(source, pbe_alg_id);
510✔
58
         } else {
59
            // todo read more efficiently
60
            while(auto b = source.read_byte()) {
1,204,643✔
61
               key_data.push_back(*b);
1,202,726✔
62
            }
1,202,726✔
63
         }
64
      } else {
65
         std::string label;
2,611✔
66
         key_data = PEM_Code::decode(source, label);
5,160✔
67

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

79
      if(key_data.empty()) {
4,693✔
80
         throw PKCS8_Exception("No key data found");
×
81
      }
82
   } catch(Decoding_Error& e) {
91✔
83
      throw Decoding_Error("PKCS #8 private key decoding", e);
83✔
84
   }
83✔
85

86
   try {
4,693✔
87
      if(is_encrypted) {
4,693✔
88
         if(pbe_alg_id.oid().to_formatted_string() != "PBE-PKCS5v20") {
501✔
89
            throw PKCS8_Exception(fmt("Unknown PBE type {}", pbe_alg_id.oid()));
×
90
         }
91

92
#if defined(BOTAN_HAS_PKCS5_PBES2)
93
         key = pbes2_decrypt(key_data, get_passphrase(), pbe_alg_id.parameters());
1,503✔
94
#else
95
         BOTAN_UNUSED(get_passphrase);
96
         throw Decoding_Error("Private key is encrypted but PBES2 was disabled in build");
97
#endif
98
      } else {
99
         key = key_data;
4,192✔
100
      }
101

102
      BER_Decoder(key, BER_Decoder::Limits::DER())
10,604✔
103
         .start_sequence()
3,546✔
104
         .decode_and_check<size_t>(0, "Unknown PKCS #8 version number")
7,026✔
105
         .decode(pk_alg_id)
3,480✔
106
         .decode(key, ASN1_Type::OctetString)
3,475✔
107
         .discard_remaining()
3,475✔
108
         .end_cons();
3,475✔
109
   } catch(std::exception& e) {
1,218✔
110
      throw Decoding_Error("PKCS #8 private key decoding", e);
1,218✔
111
   }
1,218✔
112
   return key;
6,950✔
113
}
6,093✔
114

115
}  // namespace
116

117
/*
118
* PEM encode a PKCS #8 private key, unencrypted
119
*/
120
std::string PEM_encode(const Private_Key& key) {
57✔
121
   return PEM_Code::encode(key.private_key_info(), "PRIVATE KEY");
171✔
122
}
123

124
#if defined(BOTAN_HAS_PKCS5_PBES2)
125

126
namespace {
127

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

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

145
      // Default is something compatible with everyone else
146
      return std::make_pair("AES-256/CBC", "SHA-256");
26✔
147
   }
148

149
   const SCAN_Name request(pbe_algo);
444✔
150

151
   if(request.arg_count() != 2 || (request.algo_name() != "PBE-PKCS5v20" && request.algo_name() != "PBES2")) {
444✔
152
      throw Invalid_Argument(fmt("Unsupported PBE '{}'", pbe_algo));
×
153
   }
154

155
   return std::make_pair(request.arg(0), request.arg(1));
888✔
156
}
444✔
157

158
}  // namespace
159

160
#endif
161

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

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

176
   std::vector<uint8_t> output;
470✔
177
   DER_Encoder der(output);
470✔
178
   der.start_sequence().encode(pbe_info.first).encode(pbe_info.second, ASN1_Type::OctetString).end_cons();
470✔
179

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

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

199
   return PEM_Code::encode(PKCS8::BER_encode(key, rng, pass, msec, pbe_algo), "ENCRYPTED PRIVATE KEY");
726✔
200
}
201

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

220
   std::vector<uint8_t> output;
48✔
221
   DER_Encoder der(output);
48✔
222
   der.start_sequence().encode(pbe_info.first).encode(pbe_info.second, ASN1_Type::OctetString).end_cons();
48✔
223

224
   return output;
48✔
225

226
#else
227
   BOTAN_UNUSED(key, rng, pass, pbkdf_iterations, cipher, pbkdf_hash);
228
   throw Encoding_Error("PKCS8::BER_encode_encrypted_pbkdf_iter cannot encrypt because PBES2 disabled in build");
229
#endif
230
}
48✔
231

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

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

265
   std::vector<uint8_t> output;
20✔
266
   DER_Encoder(output)
40✔
267
      .start_sequence()
20✔
268
      .encode(pbe_info.first)
20✔
269
      .encode(pbe_info.second, ASN1_Type::OctetString)
20✔
270
      .end_cons();
20✔
271

272
   return output;
20✔
273
#else
274
   BOTAN_UNUSED(key, rng, pass, pbkdf_msec, pbkdf_iterations, cipher, pbkdf_hash);
275
   throw Encoding_Error("BER_encode_encrypted_pbkdf_msec cannot encrypt because PBES2 disabled in build");
276
#endif
277
}
20✔
278

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

294
namespace {
295

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

305
   const std::string alg_name = alg_id.oid().human_name_or_empty();
3,475✔
306
   if(alg_name.empty()) {
3,475✔
307
      throw PKCS8_Exception(fmt("Unknown algorithm OID {}", alg_id.oid()));
×
308
   }
309

310
   return load_private_key(alg_id, pkcs8_key);
6,531✔
311
}
8,259✔
312

313
}  // namespace
314

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

322
std::unique_ptr<Private_Key> load_key(std::span<const uint8_t> source,
×
323
                                      const std::function<std::string()>& get_passphrase) {
324
   Botan::DataSource_Memory ds(source);
×
325
   return load_key(ds, get_passphrase);
×
326
}
×
327

328
std::unique_ptr<Private_Key> load_key(std::span<const uint8_t> source, std::string_view pass) {
×
329
   Botan::DataSource_Memory ds(source);
×
330
   return load_key(ds, pass);
×
331
}
×
332

333
std::unique_ptr<Private_Key> load_key(std::span<const uint8_t> source) {
14✔
334
   Botan::DataSource_Memory ds(source);
14✔
335
   return load_key(ds);
14✔
336
}
14✔
337

338
/*
339
* Extract an encrypted private key and return it
340
*/
341
std::unique_ptr<Private_Key> load_key(DataSource& source, std::string_view pass) {
526✔
342
   return load_key(
526✔
343
      source, [pass]() { return std::string(pass); }, true);
1,543✔
344
}
345

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

354
   return load_key(source, fail_fn, false);
6,766✔
355
}
356

357
}  // 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