Botan 3.14.1
Crypto and TLS for C&
pkcs12_kdf.cpp
Go to the documentation of this file.
1/*
2* PKCS12 KDF
3* (C) 2026 Damiano Mazzella
4*
5* Botan is released under the Simplified BSD License (see license.txt)
6*/
7
8#include <botan/internal/pkcs12_kdf.h>
9
10#include <botan/assert.h>
11#include <botan/exceptn.h>
12#include <botan/hash.h>
13#include <botan/mem_ops.h>
14#include <botan/internal/bit_ops.h>
15#include <botan/internal/charset.h>
16#include <botan/internal/fmt.h>
17#include <botan/internal/int_utils.h>
18#include <botan/internal/time_utils.h>
19#include <algorithm>
20#include <array>
21#include <limits>
22
23namespace Botan {
24
25namespace {
26
27/*
28* Repeat data into buf until buf is filled
29*/
30void copy_repeat(std::span<uint8_t> buf, std::span<const uint8_t> data) {
31 if(data.empty()) {
32 clear_mem(buf);
33 return;
34 }
35
36 size_t pos = 0;
37 while(pos < buf.size()) {
38 const size_t to_copy = std::min(data.size(), buf.size() - pos);
39 copy_mem(buf.subspan(pos, to_copy), data.first(to_copy));
40 pos += to_copy;
41 }
42}
43
44/*
45* Big-endian addition: block = (block + addend + 1) mod 2^(len*8)
46*/
47void bigendian_add_one(std::span<uint8_t> block, std::span<const uint8_t> addend) {
48 BOTAN_DEBUG_ASSERT(block.size() == addend.size());
49
50 uint16_t carry = 1;
51 for(size_t k = block.size(); k > 0; --k) {
52 carry += static_cast<uint16_t>(block[k - 1]) + static_cast<uint16_t>(addend[k - 1]);
53 block[k - 1] = static_cast<uint8_t>(carry & 0xFF);
54 carry >>= 8;
55 }
56}
57
58secure_vector<uint8_t> pkcs12_encode_password(std::string_view password) {
59 if(password.empty()) {
60 return secure_vector<uint8_t>({0, 0});
61 }
62
63 std::vector<uint8_t> ucs2 = utf8_to_ucs2(password);
64 secure_vector<uint8_t> result(ucs2.begin(), ucs2.end());
65 secure_scrub_memory(ucs2.data(), ucs2.size());
66 result.push_back(0);
67 result.push_back(0);
68 return result;
69}
70
71void pkcs12_kdf_with_hash(std::span<uint8_t> out,
72 std::span<const uint8_t> pwd_bytes,
73 std::span<const uint8_t> salt,
74 size_t iterations,
75 uint8_t id,
76 HashFunction& hash) {
77 if(iterations == 0) {
78 throw Invalid_Argument("PKCS12-KDF: Invalid iteration count");
79 }
80 if(id < 1 || id > 3) {
81 throw Invalid_Argument("PKCS12-KDF: Invalid id (must be 1=key, 2=IV, or 3=MAC)");
82 }
83
84 // Block size depends on hash algorithm (RFC 7292 uses the hash's block size as v)
85 const size_t v = hash.hash_block_size();
86 if(v == 0) {
87 throw Invalid_Argument(fmt("PKCS12-KDF does not support hash '{}': undefined block size", hash.name()));
88 }
89
90 if(out.empty()) {
91 return;
92 }
93
94 const size_t hash_len = hash.output_length();
95
96 const size_t pwd_len = pwd_bytes.size();
97 const size_t salt_len = salt.size();
98
99 // Round len up to a multiple of v, checking for overflow
100 const auto round_up_to_v = [v](size_t len) -> size_t {
101 return mul_or_throw(ceil_division(len, v), v, "PKCS12-KDF: input too large");
102 };
103
104 // Calculate sizes (must be multiple of v)
105 const size_t S_len = round_up_to_v(salt_len);
106 const size_t P_len = round_up_to_v(pwd_len);
107 const size_t I_len = add_or_throw(S_len, P_len, "PKCS12-KDF: input too large");
108
109 // Create D (diversifier): v bytes of id
110 secure_vector<uint8_t> D(v, id);
111
112 // Create I = S || P
113 secure_vector<uint8_t> I(I_len);
114 if(S_len > 0) {
115 copy_repeat(std::span{I}.first(S_len), salt);
116 }
117 if(P_len > 0) {
118 copy_repeat(std::span{I}.last(P_len), pwd_bytes);
119 }
120
121 secure_vector<uint8_t> A(hash_len);
123
124 size_t out_offset = 0;
125 while(out_offset < out.size()) {
126 // Compute A = H^iterations(D || I)
127 hash.update(D);
128 hash.update(I);
129 hash.final(A);
130
131 for(size_t iter = 1; iter < iterations; ++iter) {
132 hash.update(A);
133 hash.final(A);
134 }
135
136 // Copy to output
137 const size_t to_copy = std::min(hash_len, out.size() - out_offset);
138 copy_mem(out.subspan(out_offset, to_copy), std::span{A}.first(to_copy));
139 out_offset += to_copy;
140
141 // Update I for next block: B = A repeated to fill v bytes,
142 // then I_j = (I_j + B + 1) mod 2^(v*8)
143 copy_repeat(B, A);
144
145 for(size_t j = 0; j < I_len; j += v) {
146 bigendian_add_one(std::span{I}.subspan(j, v), B);
147 }
148 }
149}
150
151} // namespace
152
153void pkcs12_kdf(std::span<uint8_t> out,
154 std::span<const uint8_t> pwd_bytes,
155 std::span<const uint8_t> salt,
156 size_t iterations,
157 uint8_t id,
158 HashFunction& hash) {
159 pkcs12_kdf_with_hash(out, pwd_bytes, salt, iterations, id, hash);
160}
161
162PKCS12_KDF::PKCS12_KDF(std::unique_ptr<HashFunction> hash, uint8_t id, size_t iterations) :
163 m_hash(std::move(hash)), m_id(id), m_iterations(iterations) {
164 BOTAN_ARG_CHECK(m_hash != nullptr, "PKCS12-KDF: hash must not be null");
165 BOTAN_ARG_CHECK(m_iterations > 0, "PKCS12-KDF: iterations must be greater than zero");
166 BOTAN_ARG_CHECK(m_id >= 1 && m_id <= 3, "PKCS12-KDF: id must be 1 (key), 2 (IV), or 3 (MAC)");
167}
168
169std::string PKCS12_KDF::to_string() const {
170 return fmt("PKCS12-KDF({},{},{})", m_hash->name(), static_cast<unsigned>(m_id), m_iterations);
171}
172
173void PKCS12_KDF::derive_key(uint8_t out[],
174 size_t out_len,
175 const char* password,
176 size_t password_len,
177 const uint8_t salt[],
178 size_t salt_len) const {
179 const std::string_view pwd =
180 (password != nullptr && password_len > 0) ? std::string_view(password, password_len) : std::string_view{};
181 pkcs12_kdf_with_hash({out, out_len}, pkcs12_encode_password(pwd), {salt, salt_len}, m_iterations, m_id, *m_hash);
182}
183
184PKCS12_KDF_Family::PKCS12_KDF_Family(std::unique_ptr<HashFunction> hash, size_t id) :
185 m_hash(std::move(hash)), m_id(static_cast<uint8_t>(id)) {
186 BOTAN_ARG_CHECK(m_hash != nullptr, "PKCS12-KDF: hash must not be null");
187 BOTAN_ARG_CHECK(id >= 1 && id <= 3, "PKCS12-KDF: id must be 1 (key), 2 (IV), or 3 (MAC)");
188}
189
190std::string PKCS12_KDF_Family::name() const {
191 return fmt("PKCS12-KDF({},{})", m_hash->name(), static_cast<unsigned>(m_id));
192}
193
194std::unique_ptr<PasswordHash> PKCS12_KDF_Family::tune_params(size_t output_length,
195 uint64_t desired_msec,
196 std::optional<size_t> /*max_memory*/,
197 uint64_t tuning_msec) const {
198 // Benchmark the real KDF at a fixed iteration count and target output length,
199 // so the measurement captures hash(D || I), the full I-update carry loop, the
200 // inner A-rehash loop, and the per-output-block cost.
201 const size_t tuning_iterations = 10000;
202 const size_t tuning_out_len = std::max<size_t>(output_length, 1);
203 const std::array<uint8_t, 16> tuning_salt{};
204 const std::array<uint8_t, 16> tuning_pwd{};
205 const auto pwd_bytes =
206 pkcs12_encode_password(std::string_view(reinterpret_cast<const char*>(tuning_pwd.data()), tuning_pwd.size()));
207 std::vector<uint8_t> tuning_out(tuning_out_len);
208
209 auto tuning_hash = m_hash->new_object();
210 const uint64_t measured_nsec = measure_cost(tuning_msec, [&]() {
211 pkcs12_kdf_with_hash(tuning_out, pwd_bytes, tuning_salt, tuning_iterations, m_id, *tuning_hash);
212 });
213
214 // Scale: one benchmark sample = tuning_iterations iterations; target matches desired_msec.
215 const double measured = std::max<double>(1.0, static_cast<double>(measured_nsec));
216 const double desired = static_cast<double>(desired_msec) * 1'000'000.0;
217 const double est = (desired * static_cast<double>(tuning_iterations)) / measured;
218 const double est_clamped = std::clamp(est, 1.0, static_cast<double>(std::numeric_limits<size_t>::max()));
219 const size_t iterations = static_cast<size_t>(est_clamped);
220
221 return std::make_unique<PKCS12_KDF>(m_hash->new_object(), m_id, iterations);
222}
223
224std::unique_ptr<PasswordHash> PKCS12_KDF_Family::default_params() const {
225 return std::make_unique<PKCS12_KDF>(m_hash->new_object(), m_id, 2048);
226}
227
228std::unique_ptr<PasswordHash> PKCS12_KDF_Family::from_iterations(size_t iterations) const {
229 return std::make_unique<PKCS12_KDF>(m_hash->new_object(), m_id, iterations);
230}
231
232std::unique_ptr<PasswordHash> PKCS12_KDF_Family::from_params(size_t i1, size_t /*i2*/, size_t /*i3*/) const {
233 return std::make_unique<PKCS12_KDF>(m_hash->new_object(), m_id, i1);
234}
235
236} // namespace Botan
#define BOTAN_DEBUG_ASSERT(expr)
Definition assert.h:136
#define BOTAN_ARG_CHECK(expr, msg)
Definition assert.h:33
std::string name() const override
std::unique_ptr< PasswordHash > from_params(size_t i1, size_t i2=0, size_t i3=0) const override
std::unique_ptr< PasswordHash > tune_params(size_t output_length, uint64_t desired_runtime_msec, std::optional< size_t > max_memory_usage_mb={}, uint64_t tuning_msec=10) const override
std::unique_ptr< PasswordHash > default_params() const override
std::unique_ptr< PasswordHash > from_iterations(size_t iterations) const override
PKCS12_KDF_Family(std::unique_ptr< HashFunction > hash, size_t id)
void derive_key(uint8_t out[], size_t out_len, const char *password, size_t password_len, const uint8_t salt[], size_t salt_len) const override
std::string to_string() const override
PKCS12_KDF(std::unique_ptr< HashFunction > hash, uint8_t id, size_t iterations)
size_t iterations() const override
Definition pkcs12_kdf.h:40
void hash(std::span< uint8_t > out, std::string_view password, std::span< const uint8_t > salt) const
Definition pwdhash.h:95
constexpr T add_or_throw(T a, T b, std::string_view msg)
Definition int_utils.h:66
constexpr T mul_or_throw(T a, T b, std::string_view msg)
Definition int_utils.h:81
std::string fmt(std::string_view format, const T &... args)
Definition fmt.h:53
BOTAN_FORCE_INLINE constexpr T ceil_division(T a, T b)
Definition bit_ops.h:167
constexpr void copy_mem(T *out, const T *in, size_t n)
Definition mem_ops.h:144
void secure_scrub_memory(void *ptr, size_t n)
Definition mem_utils.cpp:24
std::vector< T, secure_allocator< T > > secure_vector
Definition secmem.h:128
uint64_t measure_cost(uint64_t trial_msec, F func)
Definition time_utils.h:34
void pkcs12_kdf(std::span< uint8_t > out, std::span< const uint8_t > pwd_bytes, std::span< const uint8_t > salt, size_t iterations, uint8_t id, HashFunction &hash)
constexpr void clear_mem(T *ptr, size_t n)
Definition mem_ops.h:118
std::vector< uint8_t > utf8_to_ucs2(std::string_view utf8)
Definition charset.cpp:137