Botan  2.7.0
Crypto and TLS for C++11
pkcs8.cpp
Go to the documentation of this file.
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 #include <botan/rng.h>
10 #include <botan/der_enc.h>
11 #include <botan/ber_dec.h>
12 #include <botan/alg_id.h>
13 #include <botan/oids.h>
14 #include <botan/pem.h>
15 #include <botan/scan_name.h>
16 #include <botan/pk_algs.h>
17 
18 #if defined(BOTAN_HAS_PKCS5_PBES2)
19  #include <botan/pbes2.h>
20 #endif
21 
22 namespace Botan {
23 
24 namespace PKCS8 {
25 
26 namespace {
27 
28 /*
29 * Get info from an EncryptedPrivateKeyInfo
30 */
31 secure_vector<uint8_t> PKCS8_extract(DataSource& source,
32  AlgorithmIdentifier& pbe_alg_id)
33  {
34  secure_vector<uint8_t> key_data;
35 
36  BER_Decoder(source)
38  .decode(pbe_alg_id)
39  .decode(key_data, OCTET_STRING)
40  .verify_end();
41 
42  return key_data;
43  }
44 
45 /*
46 * PEM decode and/or decrypt a private key
47 */
48 secure_vector<uint8_t> PKCS8_decode(
49  DataSource& source,
50  std::function<std::string ()> get_passphrase,
51  AlgorithmIdentifier& pk_alg_id,
52  bool is_encrypted)
53  {
54  AlgorithmIdentifier pbe_alg_id;
55  secure_vector<uint8_t> key_data, key;
56 
57  try {
58  if(ASN1::maybe_BER(source) && !PEM_Code::matches(source))
59  {
60  if(is_encrypted)
61  {
62  key_data = PKCS8_extract(source, pbe_alg_id);
63  }
64  else
65  {
66  // todo read more efficiently
67  while(!source.end_of_data())
68  {
69  uint8_t b;
70  size_t read = source.read_byte(b);
71  if(read)
72  {
73  key_data.push_back(b);
74  }
75  }
76  }
77  }
78  else
79  {
80  std::string label;
81  key_data = PEM_Code::decode(source, label);
82 
83  // todo remove autodetect for pem as well?
84  if(label == "PRIVATE KEY")
85  is_encrypted = false;
86  else if(label == "ENCRYPTED PRIVATE KEY")
87  {
88  DataSource_Memory key_source(key_data);
89  key_data = PKCS8_extract(key_source, pbe_alg_id);
90  }
91  else
92  throw PKCS8_Exception("Unknown PEM label " + label);
93  }
94 
95  if(key_data.empty())
96  throw PKCS8_Exception("No key data found");
97  }
98  catch(Decoding_Error& e)
99  {
100  throw Decoding_Error("PKCS #8 private key decoding failed: " + std::string(e.what()));
101  }
102 
103  try
104  {
105  if(is_encrypted)
106  {
107  if(OIDS::lookup(pbe_alg_id.get_oid()) != "PBE-PKCS5v20")
108  throw Exception("Unknown PBE type " + pbe_alg_id.get_oid().as_string());
109 #if defined(BOTAN_HAS_PKCS5_PBES2)
110  key = pbes2_decrypt(key_data, get_passphrase(), pbe_alg_id.get_parameters());
111 #else
112  BOTAN_UNUSED(get_passphrase);
113  throw Decoding_Error("Private key is encrypted but PBES2 was disabled in build");
114 #endif
115  }
116  else
117  key = key_data;
118 
119  BER_Decoder(key)
121  .decode_and_check<size_t>(0, "Unknown PKCS #8 version number")
122  .decode(pk_alg_id)
123  .decode(key, OCTET_STRING)
124  .discard_remaining()
125  .end_cons();
126  }
127  catch(std::exception& e)
128  {
129  throw Decoding_Error("PKCS #8 private key decoding failed: " + std::string(e.what()));
130  }
131  return key;
132  }
133 
134 }
135 
136 /*
137 * BER encode a PKCS #8 private key, unencrypted
138 */
140  {
141  // keeping around for compat
142  return key.private_key_info();
143  }
144 
145 /*
146 * PEM encode a PKCS #8 private key, unencrypted
147 */
148 std::string PEM_encode(const Private_Key& key)
149  {
150  return PEM_Code::encode(PKCS8::BER_encode(key), "PRIVATE KEY");
151  }
152 
153 #if defined(BOTAN_HAS_PKCS5_PBES2)
154 
155 namespace {
156 
157 std::pair<std::string, std::string>
158 choose_pbe_params(const std::string& pbe_algo, const std::string& key_algo)
159  {
160  if(pbe_algo.empty())
161  {
162  // Defaults:
163  if(key_algo == "Curve25519" || key_algo == "McEliece")
164  return std::make_pair("AES-256/GCM", "SHA-512");
165  else // for everything else (RSA, DSA, ECDSA, GOST, ...)
166  return std::make_pair("AES-256/CBC", "SHA-256");
167  }
168 
169  SCAN_Name request(pbe_algo);
170  if(request.algo_name() != "PBE-PKCS5v20" || request.arg_count() != 2)
171  throw Exception("Unsupported PBE " + pbe_algo);
172  return std::make_pair(request.arg(0), request.arg(1));
173  }
174 
175 }
176 
177 #endif
178 
179 /*
180 * BER encode a PKCS #8 private key, encrypted
181 */
182 std::vector<uint8_t> BER_encode(const Private_Key& key,
184  const std::string& pass,
185  std::chrono::milliseconds msec,
186  const std::string& pbe_algo)
187  {
188 #if defined(BOTAN_HAS_PKCS5_PBES2)
189  const auto pbe_params = choose_pbe_params(pbe_algo, key.algo_name());
190 
191  const std::pair<AlgorithmIdentifier, std::vector<uint8_t>> pbe_info =
192  pbes2_encrypt_msec(PKCS8::BER_encode(key), pass, msec, nullptr,
193  pbe_params.first, pbe_params.second, rng);
194 
195  std::vector<uint8_t> output;
196  DER_Encoder der(output);
197  der.start_cons(SEQUENCE)
198  .encode(pbe_info.first)
199  .encode(pbe_info.second, OCTET_STRING)
200  .end_cons();
201 
202  return output;
203 #else
204  BOTAN_UNUSED(key, rng, pass, msec, pbe_algo);
205  throw Encoding_Error("PKCS8::BER_encode cannot encrypt because PBES2 was disabled in build");
206 #endif
207  }
208 
209 /*
210 * PEM encode a PKCS #8 private key, encrypted
211 */
212 std::string PEM_encode(const Private_Key& key,
214  const std::string& pass,
215  std::chrono::milliseconds msec,
216  const std::string& pbe_algo)
217  {
218  if(pass.empty())
219  return PEM_encode(key);
220 
221  return PEM_Code::encode(PKCS8::BER_encode(key, rng, pass, msec, pbe_algo),
222  "ENCRYPTED PRIVATE KEY");
223  }
224 
225 /*
226 * BER encode a PKCS #8 private key, encrypted
227 */
228 std::vector<uint8_t> BER_encode_encrypted_pbkdf_iter(const Private_Key& key,
230  const std::string& pass,
231  size_t pbkdf_iterations,
232  const std::string& cipher,
233  const std::string& pbkdf_hash)
234  {
235 #if defined(BOTAN_HAS_PKCS5_PBES2)
236  const std::pair<AlgorithmIdentifier, std::vector<uint8_t>> pbe_info =
238  pass, pbkdf_iterations,
239  cipher.empty() ? "AES-256/CBC" : cipher,
240  pbkdf_hash.empty() ? "SHA-256" : pbkdf_hash,
241  rng);
242 
243  std::vector<uint8_t> output;
244  DER_Encoder der(output);
245  der.start_cons(SEQUENCE)
246  .encode(pbe_info.first)
247  .encode(pbe_info.second, OCTET_STRING)
248  .end_cons();
249 
250  return output;
251 
252 #else
253  BOTAN_UNUSED(key, rng, pass, pbkdf_iterations, cipher, pbkdf_hash);
254  throw Encoding_Error("PKCS8::BER_encode_encrypted_pbkdf_iter cannot encrypt because PBES2 disabled in build");
255 #endif
256  }
257 
258 /*
259 * PEM encode a PKCS #8 private key, encrypted
260 */
263  const std::string& pass,
264  size_t pbkdf_iterations,
265  const std::string& cipher,
266  const std::string& pbkdf_hash)
267  {
268  return PEM_Code::encode(
269  PKCS8::BER_encode_encrypted_pbkdf_iter(key, rng, pass, pbkdf_iterations, cipher, pbkdf_hash),
270  "ENCRYPTED PRIVATE KEY");
271  }
272 
273 /*
274 * BER encode a PKCS #8 private key, encrypted
275 */
276 std::vector<uint8_t> BER_encode_encrypted_pbkdf_msec(const Private_Key& key,
278  const std::string& pass,
279  std::chrono::milliseconds pbkdf_msec,
280  size_t* pbkdf_iterations,
281  const std::string& cipher,
282  const std::string& pbkdf_hash)
283  {
284 #if defined(BOTAN_HAS_PKCS5_PBES2)
285  const std::pair<AlgorithmIdentifier, std::vector<uint8_t>> pbe_info =
287  pbkdf_msec, pbkdf_iterations,
288  cipher.empty() ? "AES-256/CBC" : cipher,
289  pbkdf_hash.empty() ? "SHA-256" : pbkdf_hash,
290  rng);
291 
292  std::vector<uint8_t> output;
293  DER_Encoder(output)
295  .encode(pbe_info.first)
296  .encode(pbe_info.second, OCTET_STRING)
297  .end_cons();
298 
299  return output;
300 #else
301  BOTAN_UNUSED(key, rng, pass, pbkdf_msec, pbkdf_iterations, cipher, pbkdf_hash);
302  throw Encoding_Error("BER_encode_encrypted_pbkdf_msec cannot encrypt because PBES2 disabled in build");
303 #endif
304  }
305 
306 /*
307 * PEM encode a PKCS #8 private key, encrypted
308 */
311  const std::string& pass,
312  std::chrono::milliseconds pbkdf_msec,
313  size_t* pbkdf_iterations,
314  const std::string& cipher,
315  const std::string& pbkdf_hash)
316  {
317  return PEM_Code::encode(
318  PKCS8::BER_encode_encrypted_pbkdf_msec(key, rng, pass, pbkdf_msec, pbkdf_iterations, cipher, pbkdf_hash),
319  "ENCRYPTED PRIVATE KEY");
320  }
321 
322 namespace {
323 
324 /*
325 * Extract a private key (encrypted/unencrypted) and return it
326 */
327 std::unique_ptr<Private_Key>
328 load_key(DataSource& source,
329  std::function<std::string ()> get_pass,
330  bool is_encrypted)
331  {
332  AlgorithmIdentifier alg_id;
333  secure_vector<uint8_t> pkcs8_key = PKCS8_decode(source, get_pass, alg_id, is_encrypted);
334 
335  const std::string alg_name = OIDS::lookup(alg_id.get_oid());
336  if(alg_name.empty() || alg_name == alg_id.get_oid().as_string())
337  throw PKCS8_Exception("Unknown algorithm OID: " +
338  alg_id.get_oid().as_string());
339 
340  return load_private_key(alg_id, pkcs8_key);
341  }
342 
343 }
344 
345 /*
346 * Extract an encrypted private key and return it
347 */
348 std::unique_ptr<Private_Key> load_key(DataSource& source,
349  std::function<std::string ()> get_pass)
350  {
351  return load_key(source, get_pass, true);
352  }
353 
354 /*
355 * Extract an encrypted private key and return it
356 */
357 std::unique_ptr<Private_Key> load_key(DataSource& source,
358  const std::string& pass)
359  {
360  return load_key(source, [pass]() { return pass; }, true);
361  }
362 
363 /*
364 * Extract an unencrypted private key and return it
365 */
366 std::unique_ptr<Private_Key> load_key(DataSource& source)
367  {
368  auto fail_fn = []() -> std::string {
369  throw PKCS8_Exception("Internal error: Attempt to read password for unencrypted key");
370  };
371 
372  return load_key(source, fail_fn, false);
373  }
374 
375 /*
376 * Make a copy of this private key
377 */
378 std::unique_ptr<Private_Key> copy_key(const Private_Key& key)
379  {
380  DataSource_Memory source(PEM_encode(key));
381  return PKCS8::load_key(source);
382  }
383 
384 /*
385 * Extract an encrypted private key and return it
386 */
389  std::function<std::string ()> get_pass)
390  {
391  BOTAN_UNUSED(rng);
392  return PKCS8::load_key(source, get_pass).release();
393  }
394 
395 /*
396 * Extract an encrypted private key and return it
397 */
400  const std::string& pass)
401  {
402  BOTAN_UNUSED(rng);
403  return PKCS8::load_key(source, pass).release();
404  }
405 
406 /*
407 * Extract an unencrypted private key and return it
408 */
411  {
412  BOTAN_UNUSED(rng);
413  return PKCS8::load_key(source).release();
414  }
415 
416 #if defined(BOTAN_TARGET_OS_HAS_FILESYSTEM)
417 
418 /*
419 * Extract an encrypted private key and return it
420 */
421 Private_Key* load_key(const std::string& fsname,
423  std::function<std::string ()> get_pass)
424  {
425  BOTAN_UNUSED(rng);
426  DataSource_Stream in(fsname);
427  return PKCS8::load_key(in, get_pass).release();
428  }
429 
430 /*
431 * Extract an encrypted private key and return it
432 */
433 Private_Key* load_key(const std::string& fsname,
434  RandomNumberGenerator& rng,
435  const std::string& pass)
436  {
437  BOTAN_UNUSED(rng);
438  DataSource_Stream in(fsname);
439  return PKCS8::load_key(in, [pass]() { return pass; }).release();
440  }
441 
442 /*
443 * Extract an unencrypted private key and return it
444 */
445 Private_Key* load_key(const std::string& fsname,
446  RandomNumberGenerator& rng)
447  {
448  BOTAN_UNUSED(rng);
449  DataSource_Stream in(fsname);
450  return PKCS8::load_key(in).release();
451  }
452 #endif
453 
454 /*
455 * Make a copy of this private key
456 */
459  {
460  BOTAN_UNUSED(rng);
461  return PKCS8::copy_key(key).release();
462  }
463 
464 
465 
466 }
467 
468 }
std::unique_ptr< Private_Key > load_private_key(const AlgorithmIdentifier &alg_id, const secure_vector< uint8_t > &key_bits)
Definition: pk_algs.cpp:170
std::unique_ptr< Private_Key > copy_key(const Private_Key &key)
Definition: pkcs8.cpp:378
BER_Decoder & decode_and_check(const T &expected, const std::string &error_msg)
Definition: ber_dec.h:277
std::string as_string() const
Definition: asn1_oid.h:48
std::pair< AlgorithmIdentifier, std::vector< uint8_t > > pbes2_encrypt_msec(const secure_vector< uint8_t > &key_bits, const std::string &passphrase, std::chrono::milliseconds msec, size_t *out_iterations_if_nonnull, const std::string &cipher, const std::string &digest, RandomNumberGenerator &rng)
Definition: pbes2.cpp:246
virtual std::string algo_name() const =0
std::vector< uint8_t > BER_encode_encrypted_pbkdf_iter(const Private_Key &key, RandomNumberGenerator &rng, const std::string &pass, size_t pbkdf_iterations, const std::string &cipher, const std::string &pbkdf_hash)
Definition: pkcs8.cpp:228
bool maybe_BER(DataSource &source)
Definition: asn1_obj.cpp:219
DER_Encoder & end_cons()
Definition: der_enc.cpp:191
std::vector< uint8_t > BER_encode_encrypted_pbkdf_msec(const Private_Key &key, RandomNumberGenerator &rng, const std::string &pass, std::chrono::milliseconds pbkdf_msec, size_t *pbkdf_iterations, const std::string &cipher, const std::string &pbkdf_hash)
Definition: pkcs8.cpp:276
BER_Decoder & decode(bool &out)
Definition: ber_dec.h:170
DER_Encoder & encode(bool b)
Definition: der_enc.cpp:285
secure_vector< uint8_t > private_key_info() const
Definition: pk_keys.cpp:64
std::string encode(const uint8_t der[], size_t length, const std::string &label, size_t width)
Definition: pem.cpp:43
bool matches(DataSource &source, const std::string &extra, size_t search_range)
Definition: pem.cpp:142
virtual bool end_of_data() const =0
std::pair< AlgorithmIdentifier, std::vector< uint8_t > > pbes2_encrypt_iter(const secure_vector< uint8_t > &key_bits, const std::string &passphrase, size_t pbkdf_iter, const std::string &cipher, const std::string &digest, RandomNumberGenerator &rng)
Definition: pbes2.cpp:265
std::string PEM_encode(const Private_Key &key)
Definition: pkcs8.cpp:148
const char * what() const BOTAN_NOEXCEPT override
Definition: exceptn.h:25
secure_vector< uint8_t > decode(DataSource &source, std::string &label)
Definition: pem.cpp:68
BER_Decoder start_cons(ASN1_Tag type_tag, ASN1_Tag class_tag=UNIVERSAL)
Definition: ber_dec.cpp:290
Definition: alg_id.cpp:13
size_t read_byte(uint8_t &out)
Definition: data_src.cpp:23
secure_vector< uint8_t > BER_encode(const Private_Key &key)
Definition: pkcs8.cpp:139
secure_vector< uint8_t > pbes2_decrypt(const secure_vector< uint8_t > &key_bits, const std::string &passphrase, const std::vector< uint8_t > &params)
Definition: pbes2.cpp:276
#define BOTAN_UNUSED(...)
Definition: assert.h:130
std::string PEM_encode_encrypted_pbkdf_iter(const Private_Key &key, RandomNumberGenerator &rng, const std::string &pass, size_t pbkdf_iterations, const std::string &cipher, const std::string &pbkdf_hash)
Definition: pkcs8.cpp:261
const std::vector< uint8_t > & get_parameters() const
Definition: alg_id.h:38
const OID & get_oid() const
Definition: alg_id.h:37
BER_Decoder & verify_end()
Definition: ber_dec.cpp:208
DER_Encoder & start_cons(ASN1_Tag type_tag, ASN1_Tag class_tag=UNIVERSAL)
Definition: der_enc.cpp:181
std::vector< T, secure_allocator< T > > secure_vector
Definition: secmem.h:88
std::unique_ptr< Private_Key > load_key(DataSource &source, std::function< std::string()> get_pass)
Definition: pkcs8.cpp:348
std::string lookup(const OID &oid)
Definition: oids.cpp:113
std::string PEM_encode_encrypted_pbkdf_msec(const Private_Key &key, RandomNumberGenerator &rng, const std::string &pass, std::chrono::milliseconds pbkdf_msec, size_t *pbkdf_iterations, const std::string &cipher, const std::string &pbkdf_hash)
Definition: pkcs8.cpp:309