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

randombit / botan / 5133556677

31 May 2023 02:11PM UTC coverage: 91.735% (-0.3%) from 92.012%
5133556677

Pull #3568

github

web-flow
Merge de48a2eb6 into 1cbeffafb
Pull Request #3568: Change clang-format AllowShortBlocksOnASingleLine from true to Empty

76059 of 82912 relevant lines covered (91.73%)

12004312.75 hits per line

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

85.93
/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/ber_dec.h>
12
#include <botan/der_enc.h>
13
#include <botan/pem.h>
14
#include <botan/pk_algs.h>
15
#include <botan/rng.h>
16
#include <botan/internal/fmt.h>
17
#include <botan/internal/scan_name.h>
18

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

23
namespace Botan::PKCS8 {
24

25
namespace {
26

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

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

35
   return key_data;
223✔
36
}
×
37

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

48
   try {
4,284✔
49
      if(ASN1::maybe_BER(source) && !PEM_Code::matches(source)) {
4,284✔
50
         if(is_encrypted) {
1,879✔
51
            key_data = PKCS8_extract(source, pbe_alg_id);
230✔
52
         } else {
53
            // todo read more efficiently
54
            while(!source.end_of_data()) {
733,793✔
55
               uint8_t b;
732,029✔
56
               size_t read = source.read_byte(b);
732,029✔
57
               if(read) {
732,029✔
58
                  key_data.push_back(b);
732,029✔
59
               }
60
            }
61
         }
62
      } else {
63
         std::string label;
2,404✔
64
         key_data = PEM_Code::decode(source, label);
4,746✔
65

66
         // todo remove autodetect for pem as well?
67
         if(label == "PRIVATE KEY") {
2,342✔
68
            is_encrypted = false;
69
         } else if(label == "ENCRYPTED PRIVATE KEY") {
136✔
70
            DataSource_Memory key_source(key_data);
108✔
71
            key_data = PKCS8_extract(key_source, pbe_alg_id);
216✔
72
         } else {
108✔
73
            throw PKCS8_Exception(fmt("Unknown PEM label '{}'", label));
56✔
74
         }
75
      }
2,404✔
76

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

84
   try {
4,193✔
85
      if(is_encrypted) {
4,193✔
86
         if(pbe_alg_id.oid().to_formatted_string() != "PBE-PKCS5v20") {
223✔
87
            throw PKCS8_Exception(fmt("Unknown PBE type {}", pbe_alg_id.oid()));
×
88
         }
89

90
#if defined(BOTAN_HAS_PKCS5_PBES2)
91
         key = pbes2_decrypt(key_data, get_passphrase(), pbe_alg_id.parameters());
795✔
92
#else
93
         BOTAN_UNUSED(get_passphrase);
94
         throw Decoding_Error("Private key is encrypted but PBES2 was disabled in build");
95
#endif
96
      } else {
97
         key = key_data;
3,970✔
98
      }
99

100
      BER_Decoder(key)
4,193✔
101
         .start_sequence()
8,292✔
102
         .decode_and_check<size_t>(0, "Unknown PKCS #8 version number")
8,092✔
103
         .decode(pk_alg_id)
3,993✔
104
         .decode(key, ASN1_Type::OctetString)
3,372✔
105
         .discard_remaining()
3,372✔
106
         .end_cons();
3,372✔
107
   } catch(std::exception& e) {
821✔
108
      throw Decoding_Error("PKCS #8 private key decoding", e);
821✔
109
   }
821✔
110
   return key;
6,744✔
111
}
5,196✔
112

113
}  // namespace
114

115
/*
116
* PEM encode a PKCS #8 private key, unencrypted
117
*/
118
std::string PEM_encode(const Private_Key& key) { return PEM_Code::encode(key.private_key_info(), "PRIVATE KEY"); }
180✔
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) {
194✔
125
   if(pbe_algo.empty()) {
194✔
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");
52✔
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);
168✔
146

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

151
   return std::make_pair(request.arg(0), request.arg(1));
336✔
152
}
168✔
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,
194✔
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());
194✔
168

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

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

176
   return output;
194✔
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
}
194✔
182

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

195
   return PEM_Code::encode(PKCS8::BER_encode(key, rng, pass, msec, pbe_algo), "ENCRYPTED PRIVATE KEY");
312✔
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(),
88✔
210
                         pass,
211
                         pbkdf_iterations,
212
                         cipher.empty() ? "AES-256/CBC" : cipher,
44✔
213
                         pbkdf_hash.empty() ? "SHA-256" : pbkdf_hash,
44✔
214
                         rng);
132✔
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(),
38✔
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);
27✔
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,284✔
296
                                      const std::function<std::string()>& get_pass,
297
                                      bool is_encrypted) {
298
   AlgorithmIdentifier alg_id;
4,284✔
299
   secure_vector<uint8_t> pkcs8_key = PKCS8_decode(source, get_pass, alg_id, is_encrypted);
4,284✔
300

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

306
   return load_private_key(alg_id, pkcs8_key);
6,071✔
307
}
7,656✔
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) {
×
330
   Botan::DataSource_Memory ds(source);
×
331
   return load_key(ds);
×
332
}
×
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) {
237✔
338
   return load_key(
237✔
339
      source, [pass]() { return std::string(pass); }, true);
687✔
340
}
341

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

350
   return load_key(source, fail_fn, false);
6,487✔
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

© 2025 Coveralls, Inc