From 9100a55cd0fa78689dbfbb8a0843558dbed95e31 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9=20Meusel?= Date: Tue, 3 Dec 2024 08:55:45 +0100 Subject: [PATCH] Add KDF::derive_key() producing a std::array<> --- src/lib/kdf/kdf.h | 49 ++++++++++++++++++++++++++++++++++++++++++ src/tests/test_kdf.cpp | 5 +++++ 2 files changed, 54 insertions(+) diff --git a/src/lib/kdf/kdf.h b/src/lib/kdf/kdf.h index e541c321bb..2be444d949 100644 --- a/src/lib/kdf/kdf.h +++ b/src/lib/kdf/kdf.h @@ -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 + std::array derive_key(std::span secret, + std::span salt = {}, + std::span label = {}) { + std::array 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 + std::array derive_key(std::span secret, + std::span salt = {}, + std::string_view label = "") { + return derive_key(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 + std::array derive_key(std::span secret, + std::string_view salt = "", + std::string_view label = "") { + return derive_key(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 */ diff --git a/src/tests/test_kdf.cpp b/src/tests/test_kdf.cpp index 35f5add8f8..b70c55cdf2 100644 --- a/src/tests/test_kdf.cpp +++ b/src/tests/test_kdf.cpp @@ -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{key.begin(), key.end()}, expected); + } + // Test that clone works auto clone = kdf->new_object(); result.confirm("Clone has different pointer", kdf.get() != clone.get());