Botan 3.9.0
Crypto and TLS for C&
pbes2.cpp
Go to the documentation of this file.
1/*
2* PKCS #5 PBES2
3* (C) 1999-2008,2014,2021 Jack Lloyd
4* (C) 2018 Ribose Inc
5*
6* Botan is released under the Simplified BSD License (see license.txt)
7*/
8
9#include <botan/internal/pbes2.h>
10
11#include <botan/asn1_obj.h>
12#include <botan/ber_dec.h>
13#include <botan/cipher_mode.h>
14#include <botan/der_enc.h>
15#include <botan/pwdhash.h>
16#include <botan/rng.h>
17#include <botan/internal/fmt.h>
18#include <botan/internal/parsing.h>
19
20namespace Botan {
21
22namespace {
23
24bool known_pbes_cipher_mode(std::string_view mode) {
25 return (mode == "CBC" || mode == "GCM" || mode == "SIV");
26}
27
28secure_vector<uint8_t> derive_key(std::string_view passphrase,
29 const AlgorithmIdentifier& kdf_algo,
30 size_t default_key_size) {
31 if(kdf_algo.oid() == OID::from_string("PKCS5.PBKDF2")) {
33 size_t iterations = 0;
34 size_t key_length = 0;
35
36 AlgorithmIdentifier prf_algo;
37 BER_Decoder(kdf_algo.parameters())
40 .decode(iterations)
42 .decode_optional(prf_algo,
46 .end_cons();
47
48 if(salt.size() < 8) {
49 throw Decoding_Error("PBE-PKCS5 v2.0: Encoded salt is too small");
50 }
51
52 if(key_length == 0) {
53 key_length = default_key_size;
54 }
55
56 const std::string prf = prf_algo.oid().human_name_or_empty();
57 if(prf.empty() || !prf.starts_with("HMAC")) {
58 throw Decoding_Error(fmt("Unknown PBES2 PRF {}", prf_algo.oid()));
59 }
60
61 auto pbkdf_fam = PasswordHashFamily::create_or_throw(fmt("PBKDF2({})", prf));
62 auto pbkdf = pbkdf_fam->from_params(iterations);
63
64 secure_vector<uint8_t> derived_key(key_length);
65 pbkdf->hash(derived_key, passphrase, salt);
66 return derived_key;
67 } else if(kdf_algo.oid() == OID::from_string("Scrypt")) {
69 size_t N = 0;
70 size_t r = 0;
71 size_t p = 0;
72 size_t key_length = 0;
73
74 AlgorithmIdentifier prf_algo;
75 BER_Decoder(kdf_algo.parameters())
78 .decode(N)
79 .decode(r)
80 .decode(p)
82 .end_cons();
83
84 if(key_length == 0) {
85 key_length = default_key_size;
86 }
87
88 secure_vector<uint8_t> derived_key(key_length);
89
90 auto pwdhash_fam = PasswordHashFamily::create_or_throw("Scrypt");
91 auto pwdhash = pwdhash_fam->from_params(N, r, p);
92 pwdhash->hash(derived_key, passphrase, salt);
93
94 return derived_key;
95 } else {
96 throw Decoding_Error(fmt("PBE-PKCS5 v2.0: Unknown KDF algorithm {}", kdf_algo.oid()));
97 }
98}
99
100secure_vector<uint8_t> derive_key(std::string_view passphrase,
101 std::string_view digest,
103 size_t* msec_in_iterations_out,
104 size_t iterations_if_msec_null,
105 size_t key_length,
106 bool include_key_length_in_struct,
107 AlgorithmIdentifier& kdf_algo) {
108 const size_t salt_len = 16;
109 const secure_vector<uint8_t> salt = rng.random_vec(salt_len);
110
111 if(digest == "Scrypt") {
112 auto pwhash_fam = PasswordHashFamily::create_or_throw("Scrypt");
113
114 std::unique_ptr<PasswordHash> pwhash;
115
116 if(msec_in_iterations_out != nullptr) {
117 const std::chrono::milliseconds msec(*msec_in_iterations_out);
118 pwhash = pwhash_fam->tune(key_length, msec);
119 } else {
120 pwhash = pwhash_fam->from_iterations(iterations_if_msec_null);
121 }
122
123 secure_vector<uint8_t> key(key_length);
124 pwhash->hash(key, passphrase, salt);
125
126 const size_t N = pwhash->memory_param();
127 const size_t r = pwhash->iterations();
128 const size_t p = pwhash->parallelism();
129
130 if(msec_in_iterations_out != nullptr) {
131 *msec_in_iterations_out = 0;
132 }
133
134 std::vector<uint8_t> scrypt_params;
135 DER_Encoder(scrypt_params)
138 .encode(N)
139 .encode(r)
140 .encode(p)
141 .encode_if(include_key_length_in_struct, key_length)
142 .end_cons();
143
144 kdf_algo = AlgorithmIdentifier(OID::from_string("Scrypt"), scrypt_params);
145 return key;
146 } else {
147 const std::string prf = fmt("HMAC({})", digest);
148 const std::string pbkdf_name = fmt("PBKDF2({})", prf);
149
150 auto pwhash_fam = PasswordHashFamily::create(pbkdf_name);
151 if(!pwhash_fam) {
152 throw Invalid_Argument(fmt("Unknown password hash digest {}", digest));
153 }
154
155 std::unique_ptr<PasswordHash> pwhash;
156
157 if(msec_in_iterations_out != nullptr) {
158 const std::chrono::milliseconds msec(*msec_in_iterations_out);
159 pwhash = pwhash_fam->tune(key_length, msec);
160 } else {
161 pwhash = pwhash_fam->from_iterations(iterations_if_msec_null);
162 }
163
164 secure_vector<uint8_t> key(key_length);
165 pwhash->hash(key, passphrase, salt);
166
167 std::vector<uint8_t> pbkdf2_params;
168
169 const size_t iterations = pwhash->iterations();
170
171 if(msec_in_iterations_out != nullptr) {
172 *msec_in_iterations_out = iterations;
173 }
174
175 DER_Encoder(pbkdf2_params)
178 .encode(iterations)
179 .encode_if(include_key_length_in_struct, key_length)
181 .end_cons();
182
183 kdf_algo = AlgorithmIdentifier("PKCS5.PBKDF2", pbkdf2_params);
184 return key;
185 }
186}
187
188/*
189* PKCS#5 v2.0 PBE Encryption
190*/
191std::pair<AlgorithmIdentifier, std::vector<uint8_t>> pbes2_encrypt_shared(std::span<const uint8_t> key_bits,
192 std::string_view passphrase,
193 size_t* msec_in_iterations_out,
194 size_t iterations_if_msec_null,
195 std::string_view cipher,
196 std::string_view prf,
199
200 const auto cipher_spec = split_on(cipher, '/');
201
202 if(cipher_spec.size() != 2 || !known_pbes_cipher_mode(cipher_spec[1]) || !enc) {
203 throw Encoding_Error(fmt("PBE-PKCS5 v2.0: Invalid or unavailable cipher '{}'", cipher));
204 }
205
206 const size_t key_length = enc->key_spec().maximum_keylength();
207
208 const secure_vector<uint8_t> iv = rng.random_vec(enc->default_nonce_length());
209
210 AlgorithmIdentifier kdf_algo;
211
212 const bool include_key_length_in_struct = enc->key_spec().minimum_keylength() != enc->key_spec().maximum_keylength();
213
214 const auto derived_key = derive_key(passphrase,
215 prf,
216 rng,
217 msec_in_iterations_out,
218 iterations_if_msec_null,
219 key_length,
220 include_key_length_in_struct,
221 kdf_algo);
222
223 enc->set_key(derived_key);
224 enc->start(iv);
225 secure_vector<uint8_t> ctext(key_bits.begin(), key_bits.end());
226 enc->finish(ctext);
227
228 std::vector<uint8_t> encoded_iv;
230
231 std::vector<uint8_t> pbes2_params;
232 DER_Encoder(pbes2_params)
234 .encode(kdf_algo)
235 .encode(AlgorithmIdentifier(cipher, encoded_iv))
236 .end_cons();
237
238 AlgorithmIdentifier id(OID::from_string("PBE-PKCS5v20"), pbes2_params);
239
240 return std::make_pair(id, unlock(ctext));
241}
242
243} // namespace
244
245std::pair<AlgorithmIdentifier, std::vector<uint8_t>> pbes2_encrypt(std::span<const uint8_t> key_bits,
246 std::string_view passphrase,
247 std::chrono::milliseconds msec,
248 std::string_view cipher,
249 std::string_view digest,
251 size_t msec_in_iterations_out = static_cast<size_t>(msec.count());
252 return pbes2_encrypt_shared(key_bits, passphrase, &msec_in_iterations_out, 0, cipher, digest, rng);
253 // return value msec_in_iterations_out discarded
254}
255
256std::pair<AlgorithmIdentifier, std::vector<uint8_t>> pbes2_encrypt_msec(std::span<const uint8_t> key_bits,
257 std::string_view passphrase,
258 std::chrono::milliseconds msec,
259 size_t* out_iterations_if_nonnull,
260 std::string_view cipher,
261 std::string_view digest,
263 size_t msec_in_iterations_out = static_cast<size_t>(msec.count());
264
265 auto ret = pbes2_encrypt_shared(key_bits, passphrase, &msec_in_iterations_out, 0, cipher, digest, rng);
266
267 if(out_iterations_if_nonnull != nullptr) {
268 *out_iterations_if_nonnull = msec_in_iterations_out;
269 }
270
271 return ret;
272}
273
274std::pair<AlgorithmIdentifier, std::vector<uint8_t>> pbes2_encrypt_iter(std::span<const uint8_t> key_bits,
275 std::string_view passphrase,
276 size_t pbkdf_iter,
277 std::string_view cipher,
278 std::string_view digest,
280 return pbes2_encrypt_shared(key_bits, passphrase, nullptr, pbkdf_iter, cipher, digest, rng);
281}
282
283secure_vector<uint8_t> pbes2_decrypt(std::span<const uint8_t> key_bits,
284 std::string_view passphrase,
285 const std::vector<uint8_t>& params) {
286 AlgorithmIdentifier kdf_algo;
287 AlgorithmIdentifier enc_algo;
288
289 BER_Decoder(params).start_sequence().decode(kdf_algo).decode(enc_algo).end_cons();
290
291 const std::string cipher = enc_algo.oid().human_name_or_empty();
292 const auto cipher_spec = split_on(cipher, '/');
293 if(cipher_spec.size() != 2 || !known_pbes_cipher_mode(cipher_spec[1])) {
294 throw Decoding_Error(fmt("PBE-PKCS5 v2.0: Unknown/invalid cipher OID {}", enc_algo.oid()));
295 }
296
299
301 if(!dec) {
302 throw Decoding_Error(fmt("PBE-PKCS5 cannot decrypt no cipher '{}'", cipher));
303 }
304
305 dec->set_key(derive_key(passphrase, kdf_algo, dec->key_spec().maximum_keylength()));
306
307 dec->start(iv);
308
309 secure_vector<uint8_t> buf(key_bits.begin(), key_bits.end());
310 dec->finish(buf);
311
312 return buf;
313}
314
315} // namespace Botan
const std::vector< uint8_t > & parameters() const
Definition asn1_obj.h:481
const OID & oid() const
Definition asn1_obj.h:479
BER_Decoder & decode(bool &out)
Definition ber_dec.h:188
BER_Decoder & verify_end()
Definition ber_dec.cpp:214
BER_Decoder & end_cons()
Definition ber_dec.cpp:312
BER_Decoder start_sequence()
Definition ber_dec.h:125
BER_Decoder & decode_optional(T &out, ASN1_Type type_tag, ASN1_Class class_tag, const T &default_value=T())
Definition ber_dec.h:253
static std::unique_ptr< Cipher_Mode > create(std::string_view algo, Cipher_Dir direction, std::string_view provider="")
DER_Encoder & start_sequence()
Definition der_enc.h:65
DER_Encoder & encode_if(bool pred, DER_Encoder &enc)
Definition der_enc.h:156
DER_Encoder & end_cons()
Definition der_enc.cpp:173
DER_Encoder & encode(bool b)
Definition der_enc.cpp:252
std::string human_name_or_empty() const
Definition asn1_oid.cpp:147
static OID from_string(std::string_view str)
Definition asn1_oid.cpp:86
static std::unique_ptr< PasswordHashFamily > create_or_throw(std::string_view algo_spec, std::string_view provider="")
Definition pwdhash.cpp:110
static std::unique_ptr< PasswordHashFamily > create(std::string_view algo_spec, std::string_view provider="")
Definition pwdhash.cpp:54
BOTAN_FORCE_INLINE BOTAN_FN_ISA_AES void enc(uint8x16_t &B, uint8x16_t K)
Definition aes_armv8.cpp:21
std::string fmt(std::string_view format, const T &... args)
Definition fmt.h:53
std::vector< std::string > split_on(std::string_view str, char delim)
Definition parsing.cpp:111
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:274
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:283
std::vector< T > unlock(const secure_vector< T > &in)
Definition secmem.h:86
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:256
std::vector< T, secure_allocator< T > > secure_vector
Definition secmem.h:69
std::pair< AlgorithmIdentifier, std::vector< uint8_t > > pbes2_encrypt(std::span< const uint8_t > key_bits, std::string_view passphrase, std::chrono::milliseconds msec, std::string_view cipher, std::string_view digest, RandomNumberGenerator &rng)
Definition pbes2.cpp:245