diff --git a/include/Void/Crypto/Crypto.hpp b/include/Void/Crypto/Crypto.hpp index 0b990c6..f9a5405 100644 --- a/include/Void/Crypto/Crypto.hpp +++ b/include/Void/Crypto/Crypto.hpp @@ -5,6 +5,7 @@ #include #include +#include #include #include #include @@ -195,6 +196,19 @@ namespace Void::Crypto std::span signature, const ProviderOptions& provider = {}); + /// Compute HMAC-SHA-1 (RFC 2104) into a caller-owned 20-byte buffer. + /// Wipes output on backend failure and rejects overlapping buffers. + [[nodiscard]] Void::Result::Result + hmac_sha1_into(std::span secret_key, + std::span message, + std::span output, + const ProviderOptions& provider = {}); + + [[nodiscard]] Void::Result::Result + hmac_sha1(std::span secret_key, + std::span message, + const ProviderOptions& provider = {}); + /// Compute HMAC-SHA-256 into a caller-owned 32-byte buffer. /// Wipes output on backend failure and rejects overlapping buffers. [[nodiscard]] Void::Result::Result @@ -208,6 +222,25 @@ namespace Void::Crypto std::span message, const ProviderOptions& provider = {}); + /// Derive key material with RFC 8018 PBKDF2-HMAC-SHA-256 into a + /// caller-owned buffer. iterations must be 1..kMaxPbkdf2Iterations, salt + /// at most kMaxPbkdf2SaltBytes and output 1..kMaxPbkdf2OutputBytes. + /// Rejects overlapping buffers and wipes output on any failure after + /// validation. + [[nodiscard]] Void::Result::Result + pbkdf2_hmac_sha256_into(std::span password, + std::span salt, + std::uint32_t iterations, + std::span output, + const ProviderOptions& provider = {}); + + [[nodiscard]] Void::Result::Result + pbkdf2_hmac_sha256(std::span password, + std::span salt, + std::uint32_t iterations, + std::size_t output_length, + const ProviderOptions& provider = {}); + /// Derive key material with RFC 5869 HKDF-SHA-256 into a caller-owned /// buffer (1..CryptoLimits::kMaxHkdfOutputBytes). Rejects overlapping /// buffers and wipes secret_output on any failure after validation. diff --git a/include/Void/Crypto/Types.hpp b/include/Void/Crypto/Types.hpp index b78458b..f87c9db 100644 --- a/include/Void/Crypto/Types.hpp +++ b/include/Void/Crypto/Types.hpp @@ -16,12 +16,16 @@ namespace Void::Crypto inline constexpr std::size_t Ed25519PublicKeySize = 32; inline constexpr std::size_t Ed25519SignatureSize = 64; inline constexpr std::size_t Ed25519SeedSize = 32; + inline constexpr std::size_t HmacSha1Size = 20; inline constexpr std::size_t HmacSha256Size = 32; struct CryptoLimits { static constexpr std::size_t kMaxOneShotMessageBytes = 16ULL * 1024ULL * 1024ULL; static constexpr std::size_t kMaxHkdfOutputBytes = 4ULL * 1024ULL; + static constexpr std::uint32_t kMaxPbkdf2Iterations = 10'000'000U; + static constexpr std::size_t kMaxPbkdf2SaltBytes = 64ULL * 1024ULL; + static constexpr std::size_t kMaxPbkdf2OutputBytes = 1024ULL; static constexpr std::size_t kStreamChunkBytes = 64ULL * 1024ULL; static constexpr std::size_t kDefaultMaxConcurrentFileHashes = 8; static constexpr std::size_t kDefaultMaxWaitingFileHashes = 32; @@ -256,7 +260,8 @@ namespace Void::Crypto ed25519_sign, ed25519_verify, hmac, - hkdf + hkdf, + pbkdf2 }; struct FaultConfig { diff --git a/src/Crypto/BuiltinHash.cpp b/src/Crypto/BuiltinHash.cpp index 83d1101..492ab09 100644 --- a/src/Crypto/BuiltinHash.cpp +++ b/src/Crypto/BuiltinHash.cpp @@ -789,6 +789,46 @@ namespace Void::Crypto::Detail return out; } + void builtin_hmac_sha1(std::span secret_key, + std::span message, + std::span output_20) noexcept + { + std::array key_block{}; + if (secret_key.size() > 64) { + Sha1State kh; + kh.update(secret_key); + kh.finalize_into(std::span{key_block}.subspan(0, 20)); + } else if (!secret_key.empty()) { + std::memcpy(key_block.data(), secret_key.data(), secret_key.size()); + } + + std::array ipad{}; + std::array opad{}; + for (std::size_t i = 0; i < 64; ++i) { + ipad[i] = key_block[i] ^ std::byte{0x36}; + opad[i] = key_block[i] ^ std::byte{0x5C}; + } + + std::array inner_hash{}; + { + Sha1State inner; + inner.update(ipad); + inner.update(message); + inner.finalize_into(inner_hash); + } + { + Sha1State outer; + outer.update(opad); + outer.update(inner_hash); + outer.finalize_into(output_20); + } + + builtin_secure_wipe(key_block); + builtin_secure_wipe(ipad); + builtin_secure_wipe(opad); + builtin_secure_wipe(inner_hash); + } + void builtin_hmac_sha256(std::span secret_key, std::span message, std::span output_32) noexcept @@ -892,4 +932,95 @@ namespace Void::Crypto::Detail builtin_secure_wipe(t); } + void builtin_pbkdf2_hmac_sha256(std::span password, + std::span salt, + std::uint32_t iterations, + std::span secret_output) noexcept + { + std::array key_block{}; + if (password.size() > 64) { + Sha256State kh; + kh.update(password); + kh.finalize_into(std::span{key_block}.subspan(0, 32)); + } else if (!password.empty()) { + std::memcpy(key_block.data(), password.data(), password.size()); + } + + std::array ipad{}; + std::array opad{}; + for (std::size_t i = 0; i < 64; ++i) { + ipad[i] = key_block[i] ^ std::byte{0x36}; + opad[i] = key_block[i] ^ std::byte{0x5C}; + } + + auto hmac = [&ipad, &opad](std::span data, + std::span out) noexcept { + std::array inner_hash{}; + { + Sha256State inner; + inner.update(ipad); + inner.update(data); + inner.finalize_into(inner_hash); + } + { + Sha256State outer; + outer.update(opad); + outer.update(inner_hash); + outer.finalize_into(out); + } + builtin_secure_wipe(inner_hash); + }; + + // Callers cap the output length, so this cannot overflow. + const std::size_t blocks = (secret_output.size() + 31) / 32; + std::size_t written = 0; + for (std::size_t block = 1; block <= blocks; ++block) { + std::array counter{}; + store_be32(counter.data(), static_cast(block)); + + std::array u{}; + { + std::array inner_hash{}; + { + Sha256State inner; + inner.update(ipad); + inner.update(salt); + inner.update(counter); + inner.finalize_into(inner_hash); + } + { + Sha256State outer; + outer.update(opad); + outer.update(inner_hash); + outer.finalize_into(u); + } + builtin_secure_wipe(inner_hash); + } + + std::array t = u; + for (std::uint32_t iteration = 1; iteration < iterations; + ++iteration) { + std::array next{}; + hmac(u, next); + u = next; + for (std::size_t i = 0; i < t.size(); ++i) { + t[i] ^= u[i]; + } + builtin_secure_wipe(next); + } + + const std::size_t copy_n = + std::min(32, secret_output.size() - written); + std::memcpy(secret_output.data() + written, t.data(), copy_n); + written += copy_n; + + builtin_secure_wipe(u); + builtin_secure_wipe(t); + } + + builtin_secure_wipe(key_block); + builtin_secure_wipe(ipad); + builtin_secure_wipe(opad); + } + } // namespace Void::Crypto::Detail diff --git a/src/Crypto/BuiltinHash.hpp b/src/Crypto/BuiltinHash.hpp index fe86865..e7ff7bc 100644 --- a/src/Crypto/BuiltinHash.hpp +++ b/src/Crypto/BuiltinHash.hpp @@ -4,6 +4,7 @@ #include #include +#include #include namespace Void::Crypto::Detail @@ -37,10 +38,19 @@ namespace Void::Crypto::Detail void destroy() noexcept; }; + void builtin_hmac_sha1(std::span secret_key, + std::span message, + std::span output_20) noexcept; + void builtin_hmac_sha256(std::span secret_key, std::span message, std::span output_32) noexcept; + void builtin_pbkdf2_hmac_sha256(std::span password, + std::span salt, + std::uint32_t iterations, + std::span secret_output) noexcept; + void builtin_hkdf_sha256(std::span secret_input, std::span salt, std::span context, diff --git a/src/Crypto/Crypto.cpp b/src/Crypto/Crypto.cpp index 55bd6e6..04627de 100644 --- a/src/Crypto/Crypto.cpp +++ b/src/Crypto/Crypto.cpp @@ -220,6 +220,135 @@ namespace Void::Crypto return std::unexpected{make_crypto_error( CryptoErrorCode::unsupported_algorithm, "Crypto::verifyEd25519: built without OpenSSL backend")}; +#endif + } + + [[maybe_unused]] [[nodiscard]] const char* + hmac_digest_name(HashAlgorithm algorithm) noexcept + { + switch (algorithm) { + case HashAlgorithm::Sha1: + return "SHA1"; + case HashAlgorithm::Sha256: + return "SHA256"; + default: + return nullptr; + } + } + + [[nodiscard]] Void::Result::Result + hmac_into_impl(HashAlgorithm algorithm, + std::span secret_key, + std::span message, + std::span output, + const ProviderOptions& provider, + std::string_view operation) + { + const std::size_t expected_size = algorithm == HashAlgorithm::Sha1 + ? HmacSha1Size + : HmacSha256Size; + if (output.size() != expected_size) { + return std::unexpected{ + make_crypto_error(CryptoErrorCode::invalid_argument, + std::format("{}: output must be {} bytes", + operation, expected_size))}; + } + if (spans_overlap(secret_key, output) || + spans_overlap(message, output)) { + return std::unexpected{make_crypto_error( + CryptoErrorCode::overlapping_buffers, + std::format("{}: output buffer overlaps input", + operation))}; + } + if (auto fault = + maybe_inject_fault(FaultOperation::hmac, operation); + fault.has_value()) { + secure_wipe(output); + return std::unexpected{std::move(*fault)}; + } + + if (use_builtin_hash(algorithm, provider)) { + if (!provider.property_query.empty()) { + secure_wipe(output); + return std::unexpected{make_crypto_error( + CryptoErrorCode::provider_error, + std::format("{}: property_query unavailable on " + "built-in backend", + operation))}; + } + if (algorithm == HashAlgorithm::Sha1) { + Detail::builtin_hmac_sha1(secret_key, message, output); + } else { + Detail::builtin_hmac_sha256(secret_key, message, output); + } + return {}; + } + +#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL + const char* name = hmac_digest_name(algorithm); + if (name == nullptr) { + secure_wipe(output); + return std::unexpected{make_crypto_error( + CryptoErrorCode::unsupported_algorithm, + std::format("{}: unsupported HMAC algorithm", operation))}; + } + ERR_clear_error(); + EvpMacPtr mac{ + EVP_MAC_fetch(nullptr, "HMAC", propq_or_null(provider)), + &EVP_MAC_free}; + if (!mac) { + secure_wipe(output); + return std::unexpected{make_openssl_error( + CryptoErrorCode::provider_error, + std::format("{}: EVP_MAC_fetch failed", operation))}; + } + EvpMacCtxPtr ctx{EVP_MAC_CTX_new(mac.get()), &EVP_MAC_CTX_free}; + if (!ctx) { + secure_wipe(output); + return std::unexpected{make_openssl_error( + CryptoErrorCode::backend_error, + std::format("{}: EVP_MAC_CTX_new failed", operation))}; + } + + std::array digest_name{}; + std::strncpy(digest_name.data(), name, digest_name.size() - 1); + std::array params = { + OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST, + digest_name.data(), 0), + OSSL_PARAM_construct_end(), + }; + + if (EVP_MAC_init(ctx.get(), non_null_bytes(secret_key), + secret_key.size(), params.data()) != 1) { + secure_wipe(output); + return std::unexpected{make_openssl_error( + CryptoErrorCode::provider_error, + std::format("{}: EVP_MAC_init failed", operation))}; + } + if (!message.empty() && + EVP_MAC_update(ctx.get(), non_null_bytes(message), + message.size()) != 1) { + secure_wipe(output); + return std::unexpected{make_openssl_error( + CryptoErrorCode::backend_error, + std::format("{}: EVP_MAC_update failed", operation))}; + } + std::size_t out_len = 0; + if (EVP_MAC_final(ctx.get(), + reinterpret_cast(output.data()), + &out_len, output.size()) != 1 || + out_len != expected_size) { + secure_wipe(output); + return std::unexpected{make_openssl_error( + CryptoErrorCode::backend_error, + std::format("{}: EVP_MAC_final failed", operation))}; + } + return {}; +#else + secure_wipe(output); + return std::unexpected{make_crypto_error( + CryptoErrorCode::backend_error, + std::format("{}: OpenSSL backend unavailable", operation))}; #endif } } // namespace @@ -939,26 +1068,98 @@ namespace Void::Crypto provider); } + Void::Result::Result + hmac_sha1_into(std::span secret_key, + std::span + message, + std::span + output, + const ProviderOptions& provider) + { + return hmac_into_impl(HashAlgorithm::Sha1, secret_key, message, output, + provider, "Crypto::hmac_sha1_into"); + } + + Void::Result::Result + hmac_sha1(std::span secret_key, + std::span + message, + const ProviderOptions& provider) + { + Digest out(HmacSha1Size); + if (auto res = hmac_sha1_into(secret_key, message, out, provider); + !res.has_value()) { + secure_wipe(out); + return std::unexpected{std::move(res.error())}; + } + return out; + } + Void::Result::Result hmac_sha256_into(std::span secret_key, std::span message, std::span output, const ProviderOptions& provider) { - if (output.size() != HmacSha256Size) { + return hmac_into_impl(HashAlgorithm::Sha256, secret_key, message, + output, provider, "Crypto::hmac_sha256_into"); + } + + Void::Result::Result hmac_sha256(std::span secret_key, + std::span message, + const ProviderOptions& provider) + { + Digest out(HmacSha256Size); + if (auto res = hmac_sha256_into(secret_key, message, out, provider); + !res.has_value()) { + secure_wipe(out); + return std::unexpected{std::move(res.error())}; + } + return out; + } + + Void::Result::Result + pbkdf2_hmac_sha256_into(std::span password, + std::span salt, + std::uint32_t iterations, + std::span output, + const ProviderOptions& provider) + { + if (iterations == 0 || + iterations > CryptoLimits::kMaxPbkdf2Iterations) { return std::unexpected{make_crypto_error( CryptoErrorCode::invalid_argument, - std::format("Crypto::hmac_sha256_into: output must be {} bytes", - HmacSha256Size))}; + std::format("Crypto::pbkdf2_hmac_sha256: iterations must be " + "1..{}", + CryptoLimits::kMaxPbkdf2Iterations))}; } - if (spans_overlap(secret_key, output) || - spans_overlap(message, output)) { + if (salt.size() > CryptoLimits::kMaxPbkdf2SaltBytes) { + return std::unexpected{make_crypto_error( + CryptoErrorCode::message_too_large, + std::format("Crypto::pbkdf2_hmac_sha256: salt exceeds {} byte " + "cap", + CryptoLimits::kMaxPbkdf2SaltBytes))}; + } + if (output.empty()) { + return std::unexpected{make_crypto_error( + CryptoErrorCode::invalid_argument, + "Crypto::pbkdf2_hmac_sha256: output buffer must be non-empty")}; + } + if (output.size() > CryptoLimits::kMaxPbkdf2OutputBytes) { + return std::unexpected{make_crypto_error( + CryptoErrorCode::output_too_large, + std::format( + "Crypto::pbkdf2_hmac_sha256: output size exceeds {} byte " + "cap", + CryptoLimits::kMaxPbkdf2OutputBytes))}; + } + if (spans_overlap(password, output) || spans_overlap(salt, output)) { return std::unexpected{make_crypto_error( CryptoErrorCode::overlapping_buffers, - "Crypto::hmac_sha256_into: output buffer overlaps input")}; + "Crypto::pbkdf2_hmac_sha256: output buffer overlaps input")}; } - if (auto fault = maybe_inject_fault(FaultOperation::hmac, - "Crypto::hmac_sha256_into"); + if (auto fault = maybe_inject_fault(FaultOperation::pbkdf2, + "Crypto::pbkdf2_hmac_sha256"); fault.has_value()) { secure_wipe(output); return std::unexpected{std::move(*fault)}; @@ -969,78 +1170,83 @@ namespace Void::Crypto secure_wipe(output); return std::unexpected{make_crypto_error( CryptoErrorCode::provider_error, - "Crypto::hmac_sha256_into: property_query unavailable on " + "Crypto::pbkdf2_hmac_sha256: property_query unavailable on " "built-in backend")}; } - Detail::builtin_hmac_sha256(secret_key, message, output); + Detail::builtin_pbkdf2_hmac_sha256(password, salt, iterations, + output); return {}; } #if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL ERR_clear_error(); - EvpMacPtr mac{EVP_MAC_fetch(nullptr, "HMAC", propq_or_null(provider)), - &EVP_MAC_free}; - if (!mac) { + EvpKdfPtr kdf{EVP_KDF_fetch(nullptr, "PBKDF2", propq_or_null(provider)), + &EVP_KDF_free}; + if (!kdf) { secure_wipe(output); return std::unexpected{make_openssl_error( CryptoErrorCode::provider_error, - "Crypto::hmac_sha256_into: EVP_MAC_fetch failed")}; + "Crypto::pbkdf2_hmac_sha256: EVP_KDF_fetch failed")}; } - EvpMacCtxPtr ctx{EVP_MAC_CTX_new(mac.get()), &EVP_MAC_CTX_free}; + EvpKdfCtxPtr ctx{EVP_KDF_CTX_new(kdf.get()), &EVP_KDF_CTX_free}; if (!ctx) { secure_wipe(output); return std::unexpected{make_openssl_error( CryptoErrorCode::backend_error, - "Crypto::hmac_sha256_into: EVP_MAC_CTX_new failed")}; + "Crypto::pbkdf2_hmac_sha256: EVP_KDF_CTX_new failed")}; } char digest_name[] = "SHA256"; - std::array params = { - OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST, digest_name, + int iteration_count = static_cast(iterations); + std::array params = { + OSSL_PARAM_construct_utf8_string(OSSL_KDF_PARAM_DIGEST, digest_name, 0), + OSSL_PARAM_construct_octet_string( + OSSL_KDF_PARAM_PASSWORD, + const_cast(non_null_bytes(password)), + password.size()), + OSSL_PARAM_construct_octet_string( + OSSL_KDF_PARAM_SALT, + const_cast(non_null_bytes(salt)), salt.size()), + OSSL_PARAM_construct_int(OSSL_KDF_PARAM_ITER, &iteration_count), OSSL_PARAM_construct_end(), }; - if (EVP_MAC_init(ctx.get(), non_null_bytes(secret_key), - secret_key.size(), params.data()) != 1) { - secure_wipe(output); - return std::unexpected{make_openssl_error( - CryptoErrorCode::provider_error, - "Crypto::hmac_sha256_into: EVP_MAC_init failed")}; - } - if (!message.empty() && - EVP_MAC_update(ctx.get(), non_null_bytes(message), - message.size()) != 1) { + if (EVP_KDF_derive(ctx.get(), + reinterpret_cast(output.data()), + output.size(), params.data()) != 1) { secure_wipe(output); return std::unexpected{make_openssl_error( CryptoErrorCode::backend_error, - "Crypto::hmac_sha256_into: EVP_MAC_update failed")}; - } - std::size_t out_len = 0; - if (EVP_MAC_final(ctx.get(), - reinterpret_cast(output.data()), - &out_len, output.size()) != 1 || - out_len != HmacSha256Size) { - secure_wipe(output); - return std::unexpected{make_openssl_error( - CryptoErrorCode::backend_error, - "Crypto::hmac_sha256_into: EVP_MAC_final failed")}; + "Crypto::pbkdf2_hmac_sha256: EVP_KDF_derive failed")}; } return {}; #else secure_wipe(output); return std::unexpected{make_crypto_error( CryptoErrorCode::backend_error, - "Crypto::hmac_sha256_into: OpenSSL backend unavailable")}; + "Crypto::pbkdf2_hmac_sha256: OpenSSL backend unavailable")}; #endif } - Void::Result::Result hmac_sha256(std::span secret_key, - std::span message, - const ProviderOptions& provider) + Void::Result::Result + pbkdf2_hmac_sha256(std::span password, + std::span salt, + std::uint32_t iterations, + std::size_t output_length, + const ProviderOptions& provider) { - Digest out(HmacSha256Size); - if (auto res = hmac_sha256_into(secret_key, message, out, provider); + if (output_length > CryptoLimits::kMaxPbkdf2OutputBytes) { + return std::unexpected{make_crypto_error( + CryptoErrorCode::output_too_large, + std::format( + "Crypto::pbkdf2_hmac_sha256: output size exceeds {} byte " + "cap", + CryptoLimits::kMaxPbkdf2OutputBytes))}; + } + Digest out(output_length); + if (auto res = pbkdf2_hmac_sha256_into(password, salt, iterations, out, + provider); !res.has_value()) { secure_wipe(out); return std::unexpected{std::move(res.error())}; diff --git a/tests/standalone/Crypto/HmacPbkdf2.cpp b/tests/standalone/Crypto/HmacPbkdf2.cpp new file mode 100644 index 0000000..ba3b59e --- /dev/null +++ b/tests/standalone/Crypto/HmacPbkdf2.cpp @@ -0,0 +1,395 @@ +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace +{ + int hex_nibble(char c) + { + if (c >= '0' && c <= '9') { + return c - '0'; + } + if (c >= 'a' && c <= 'f') { + return c - 'a' + 10; + } + if (c >= 'A' && c <= 'F') { + return c - 'A' + 10; + } + return -1; + } + + std::vector from_hex(std::string_view hex) + { + Void::Testing::require(hex.size() % 2 == 0); + std::vector out; + out.reserve(hex.size() / 2); + for (std::size_t i = 0; i < hex.size(); i += 2) { + const int hi = hex_nibble(hex[i]); + const int lo = hex_nibble(hex[i + 1]); + Void::Testing::require(hi >= 0 && lo >= 0); + out.push_back(static_cast((hi << 4) | lo)); + } + return out; + } + + std::string to_hex(std::span data) + { + static constexpr char kHex[] = "0123456789abcdef"; + std::string out; + out.reserve(data.size() * 2); + for (const std::byte b : data) { + const auto v = static_cast(b); + out.push_back(kHex[v >> 4]); + out.push_back(kHex[v & 0x0F]); + } + return out; + } + + std::span as_bytes(std::string_view text) + { + return std::as_bytes(std::span{text.data(), text.size()}); + } + + std::string hotp(std::span secret, std::uint64_t counter, + int digits) + { + std::array message{}; + for (std::size_t i = 0; i < message.size(); ++i) { + message[message.size() - 1 - i] = + static_cast((counter >> (8 * i)) & 0xFFU); + } + auto mac = Void::Crypto::hmac_sha1(secret, message); + Void::Testing::require(mac.has_value()); + const auto offset = static_cast( + std::to_integer(mac->back()) & 0x0FU); + const std::uint32_t binary = + ((std::to_integer((*mac)[offset]) & 0x7FU) << 24U) | + ((std::to_integer((*mac)[offset + 1]) & 0xFFU) + << 16U) | + ((std::to_integer((*mac)[offset + 2]) & 0xFFU) + << 8U) | + (std::to_integer((*mac)[offset + 3]) & 0xFFU); + std::uint32_t modulus = 1; + for (int i = 0; i < digits; ++i) { + modulus *= 10U; + } + std::string code = std::to_string(binary % modulus); + while (code.size() < static_cast(digits)) { + code.insert(code.begin(), '0'); + } + return code; + } + + std::string totp(std::span secret, std::uint64_t unix_time, + int digits) + { + return hotp(secret, unix_time / 30U, digits); + } +} // namespace + +Void::Testing::Test crypto_hmac_sha1_rfc2202_vectors() +{ + using namespace Void::Crypto; + + const std::array macs = { + "b617318655057264e28bc0b6fb378c8ef146be00", + "effcdf6ae5eb2fa2d27416d5f184df9c259a7c79", + "125d7342b9ac11cd91a39af48aa17b4f63f175d3", + "4c9007f4026250c6bc8414f9bf50c86c2d7235da", + "aa4ae5e15272d00e95705637ce8a3b55ed402112", + "e8e99d0f45237d786d6bbaa7965c7808bbff1a91"}; + + const std::vector twenty_0b(20, std::byte{0x0b}); + const std::vector twenty_aa(20, std::byte{0xaa}); + const std::vector eighty_aa(80, std::byte{0xaa}); + const std::vector fifty_dd(50, std::byte{0xdd}); + const std::vector fifty_cd(50, std::byte{0xcd}); + const auto key4 = + from_hex("0102030405060708090a0b0c0d0e0f10111213141516171819"); + + // Keys/messages that are not pure hex are supplied directly. + struct RawVector { + std::span key; + std::span data; + std::string_view mac_hex; + }; + const std::array raw = {{ + {twenty_0b, as_bytes("Hi There"), macs[0]}, + {as_bytes("Jefe"), as_bytes("what do ya want for nothing?"), + macs[1]}, + {twenty_aa, fifty_dd, macs[2]}, + {key4, fifty_cd, macs[3]}, + {eighty_aa, + as_bytes("Test Using Larger Than Block-Size Key - Hash Key First"), + macs[4]}, + {eighty_aa, + as_bytes("Test Using Larger Than Block-Size Key and Larger Than One " + "Block-Size Data"), + macs[5]}, + }}; + + const ProviderOptions builtin{.prefer_builtin = true}; + for (const auto& vec : raw) { + for (const auto& opts : {ProviderOptions{}, builtin}) { + if (opts.prefer_builtin == false && !has_openssl_backend()) { + continue; + } + auto mac = hmac_sha1(vec.key, vec.data, opts); + Void::Testing::require(mac.has_value()); + Void::Testing::expect_eq(to_hex(*mac), std::string{vec.mac_hex}); + } + } +} + +Void::Testing::Test crypto_hmac_sha1_boundaries_and_guards() +{ + using namespace Void::Crypto; + + // Empty key and message are valid. + auto empty = hmac_sha1({}, {}); + Void::Testing::require(empty.has_value()); + Void::Testing::expect_eq(empty->size(), HmacSha1Size); + + // Wrong output size is rejected before touching the buffer. + std::array wrong_size{}; + auto bad_size = + hmac_sha1_into(as_bytes("key"), as_bytes("msg"), wrong_size); + Void::Testing::require(!bad_size.has_value()); + Void::Testing::expect_eq( + bad_size.error().code().value, + static_cast(CryptoErrorCode::invalid_argument)); + + // Overlapping input/output is rejected. + std::array shared{}; + shared.fill(std::byte{0x5A}); + auto overlap = hmac_sha1_into(std::span{shared}.subspan(0, 20), + std::span{shared}.subspan(20, 20), + std::span{shared}.subspan(0, 20)); + Void::Testing::require(!overlap.has_value()); + Void::Testing::expect_eq( + overlap.error().code().value, + static_cast(CryptoErrorCode::overlapping_buffers)); + + // Injected backend fault wipes the destination. + std::array wiped{}; + wiped.fill(std::byte{0xCC}); + { + ScopedFaultGuard fault{FaultConfig{FaultOperation::hmac, + CryptoErrorCode::provider_error, 0}}; + auto failed = hmac_sha1_into(as_bytes("key"), as_bytes("msg"), wiped); + Void::Testing::require(!failed.has_value()); + } + Void::Testing::expect( + std::all_of(wiped.begin(), wiped.end(), + [](std::byte b) { return b == std::byte{0}; })); + + // property_query is unavailable on the built-in backend. + ProviderOptions bad_provider{.property_query = "provider=none", + .prefer_builtin = true}; + auto unavailable = + hmac_sha1(as_bytes("key"), as_bytes("msg"), bad_provider); + Void::Testing::require(!unavailable.has_value()); + Void::Testing::expect_eq( + unavailable.error().code().value, + static_cast(CryptoErrorCode::provider_error)); +} + +Void::Testing::Test crypto_hotp_totp_rfc4226_6238_vectors() +{ + const auto secret = as_bytes("12345678901234567890"); + + // RFC 4226 Appendix D. + const std::array hotp_expected = { + "755224", "287082", "359152", "969429", "338314", + "254676", "287922", "162583", "399871", "520489"}; + for (std::uint64_t counter = 0; counter < hotp_expected.size(); ++counter) { + Void::Testing::expect_eq(hotp(secret, counter, 6), + std::string{hotp_expected[counter]}); + } + + // RFC 6238 Appendix B (SHA-1 rows, 8 digits). + struct TotpVector { + std::uint64_t time; + std::string_view code; + }; + const std::array totp_vectors = {{ + {59, "94287082"}, + {1111111109, "07081804"}, + {1111111111, "14050471"}, + {1234567890, "89005924"}, + {2000000000, "69279037"}, + {20000000000, "65353130"}, + }}; + for (const auto& vec : totp_vectors) { + Void::Testing::expect_eq(totp(secret, vec.time, 8), + std::string{vec.code}); + } +} + +Void::Testing::Test crypto_pbkdf2_hmac_sha256_rfc7914_vectors() +{ + using namespace Void::Crypto; + + const ProviderOptions builtin{.prefer_builtin = true}; + + // RFC 7914 section 11, first vector (c = 1, 64-byte output). + { + const auto expected = std::string{ + "55ac046e56e3089fec1691c22544b605f94185216dde0465e68b9d57c20dacbc" + "49ca9cccf179b645991664b39d77ef317c71b845b1e30bd509112041d3a19783"}; + for (const auto& opts : {ProviderOptions{}, builtin}) { + if (!opts.prefer_builtin && !has_openssl_backend()) { + continue; + } + auto derived = pbkdf2_hmac_sha256(as_bytes("passwd"), + as_bytes("salt"), 1, 64, opts); + Void::Testing::require(derived.has_value()); + Void::Testing::expect_eq(to_hex(*derived), expected); + } + } + + // RFC 7914 section 11, second vector (c = 80000, 64-byte output). + { + auto derived = pbkdf2_hmac_sha256(as_bytes("Password"), + as_bytes("NaCl"), 80000, 64); + Void::Testing::require(derived.has_value()); + Void::Testing::expect_eq( + to_hex(*derived), + std::string{ + "4ddcd8f60b98be21830cee5ef22701f9641a4418d04c0414aeff" + "08876b34ab56a1d425a1225833549adb841b51c9b3176a272bdebba1d0" + "78478f62b397f33c8d"}); + } +} + +Void::Testing::Test crypto_pbkdf2_hmac_sha256_boundaries_and_guards() +{ + using namespace Void::Crypto; + + const auto password = as_bytes("password"); + const auto salt = as_bytes("salt"); + + // Zero and oversized iteration counts are rejected. + for (const std::uint32_t iterations : + {0U, CryptoLimits::kMaxPbkdf2Iterations + 1U}) { + std::array out{}; + auto r = pbkdf2_hmac_sha256_into(password, salt, iterations, out); + Void::Testing::require(!r.has_value()); + Void::Testing::expect_eq( + r.error().code().value, + static_cast(CryptoErrorCode::invalid_argument)); + } + + // Oversized salt and output are rejected without mutating the output. + { + std::vector big_salt(CryptoLimits::kMaxPbkdf2SaltBytes + 1U, + std::byte{0x11}); + std::array out{}; + auto r = pbkdf2_hmac_sha256_into(password, big_salt, 1, out); + Void::Testing::require(!r.has_value()); + Void::Testing::expect_eq( + r.error().code().value, + static_cast(CryptoErrorCode::message_too_large)); + + std::vector big_out(CryptoLimits::kMaxPbkdf2OutputBytes + 1U, + std::byte{0x7A}); + auto r_big = pbkdf2_hmac_sha256_into(password, salt, 1, big_out); + Void::Testing::require(!r_big.has_value()); + Void::Testing::expect_eq( + r_big.error().code().value, + static_cast(CryptoErrorCode::output_too_large)); + Void::Testing::expect( + std::all_of(big_out.begin(), big_out.end(), + [](std::byte b) { return b == std::byte{0x7A}; })); + + std::span empty_out; + auto r_empty = pbkdf2_hmac_sha256_into(password, salt, 1, empty_out); + Void::Testing::require(!r_empty.has_value()); + Void::Testing::expect_eq( + r_empty.error().code().value, + static_cast(CryptoErrorCode::invalid_argument)); + + // The Digest overload rejects an overflowing length before allocating. + auto r_overflow = pbkdf2_hmac_sha256( + password, salt, 1, std::numeric_limits::max()); + Void::Testing::require(!r_overflow.has_value()); + Void::Testing::expect_eq( + r_overflow.error().code().value, + static_cast(CryptoErrorCode::output_too_large)); + } + + // Overlapping output is rejected. + { + std::array shared{}; + auto r = pbkdf2_hmac_sha256_into(std::span{shared}.subspan(0, 16), {}, + 1, std::span{shared}.subspan(8, 32)); + Void::Testing::require(!r.has_value()); + Void::Testing::expect_eq( + r.error().code().value, + static_cast(CryptoErrorCode::overlapping_buffers)); + } + + // Injected fault wipes the destination. + { + std::array wiped{}; + wiped.fill(std::byte{0xCC}); + { + ScopedFaultGuard fault{FaultConfig{ + FaultOperation::pbkdf2, CryptoErrorCode::provider_error, 0}}; + auto r = pbkdf2_hmac_sha256_into(password, salt, 1, wiped); + Void::Testing::require(!r.has_value()); + } + Void::Testing::expect( + std::all_of(wiped.begin(), wiped.end(), + [](std::byte b) { return b == std::byte{0}; })); + } + + // Empty password and salt are valid; match hashlib reference values. + { + const auto expected = std::string{ + "f7ce0b653d2d72a4108cf5abe912ffdd777616dbbb27a70e8204f3ae2d0f6fad"}; + for (const auto& opts : + {ProviderOptions{}, ProviderOptions{.prefer_builtin = true}}) { + if (!opts.prefer_builtin && !has_openssl_backend()) { + continue; + } + auto derived = pbkdf2_hmac_sha256({}, {}, 1, 32, opts); + Void::Testing::require(derived.has_value()); + Void::Testing::expect_eq(to_hex(*derived), expected); + } + } + + // Partial final block and built-in/backend parity. + { + auto odd = pbkdf2_hmac_sha256(password, salt, 2, 33); + Void::Testing::require(odd.has_value()); + Void::Testing::expect_eq(odd->size(), 33U); + auto prefix = pbkdf2_hmac_sha256(password, salt, 2, 32); + Void::Testing::require(prefix.has_value()); + Void::Testing::expect( + std::equal(prefix->begin(), prefix->end(), odd->begin())); + + auto builtin = pbkdf2_hmac_sha256( + password, salt, 2, 33, ProviderOptions{.prefer_builtin = true}); + Void::Testing::require(builtin.has_value()); + Void::Testing::expect_eq(*builtin, *odd); + + auto gitea = pbkdf2_hmac_sha256(as_bytes("password"), + as_bytes("somesalt"), 10000, 32); + Void::Testing::require(gitea.has_value()); + Void::Testing::expect_eq( + to_hex(*gitea), + std::string{"f47eaaf9fcacaf867696eaa1d205356d2d029bff08828a05d0dab" + "60b6e0c2de2"}); + } +}