Botan 3.8.1
Crypto and TLS for C&
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
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
24namespace Botan::PKCS8 {
25
26namespace {
27
28/*
29* Get info from an EncryptedPrivateKeyInfo
30*/
31secure_vector<uint8_t> PKCS8_extract(DataSource& source, AlgorithmIdentifier& pbe_alg_id) {
33
35
36 return key_data;
37}
38
39/*
40* PEM decode and/or decrypt a private key
41*/
42secure_vector<uint8_t> PKCS8_decode(DataSource& source,
43 const std::function<std::string()>& get_passphrase,
44 AlgorithmIdentifier& pk_alg_id,
45 bool is_encrypted) {
46 AlgorithmIdentifier pbe_alg_id;
47 secure_vector<uint8_t> key_data, key;
48
49 try {
50 if(ASN1::maybe_BER(source) && !PEM_Code::matches(source)) {
51 if(is_encrypted) {
52 key_data = PKCS8_extract(source, pbe_alg_id);
53 } else {
54 // todo read more efficiently
55 while(!source.end_of_data()) {
56 uint8_t b;
57 size_t read = source.read_byte(b);
58 if(read) {
59 key_data.push_back(b);
60 }
61 }
62 }
63 } else {
64 std::string label;
65 key_data = PEM_Code::decode(source, label);
66
67 // todo remove autodetect for pem as well?
68 if(label == "PRIVATE KEY") {
69 is_encrypted = false;
70 } else if(label == "ENCRYPTED PRIVATE KEY") {
71 DataSource_Memory key_source(key_data);
72 key_data = PKCS8_extract(key_source, pbe_alg_id);
73 } else {
74 throw PKCS8_Exception(fmt("Unknown PEM label '{}'", label));
75 }
76 }
77
78 if(key_data.empty()) {
79 throw PKCS8_Exception("No key data found");
80 }
81 } catch(Decoding_Error& e) {
82 throw Decoding_Error("PKCS #8 private key decoding", e);
83 }
84
85 try {
86 if(is_encrypted) {
87 if(pbe_alg_id.oid().to_formatted_string() != "PBE-PKCS5v20") {
88 throw PKCS8_Exception(fmt("Unknown PBE type {}", pbe_alg_id.oid()));
89 }
90
91#if defined(BOTAN_HAS_PKCS5_PBES2)
92 key = pbes2_decrypt(key_data, get_passphrase(), pbe_alg_id.parameters());
93#else
94 BOTAN_UNUSED(get_passphrase);
95 throw Decoding_Error("Private key is encrypted but PBES2 was disabled in build");
96#endif
97 } else {
98 key = key_data;
99 }
100
101 BER_Decoder(key)
103 .decode_and_check<size_t>(0, "Unknown PKCS #8 version number")
104 .decode(pk_alg_id)
105 .decode(key, ASN1_Type::OctetString)
106 .discard_remaining()
107 .end_cons();
108 } catch(std::exception& e) {
109 throw Decoding_Error("PKCS #8 private key decoding", e);
110 }
111 return key;
112}
113
114} // namespace
115
116/*
117* PEM encode a PKCS #8 private key, unencrypted
118*/
119std::string PEM_encode(const Private_Key& key) {
120 return PEM_Code::encode(key.private_key_info(), "PRIVATE KEY");
121}
122
123#if defined(BOTAN_HAS_PKCS5_PBES2)
124
125namespace {
126
127std::pair<std::string, std::string> choose_pbe_params(std::string_view pbe_algo, std::string_view key_algo) {
128 if(pbe_algo.empty()) {
129 /*
130 * For algorithms where we are using a non-RFC format anyway, default to
131 * SIV or GCM. For others (RSA, ECDSA, ...) default to something widely
132 * compatible.
133 */
134 const bool nonstandard_pk = (key_algo == "McEliece" || key_algo == "XMSS");
135
136 if(nonstandard_pk) {
137 #if defined(BOTAN_HAS_AEAD_SIV) && defined(BOTAN_HAS_SHA2_64)
138 return std::make_pair("AES-256/SIV", "SHA-512");
139 #elif defined(BOTAN_HAS_AEAD_GCM) && defined(BOTAN_HAS_SHA2_64)
140 return std::make_pair("AES-256/GCM", "SHA-512");
141 #endif
142 }
143
144 // Default is something compatible with everyone else
145 return std::make_pair("AES-256/CBC", "SHA-256");
146 }
147
148 SCAN_Name request(pbe_algo);
149
150 if(request.arg_count() != 2 || (request.algo_name() != "PBE-PKCS5v20" && request.algo_name() != "PBES2")) {
151 throw Invalid_Argument(fmt("Unsupported PBE '{}'", pbe_algo));
152 }
153
154 return std::make_pair(request.arg(0), request.arg(1));
155}
156
157} // namespace
158
159#endif
160
161/*
162* BER encode a PKCS #8 private key, encrypted
163*/
164std::vector<uint8_t> BER_encode(const Private_Key& key,
166 std::string_view pass,
167 std::chrono::milliseconds msec,
168 std::string_view pbe_algo) {
169#if defined(BOTAN_HAS_PKCS5_PBES2)
170 const auto pbe_params = choose_pbe_params(pbe_algo, key.algo_name());
171
172 const std::pair<AlgorithmIdentifier, std::vector<uint8_t>> pbe_info =
173 pbes2_encrypt_msec(PKCS8::BER_encode(key), pass, msec, nullptr, pbe_params.first, pbe_params.second, rng);
174
175 std::vector<uint8_t> output;
176 DER_Encoder der(output);
177 der.start_sequence().encode(pbe_info.first).encode(pbe_info.second, ASN1_Type::OctetString).end_cons();
178
179 return output;
180#else
181 BOTAN_UNUSED(key, rng, pass, msec, pbe_algo);
182 throw Encoding_Error("PKCS8::BER_encode cannot encrypt because PBES2 was disabled in build");
183#endif
184}
185
186/*
187* PEM encode a PKCS #8 private key, encrypted
188*/
189std::string PEM_encode(const Private_Key& key,
191 std::string_view pass,
192 std::chrono::milliseconds msec,
193 std::string_view pbe_algo) {
194 if(pass.empty()) {
195 return PEM_encode(key);
196 }
197
198 return PEM_Code::encode(PKCS8::BER_encode(key, rng, pass, msec, pbe_algo), "ENCRYPTED PRIVATE KEY");
199}
200
201/*
202* BER encode a PKCS #8 private key, encrypted
203*/
204std::vector<uint8_t> BER_encode_encrypted_pbkdf_iter(const Private_Key& key,
206 std::string_view pass,
207 size_t pbkdf_iterations,
208 std::string_view cipher,
209 std::string_view pbkdf_hash) {
210#if defined(BOTAN_HAS_PKCS5_PBES2)
211 const std::pair<AlgorithmIdentifier, std::vector<uint8_t>> pbe_info =
213 pass,
214 pbkdf_iterations,
215 cipher.empty() ? "AES-256/CBC" : cipher,
216 pbkdf_hash.empty() ? "SHA-256" : pbkdf_hash,
217 rng);
218
219 std::vector<uint8_t> output;
220 DER_Encoder der(output);
221 der.start_sequence().encode(pbe_info.first).encode(pbe_info.second, ASN1_Type::OctetString).end_cons();
222
223 return output;
224
225#else
226 BOTAN_UNUSED(key, rng, pass, pbkdf_iterations, cipher, pbkdf_hash);
227 throw Encoding_Error("PKCS8::BER_encode_encrypted_pbkdf_iter cannot encrypt because PBES2 disabled in build");
228#endif
229}
230
231/*
232* PEM encode a PKCS #8 private key, encrypted
233*/
236 std::string_view pass,
237 size_t pbkdf_iterations,
238 std::string_view cipher,
239 std::string_view pbkdf_hash) {
240 return PEM_Code::encode(PKCS8::BER_encode_encrypted_pbkdf_iter(key, rng, pass, pbkdf_iterations, cipher, pbkdf_hash),
241 "ENCRYPTED PRIVATE KEY");
242}
243
244/*
245* BER encode a PKCS #8 private key, encrypted
246*/
247std::vector<uint8_t> BER_encode_encrypted_pbkdf_msec(const Private_Key& key,
249 std::string_view pass,
250 std::chrono::milliseconds pbkdf_msec,
251 size_t* pbkdf_iterations,
252 std::string_view cipher,
253 std::string_view pbkdf_hash) {
254#if defined(BOTAN_HAS_PKCS5_PBES2)
255 const std::pair<AlgorithmIdentifier, std::vector<uint8_t>> pbe_info =
257 pass,
258 pbkdf_msec,
259 pbkdf_iterations,
260 cipher.empty() ? "AES-256/CBC" : cipher,
261 pbkdf_hash.empty() ? "SHA-256" : pbkdf_hash,
262 rng);
263
264 std::vector<uint8_t> output;
265 DER_Encoder(output)
267 .encode(pbe_info.first)
268 .encode(pbe_info.second, ASN1_Type::OctetString)
269 .end_cons();
270
271 return output;
272#else
273 BOTAN_UNUSED(key, rng, pass, pbkdf_msec, pbkdf_iterations, cipher, pbkdf_hash);
274 throw Encoding_Error("BER_encode_encrypted_pbkdf_msec cannot encrypt because PBES2 disabled in build");
275#endif
276}
277
278/*
279* PEM encode a PKCS #8 private key, encrypted
280*/
283 std::string_view pass,
284 std::chrono::milliseconds pbkdf_msec,
285 size_t* pbkdf_iterations,
286 std::string_view cipher,
287 std::string_view pbkdf_hash) {
288 return PEM_Code::encode(
289 PKCS8::BER_encode_encrypted_pbkdf_msec(key, rng, pass, pbkdf_msec, pbkdf_iterations, cipher, pbkdf_hash),
290 "ENCRYPTED PRIVATE KEY");
291}
292
293namespace {
294
295/*
296* Extract a private key (encrypted/unencrypted) and return it
297*/
298std::unique_ptr<Private_Key> load_key(DataSource& source,
299 const std::function<std::string()>& get_pass,
300 bool is_encrypted) {
301 AlgorithmIdentifier alg_id;
302 secure_vector<uint8_t> pkcs8_key = PKCS8_decode(source, get_pass, alg_id, is_encrypted);
303
304 const std::string alg_name = alg_id.oid().human_name_or_empty();
305 if(alg_name.empty()) {
306 throw PKCS8_Exception(fmt("Unknown algorithm OID {}", alg_id.oid()));
307 }
308
309 return load_private_key(alg_id, pkcs8_key);
310}
311
312} // namespace
313
314/*
315* Extract an encrypted private key and return it
316*/
317std::unique_ptr<Private_Key> load_key(DataSource& source, const std::function<std::string()>& get_pass) {
318 return load_key(source, get_pass, true);
319}
320
321std::unique_ptr<Private_Key> load_key(std::span<const uint8_t> source,
322 const std::function<std::string()>& get_passphrase) {
323 Botan::DataSource_Memory ds(source);
324 return load_key(ds, get_passphrase);
325}
326
327std::unique_ptr<Private_Key> load_key(std::span<const uint8_t> source, std::string_view pass) {
328 Botan::DataSource_Memory ds(source);
329 return load_key(ds, pass);
330}
331
332std::unique_ptr<Private_Key> load_key(std::span<const uint8_t> source) {
333 Botan::DataSource_Memory ds(source);
334 return load_key(ds);
335}
336
337/*
338* Extract an encrypted private key and return it
339*/
340std::unique_ptr<Private_Key> load_key(DataSource& source, std::string_view pass) {
341 return load_key(
342 source, [pass]() { return std::string(pass); }, true);
343}
344
345/*
346* Extract an unencrypted private key and return it
347*/
348std::unique_ptr<Private_Key> load_key(DataSource& source) {
349 auto fail_fn = []() -> std::string {
350 throw PKCS8_Exception("Internal error: Attempt to read password for unencrypted key");
351 };
352
353 return load_key(source, fail_fn, false);
354}
355
356} // namespace Botan::PKCS8
#define BOTAN_UNUSED
Definition assert.h:120
const std::vector< uint8_t > & parameters() const
Definition asn1_obj.h:474
const OID & oid() const
Definition asn1_obj.h:472
virtual std::string algo_name() const =0
BER_Decoder & decode(bool &out)
Definition ber_dec.h:185
BER_Decoder & verify_end()
Definition ber_dec.cpp:211
BER_Decoder start_sequence()
Definition ber_dec.h:122
BER_Decoder & decode_and_check(const T &expected, std::string_view error_msg)
Definition ber_dec.h:271
DER_Encoder & start_sequence()
Definition der_enc.h:64
DER_Encoder & end_cons()
Definition der_enc.cpp:171
DER_Encoder & encode(bool b)
Definition der_enc.cpp:250
size_t read_byte(uint8_t &out)
Definition data_src.cpp:26
virtual bool end_of_data() const =0
std::string to_formatted_string() const
Definition asn1_oid.cpp:139
std::string human_name_or_empty() const
Definition asn1_oid.cpp:147
secure_vector< uint8_t > private_key_info() const
Definition pk_keys.cpp:68
bool maybe_BER(DataSource &source)
Definition asn1_obj.cpp:192
std::string encode(const uint8_t der[], size_t length, std::string_view label, size_t width)
Definition pem.cpp:39
bool matches(DataSource &source, std::string_view extra, size_t search_range)
Definition pem.cpp:137
secure_vector< uint8_t > decode(DataSource &source, std::string &label)
Definition pem.cpp:62
std::vector< uint8_t > BER_encode(const Private_Key &key, RandomNumberGenerator &rng, std::string_view pass, std::chrono::milliseconds msec, std::string_view pbe_algo)
Definition pkcs8.cpp:164
std::string PEM_encode_encrypted_pbkdf_iter(const Private_Key &key, RandomNumberGenerator &rng, std::string_view pass, size_t pbkdf_iterations, std::string_view cipher, std::string_view pbkdf_hash)
Definition pkcs8.cpp:234
std::string PEM_encode(const Private_Key &key)
Definition pkcs8.cpp:119
std::string PEM_encode_encrypted_pbkdf_msec(const Private_Key &key, RandomNumberGenerator &rng, std::string_view pass, std::chrono::milliseconds pbkdf_msec, size_t *pbkdf_iterations, std::string_view cipher, std::string_view pbkdf_hash)
Definition pkcs8.cpp:281
std::vector< uint8_t > BER_encode_encrypted_pbkdf_iter(const Private_Key &key, RandomNumberGenerator &rng, std::string_view pass, size_t pbkdf_iterations, std::string_view cipher, std::string_view pbkdf_hash)
Definition pkcs8.cpp:204
std::vector< uint8_t > BER_encode_encrypted_pbkdf_msec(const Private_Key &key, RandomNumberGenerator &rng, std::string_view pass, std::chrono::milliseconds pbkdf_msec, size_t *pbkdf_iterations, std::string_view cipher, std::string_view pbkdf_hash)
Definition pkcs8.cpp:247
std::unique_ptr< Private_Key > load_key(DataSource &source, const std::function< std::string()> &get_pass)
Definition pkcs8.cpp:317
std::string fmt(std::string_view format, const T &... args)
Definition fmt.h:53
std::pair< AlgorithmIdentifier, std::vector< uint8_t > > pbes2_encrypt_iter(std::span< const uint8_t > key_bits, std::string_view passphrase, size_t pbkdf_iter, std::string_view cipher, std::string_view digest, RandomNumberGenerator &rng)
Definition pbes2.cpp:271
secure_vector< uint8_t > pbes2_decrypt(std::span< const uint8_t > key_bits, std::string_view passphrase, const std::vector< uint8_t > &params)
Definition pbes2.cpp:280
std::pair< AlgorithmIdentifier, std::vector< uint8_t > > pbes2_encrypt_msec(std::span< const uint8_t > key_bits, std::string_view passphrase, std::chrono::milliseconds msec, size_t *out_iterations_if_nonnull, std::string_view cipher, std::string_view digest, RandomNumberGenerator &rng)
Definition pbes2.cpp:253
std::vector< T, secure_allocator< T > > secure_vector
Definition secmem.h:65
std::unique_ptr< Private_Key > load_private_key(const AlgorithmIdentifier &alg_id, std::span< const uint8_t > key_bits)
Definition pk_algs.cpp:283