Skip to content

Commit

Permalink
Add KDF::derive_key<len>() producing a std::array<>
Browse files Browse the repository at this point in the history
  • Loading branch information
reneme committed Dec 3, 2024
1 parent cab79aa commit 9100a55
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
49 changes: 49 additions & 0 deletions src/lib/kdf/kdf.h
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,55 @@ class BOTAN_PUBLIC_API(2, 0) KDF {
{cast_char_ptr_to_uint8(label.data()), label.length()});
}

/**
* Derive a key
* @tparam key_len the desired output length in bytes
* @param secret the secret input
* @param salt a diversifier
* @param label purpose for the derived keying material
* @return the derived key
*/
template <size_t key_len>
std::array<uint8_t, key_len> derive_key(std::span<const uint8_t> secret,
std::span<const uint8_t> salt = {},
std::span<const uint8_t> label = {}) {
std::array<uint8_t, key_len> key;
perform_kdf(key, secret, salt, label);
return key;
}

/**
* Derive a key
* @tparam key_len the desired output length in bytes
* @param secret the secret input
* @param salt a diversifier
* @param label purpose for the derived keying material
* @return the derived key
*/
template <size_t key_len>
std::array<uint8_t, key_len> derive_key(std::span<const uint8_t> secret,
std::span<const uint8_t> salt = {},
std::string_view label = "") {
return derive_key<key_len>(secret, salt, {cast_char_ptr_to_uint8(label.data()), label.size()});
}

/**
* Derive a key
* @tparam key_len the desired output length in bytes
* @param secret the secret input
* @param salt a diversifier
* @param label purpose for the derived keying material
* @return the derived key
*/
template <size_t key_len>
std::array<uint8_t, key_len> derive_key(std::span<const uint8_t> secret,
std::string_view salt = "",
std::string_view label = "") {
return derive_key<key_len>(secret,
{cast_char_ptr_to_uint8(salt.data()), salt.size()},
{cast_char_ptr_to_uint8(label.data()), label.size()});
}

/**
* @return new object representing the same algorithm as *this
*/
Expand Down
5 changes: 5 additions & 0 deletions src/tests/test_kdf.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,11 @@ class KDF_KAT_Tests final : public Text_Based_Test {
result.test_eq("name", kdf->name(), kdf_name);
result.test_eq("derived key", kdf->derive_key(expected.size(), secret, salt, label), expected);

if(expected.size() == 32) {
const auto key = kdf->derive_key<32>(secret, salt, label);
result.test_eq("derived key as array", Botan::secure_vector<uint8_t>{key.begin(), key.end()}, expected);
}

// Test that clone works
auto clone = kdf->new_object();
result.confirm("Clone has different pointer", kdf.get() != clone.get());
Expand Down

0 comments on commit 9100a55

Please sign in to comment.