#include #include "BuiltinEd25519.hpp" #include "BuiltinHash.hpp" #include #include #include #include #include #include #include #include #include #include #if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL #include #include #include #include #include #include #endif namespace Void::Crypto { namespace { thread_local FaultConfig g_fault_config{}; thread_local std::size_t g_fault_hits{0}; [[nodiscard]] std::optional maybe_inject_fault(FaultOperation op, std::string_view operation) { if (g_fault_config.op == FaultOperation::none) { return std::nullopt; } if (g_fault_config.op != FaultOperation::any && g_fault_config.op != op) { return std::nullopt; } if (g_fault_hits < g_fault_config.fail_after) { ++g_fault_hits; return std::nullopt; } ++g_fault_hits; return make_crypto_error( g_fault_config.code, std::format("{}: injected crypto backend fault", operation)); } [[nodiscard]] bool spans_overlap(std::span a, std::span b) noexcept { if (a.empty() || b.empty()) { return false; } const auto a_begin = reinterpret_cast(a.data()); const auto a_end = a_begin + a.size(); const auto b_begin = reinterpret_cast(b.data()); const auto b_end = b_begin + b.size(); return a_begin < b_end && b_begin < a_end; } [[nodiscard]] bool use_builtin_hash( HashAlgorithm algorithm, const ProviderOptions& provider) noexcept { #if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL if (provider.prefer_builtin || algorithm == HashAlgorithm::Blake2b256) { return true; } return false; #else (void)algorithm; (void)provider; return true; #endif } #if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL [[nodiscard]] const char* algorithm_name(HashAlgorithm algorithm) noexcept { switch (algorithm) { case HashAlgorithm::Sha1: return "SHA1"; case HashAlgorithm::Sha256: return "SHA256"; case HashAlgorithm::Sha512: return "SHA512"; case HashAlgorithm::Blake2b256: return nullptr; case HashAlgorithm::Blake2b512: return "BLAKE2B512"; } return nullptr; } [[nodiscard]] const char* propq_or_null(const ProviderOptions& provider) noexcept { return provider.property_query.empty() ? nullptr : provider.property_query.c_str(); } [[nodiscard]] Void::Result::Error make_openssl_error(CryptoErrorCode code, std::string_view operation) { const unsigned long err_code = ERR_get_error(); ERR_clear_error(); if (err_code == 0) { return make_crypto_error(code, std::string{operation}); } std::array buffer{}; ERR_error_string_n(err_code, buffer.data(), buffer.size()); return make_crypto_error( code, std::format("{}: {}", operation, buffer.data())); } using EvpMdPtr = std::unique_ptr; using EvpMdCtxPtr = std::unique_ptr; using EvpPkeyPtr = std::unique_ptr; using EvpMacPtr = std::unique_ptr; using EvpMacCtxPtr = std::unique_ptr; using EvpKdfPtr = std::unique_ptr; using EvpKdfCtxPtr = std::unique_ptr; [[nodiscard]] const unsigned char* non_null_bytes(std::span span) noexcept { static constexpr unsigned char kEmptyByte = 0; return span.empty() ? &kEmptyByte : reinterpret_cast(span.data()); } #endif [[nodiscard]] Void::Result::Result verify_ed25519_impl(std::span message, std::span signature, std::span public_key, const ProviderOptions& provider) { if (signature.size() != Ed25519SignatureSize) { return std::unexpected{make_crypto_error( CryptoErrorCode::invalid_signature_size, std::format("Crypto::verifyEd25519: signature must be {} " "bytes", Ed25519SignatureSize))}; } if (public_key.size() != Ed25519PublicKeySize) { return std::unexpected{make_crypto_error( CryptoErrorCode::invalid_key_size, std::format("Crypto::verifyEd25519: public key must be {} " "bytes", Ed25519PublicKeySize))}; } if (message.size() > CryptoLimits::kMaxOneShotMessageBytes) { return std::unexpected{make_crypto_error( CryptoErrorCode::message_too_large, std::format("Crypto::verifyEd25519: message exceeds {} " "byte one-shot limit", CryptoLimits::kMaxOneShotMessageBytes))}; } if (auto fault = maybe_inject_fault(FaultOperation::ed25519_verify, "Crypto::verifyEd25519"); fault.has_value()) { return std::unexpected{std::move(*fault)}; } #if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL if (provider.prefer_builtin) { return std::unexpected{make_crypto_error( CryptoErrorCode::unsupported_algorithm, "Crypto::verifyEd25519: Ed25519 requires OpenSSL backend")}; } ERR_clear_error(); const char* propq = propq_or_null(provider); EvpPkeyPtr key{EVP_PKEY_new_raw_public_key_ex( nullptr, "ED25519", propq, non_null_bytes(public_key), public_key.size()), &EVP_PKEY_free}; if (!key) { const auto code = provider.property_query.empty() ? CryptoErrorCode::backend_error : CryptoErrorCode::provider_error; return std::unexpected{make_openssl_error( code, "Crypto::verifyEd25519: invalid public key or " "unavailable provider")}; } EvpMdCtxPtr context{EVP_MD_CTX_new(), &EVP_MD_CTX_free}; if (!context) { return std::unexpected{make_openssl_error( CryptoErrorCode::backend_error, "Crypto::verifyEd25519: EVP_MD_CTX_new failed")}; } if (EVP_DigestVerifyInit_ex(context.get(), nullptr, nullptr, nullptr, propq, key.get(), nullptr) != 1) { return std::unexpected{make_openssl_error( CryptoErrorCode::provider_error, "Crypto::verifyEd25519: initialization failed")}; } const int result = EVP_DigestVerify( context.get(), non_null_bytes(signature), signature.size(), non_null_bytes(message), message.size()); if (result < 0) { return std::unexpected{make_openssl_error( CryptoErrorCode::backend_error, "Crypto::verifyEd25519 failed")}; } ERR_clear_error(); return result == 1; #else (void)provider; return Detail::Ed25519::verify( reinterpret_cast(public_key.data()), reinterpret_cast(signature.data()), message); #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 bool has_openssl_backend() noexcept { #if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL return true; #else return false; #endif } void secure_wipe(std::span buffer) noexcept { #if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL if (!buffer.empty()) { OPENSSL_cleanse(buffer.data(), buffer.size()); } #else Detail::builtin_secure_wipe(buffer); #endif } bool constant_time_equal(std::span lhs, std::span rhs) noexcept { if (lhs.size() != rhs.size()) { return false; } if (lhs.empty()) { return true; } #if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL return CRYPTO_memcmp(lhs.data(), rhs.data(), lhs.size()) == 0; #else return Detail::builtin_constant_time_equal(lhs, rhs); #endif } ScopedFaultGuard::ScopedFaultGuard(FaultConfig config) noexcept : m_previous(g_fault_config), m_previous_hits(g_fault_hits) { g_fault_config = config; g_fault_hits = 0; } ScopedFaultGuard::~ScopedFaultGuard() noexcept { g_fault_config = m_previous; g_fault_hits = m_previous_hits; } struct Hasher::Impl { #if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL EvpMdCtxPtr context{nullptr, &EVP_MD_CTX_free}; EvpMdPtr algorithm{nullptr, &EVP_MD_free}; #endif Detail::BuiltinHasher builtin{}; bool using_builtin{false}; HasherState state{HasherState::Ready}; }; Hasher::Hasher(std::unique_ptr impl) noexcept : m_impl(std::move(impl)) { } Hasher::~Hasher() = default; Hasher::Hasher(Hasher&&) noexcept = default; Hasher& Hasher::operator=(Hasher&&) noexcept = default; HasherState Hasher::state() const noexcept { return m_impl ? m_impl->state : HasherState::MovedFrom; } Void::Result::Result Hasher::create(HashAlgorithm algorithm) { return create(algorithm, ProviderOptions{}); } Void::Result::Result Hasher::create(HashAlgorithm algorithm, const ProviderOptions& provider) { switch (algorithm) { case HashAlgorithm::Sha1: case HashAlgorithm::Sha256: case HashAlgorithm::Sha512: case HashAlgorithm::Blake2b256: case HashAlgorithm::Blake2b512: break; default: return std::unexpected{make_crypto_error( CryptoErrorCode::unsupported_algorithm, "Crypto::Hasher: unsupported algorithm")}; } if (auto fault = maybe_inject_fault(FaultOperation::hash_create, "Crypto::Hasher::create"); fault.has_value()) { return std::unexpected{std::move(*fault)}; } if (use_builtin_hash(algorithm, provider)) { if (!provider.property_query.empty()) { return std::unexpected{make_crypto_error( CryptoErrorCode::provider_error, "Crypto::Hasher: property_query unavailable on built-in " "backend")}; } auto impl = std::make_unique(); if (!impl->builtin.init(algorithm)) { return std::unexpected{make_crypto_error( CryptoErrorCode::backend_error, "Crypto::Hasher: built-in initialization failed")}; } impl->using_builtin = true; impl->state = HasherState::Ready; return Hasher{std::move(impl)}; } #if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL const char* md_name = algorithm_name(algorithm); if (md_name == nullptr) { return std::unexpected{make_crypto_error( CryptoErrorCode::unsupported_algorithm, "Crypto::Hasher: unsupported OpenSSL digest algorithm")}; } ERR_clear_error(); auto impl = std::make_unique(); impl->algorithm = EvpMdPtr{ EVP_MD_fetch(nullptr, md_name, propq_or_null(provider)), &EVP_MD_free}; if (!impl->algorithm) { return std::unexpected{make_openssl_error( CryptoErrorCode::provider_error, "Crypto::Hasher: EVP_MD_fetch failed")}; } impl->context = EvpMdCtxPtr{EVP_MD_CTX_new(), &EVP_MD_CTX_free}; if (!impl->context) { return std::unexpected{make_openssl_error( CryptoErrorCode::backend_error, "Crypto::Hasher: EVP_MD_CTX_new failed")}; } if (EVP_DigestInit_ex2(impl->context.get(), impl->algorithm.get(), nullptr) != 1) { return std::unexpected{make_openssl_error( CryptoErrorCode::provider_error, "Crypto::Hasher: digest initialization failed")}; } impl->using_builtin = false; impl->state = HasherState::Ready; return Hasher{std::move(impl)}; #else return std::unexpected{make_crypto_error( CryptoErrorCode::backend_error, "Crypto::Hasher: OpenSSL backend unavailable")}; #endif } Void::Result::Result Hasher::update(std::span data) { if (!m_impl) { return std::unexpected{make_crypto_error( CryptoErrorCode::invalid_state, "Crypto::Hasher::update: hasher is moved-from")}; } if (m_impl->state == HasherState::Finalized || m_impl->state == HasherState::Failed) { return std::unexpected{make_crypto_error( CryptoErrorCode::invalid_state, "Crypto::Hasher::update: hasher is finalized or failed")}; } if (auto fault = maybe_inject_fault(FaultOperation::hash_update, "Crypto::Hasher::update"); fault.has_value()) { m_impl->state = HasherState::Failed; return std::unexpected{std::move(*fault)}; } if (m_impl->using_builtin) { m_impl->builtin.update(data); m_impl->state = HasherState::Updating; return {}; } #if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL if (!data.empty() && EVP_DigestUpdate(m_impl->context.get(), data.data(), data.size()) != 1) { m_impl->state = HasherState::Failed; return std::unexpected{make_openssl_error( CryptoErrorCode::backend_error, "Crypto::Hasher::update failed")}; } m_impl->state = HasherState::Updating; return {}; #else m_impl->state = HasherState::Failed; return std::unexpected{make_crypto_error( CryptoErrorCode::backend_error, "Crypto::Hasher::update: invalid backend")}; #endif } Void::Result::Result Hasher::update(std::string_view data) { return update(std::as_bytes(std::span{data.data(), data.size()})); } Void::Result::Result Hasher::finalize() { if (!m_impl) { return std::unexpected{make_crypto_error( CryptoErrorCode::invalid_state, "Crypto::Hasher::finalize: hasher is moved-from")}; } if (m_impl->state == HasherState::Finalized || m_impl->state == HasherState::Failed) { return std::unexpected{make_crypto_error( CryptoErrorCode::invalid_state, "Crypto::Hasher::finalize: hasher is finalized or failed")}; } if (auto fault = maybe_inject_fault(FaultOperation::hash_finalize, "Crypto::Hasher::finalize"); fault.has_value()) { m_impl->state = HasherState::Failed; return std::unexpected{std::move(*fault)}; } if (m_impl->using_builtin) { Digest digest = m_impl->builtin.finalize(); m_impl->state = HasherState::Finalized; return digest; } #if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL const int digest_size = EVP_MD_get_size(m_impl->algorithm.get()); if (digest_size <= 0) { m_impl->state = HasherState::Failed; return std::unexpected{make_crypto_error( CryptoErrorCode::backend_error, "Crypto::Hasher::finalize: invalid digest size")}; } Digest digest(static_cast(digest_size)); unsigned int written = 0; if (EVP_DigestFinal_ex(m_impl->context.get(), reinterpret_cast(digest.data()), &written) != 1) { m_impl->state = HasherState::Failed; return std::unexpected{make_openssl_error( CryptoErrorCode::backend_error, "Crypto::Hasher::finalize failed")}; } m_impl->state = HasherState::Finalized; digest.resize(written); return digest; #else m_impl->state = HasherState::Failed; return std::unexpected{make_crypto_error( CryptoErrorCode::backend_error, "Crypto::Hasher::finalize: invalid backend")}; #endif } auto hash(HashAlgorithm algorithm, std::span data) -> Void::Result::Result { return hash(algorithm, data, ProviderOptions{}); } auto hash(HashAlgorithm algorithm, std::span data, const ProviderOptions& provider) -> Void::Result::Result { auto hasher = Hasher::create(algorithm, provider); if (!hasher) { return std::unexpected{hasher.error()}; } if (auto updated = hasher->update(data); !updated) { return std::unexpected{updated.error()}; } return hasher->finalize(); } auto hash(HashAlgorithm algorithm, std::string_view data) -> Void::Result::Result { return hash(algorithm, std::as_bytes(std::span{data.data(), data.size()})); } auto hashFile(HashAlgorithm algorithm, const std::filesystem::path& path) -> Void::Result::Result { return hash_file(algorithm, path, ProviderOptions{}); } auto hashFile(HashAlgorithm algorithm, const std::filesystem::path& path, const ProviderOptions& provider) -> Void::Result::Result { return hash_file(algorithm, path, provider); } auto hash_file(HashAlgorithm algorithm, const std::filesystem::path& path) -> Void::Result::Result { return hash_file(algorithm, path, ProviderOptions{}); } auto hash_file(HashAlgorithm algorithm, const std::filesystem::path& path, const ProviderOptions& provider) -> Void::Result::Result { std::ifstream input{path, std::ios::binary}; if (!input.is_open()) { return std::unexpected{make_crypto_error( CryptoErrorCode::io_error, std::format("Crypto::hash_file: cannot open '{}'", path.string()))}; } auto hasher = Hasher::create(algorithm, provider); if (!hasher) { return std::unexpected{hasher.error()}; } std::array buffer{}; while (input) { input.read(buffer.data(), static_cast(buffer.size())); const auto count = input.gcount(); if (count > 0) { const auto bytes = std::as_bytes( std::span{buffer.data(), static_cast(count)}); if (auto updated = hasher->update(bytes); !updated) { return std::unexpected{updated.error()}; } } } if (input.bad() || (!input.eof() && input.fail())) { return std::unexpected{make_crypto_error( CryptoErrorCode::io_error, std::format("Crypto::hash_file: I/O error reading '{}'", path.string()))}; } return hasher->finalize(); } Void::Result::Result sha1(std::span data) { return hash(HashAlgorithm::Sha1, data); } Void::Result::Result sha1(std::string_view data) { return hash(HashAlgorithm::Sha1, data); } Void::Result::Result sha256(std::span data) { return hash(HashAlgorithm::Sha256, data); } Void::Result::Result sha256(std::string_view data) { return hash(HashAlgorithm::Sha256, data); } Void::Result::Result sha512(std::span data) { return hash(HashAlgorithm::Sha512, data); } Void::Result::Result sha512(std::string_view data) { return hash(HashAlgorithm::Sha512, data); } Void::Result::Result blake2b256(std::span data) { return hash(HashAlgorithm::Blake2b256, data); } Void::Result::Result blake2b256(std::string_view data) { return hash(HashAlgorithm::Blake2b256, data); } Void::Result::Result blake2b512(std::span data) { return hash(HashAlgorithm::Blake2b512, data); } Void::Result::Result blake2b512(std::string_view data) { return hash(HashAlgorithm::Blake2b512, data); } Void::Result::Result sha1File(const std::filesystem::path& path) { return hash_file(HashAlgorithm::Sha1, path); } Void::Result::Result sha256File(const std::filesystem::path& path) { return hash_file(HashAlgorithm::Sha256, path); } Void::Result::Result sha512File(const std::filesystem::path& path) { return hash_file(HashAlgorithm::Sha512, path); } Void::Result::Result sha1_file(const std::filesystem::path& path) { return hash_file(HashAlgorithm::Sha1, path); } Void::Result::Result sha256_file(const std::filesystem::path& path) { return hash_file(HashAlgorithm::Sha256, path); } Void::Result::Result sha512_file(const std::filesystem::path& path) { return hash_file(HashAlgorithm::Sha512, path); } Void::Result::Result blake2b256_file(const std::filesystem::path& path) { return hash_file(HashAlgorithm::Blake2b256, path); } Void::Result::Result blake2b512_file(const std::filesystem::path& path) { return hash_file(HashAlgorithm::Blake2b512, path); } struct Ed25519PrivateKey::Impl { #if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL EvpPkeyPtr pkey{nullptr, &EVP_PKEY_free}; #else std::array seed{}; std::array public_key{}; #endif }; #if !defined(VOID_CRYPTO_HAS_OPENSSL) || !VOID_CRYPTO_HAS_OPENSSL namespace { void derive_ed25519_public_key( const std::array& seed, std::array& public_key) { Detail::Ed25519::Sha512 digest{}; Detail::Ed25519::expand_seed( reinterpret_cast(seed.data()), digest, reinterpret_cast(public_key.data())); Detail::Ed25519::wipe(digest); } } // namespace #endif Ed25519PrivateKey::Ed25519PrivateKey(std::unique_ptr impl) noexcept : m_impl(std::move(impl)) { } Ed25519PrivateKey::~Ed25519PrivateKey() = default; Ed25519PrivateKey::Ed25519PrivateKey(Ed25519PrivateKey&&) noexcept = default; Ed25519PrivateKey& Ed25519PrivateKey::operator=(Ed25519PrivateKey&&) noexcept = default; bool Ed25519PrivateKey::valid() const noexcept { #if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL return m_impl != nullptr && m_impl->pkey != nullptr; #else return m_impl != nullptr; #endif } Void::Result::Result Ed25519PrivateKey::generate(const ProviderOptions& provider) { if (auto fault = maybe_inject_fault(FaultOperation::ed25519_keygen, "Crypto::Ed25519PrivateKey::generate"); fault.has_value()) { return std::unexpected{std::move(*fault)}; } #if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL if (provider.prefer_builtin) { return std::unexpected{make_crypto_error( CryptoErrorCode::unsupported_algorithm, "Crypto::Ed25519PrivateKey::generate requires OpenSSL backend")}; } ERR_clear_error(); EvpPkeyPtr key{ EVP_PKEY_Q_keygen(nullptr, propq_or_null(provider), "ED25519"), &EVP_PKEY_free}; if (!key) { return std::unexpected{make_openssl_error( CryptoErrorCode::provider_error, "Crypto::Ed25519PrivateKey::generate failed")}; } auto impl = std::make_unique(); impl->pkey = std::move(key); return Ed25519PrivateKey{std::move(impl)}; #else (void)provider; std::random_device random; std::array seed{}; for (std::size_t offset = 0; offset < seed.size();) { const std::uint32_t word = random(); const std::size_t count = std::min(sizeof(word), seed.size() - offset); std::memcpy(seed.data() + offset, &word, count); offset += count; } auto impl = std::make_unique(); impl->seed = seed; derive_ed25519_public_key(impl->seed, impl->public_key); secure_wipe(seed); return Ed25519PrivateKey{std::move(impl)}; #endif } Void::Result::Result Ed25519PrivateKey::from_raw_seed(std::span seed, const ProviderOptions& provider) { if (seed.size() != Ed25519SeedSize) { return std::unexpected{make_crypto_error( CryptoErrorCode::invalid_key_size, std::format("Crypto::Ed25519PrivateKey::from_raw_seed: seed " "must be {} bytes", Ed25519SeedSize))}; } if (auto fault = maybe_inject_fault( FaultOperation::ed25519_import, "Crypto::Ed25519PrivateKey::from_raw_seed"); fault.has_value()) { return std::unexpected{std::move(*fault)}; } #if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL if (provider.prefer_builtin) { return std::unexpected{make_crypto_error( CryptoErrorCode::unsupported_algorithm, "Crypto::Ed25519PrivateKey::from_raw_seed requires OpenSSL " "backend")}; } ERR_clear_error(); EvpPkeyPtr key{EVP_PKEY_new_raw_private_key_ex( nullptr, "ED25519", propq_or_null(provider), non_null_bytes(seed), seed.size()), &EVP_PKEY_free}; if (!key) { return std::unexpected{make_openssl_error( CryptoErrorCode::provider_error, "Crypto::Ed25519PrivateKey::from_raw_seed failed")}; } auto impl = std::make_unique(); impl->pkey = std::move(key); return Ed25519PrivateKey{std::move(impl)}; #else (void)provider; auto impl = std::make_unique(); std::memcpy(impl->seed.data(), seed.data(), Ed25519SeedSize); derive_ed25519_public_key(impl->seed, impl->public_key); return Ed25519PrivateKey{std::move(impl)}; #endif } Void::Result::Result Ed25519PrivateKey::public_key() const { if (!valid()) { return std::unexpected{make_crypto_error( CryptoErrorCode::invalid_state, "Crypto::Ed25519PrivateKey::public_key: invalid or moved-from " "key")}; } #if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL Ed25519PublicKey pub; std::size_t len = pub.bytes.size(); if (EVP_PKEY_get_raw_public_key( m_impl->pkey.get(), reinterpret_cast(pub.bytes.data()), &len) != 1 || len != Ed25519PublicKeySize) { return std::unexpected{make_openssl_error( CryptoErrorCode::backend_error, "Crypto::Ed25519PrivateKey::public_key failed")}; } return pub; #else Ed25519PublicKey pub; std::memcpy(pub.bytes.data(), m_impl->public_key.data(), Ed25519PublicKeySize); return pub; #endif } Void::Result::Result Ed25519PrivateKey::export_raw_seed() const { if (!valid()) { return std::unexpected{make_crypto_error( CryptoErrorCode::invalid_state, "Crypto::Ed25519PrivateKey::export_raw_seed: invalid or " "moved-from key")}; } #if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL std::array raw{}; std::size_t len = raw.size(); if (EVP_PKEY_get_raw_private_key( m_impl->pkey.get(), reinterpret_cast(raw.data()), &len) != 1 || len != Ed25519SeedSize) { secure_wipe(raw); return std::unexpected{make_openssl_error( CryptoErrorCode::backend_error, "Crypto::Ed25519PrivateKey::export_raw_seed failed")}; } auto result = Ed25519Seed::from_bytes(raw); secure_wipe(raw); return result; #else return Ed25519Seed::from_bytes(m_impl->seed); #endif } Void::Result::Result sign_ed25519(std::span message, const Ed25519PrivateKey& private_key, const ProviderOptions& provider) { if (!private_key.valid()) { return std::unexpected{make_crypto_error( CryptoErrorCode::invalid_state, "Crypto::sign_ed25519: private key is invalid or moved-from")}; } if (message.size() > CryptoLimits::kMaxOneShotMessageBytes) { return std::unexpected{make_crypto_error( CryptoErrorCode::message_too_large, std::format("Crypto::sign_ed25519: message exceeds {} byte " "one-shot limit", CryptoLimits::kMaxOneShotMessageBytes))}; } if (auto fault = maybe_inject_fault(FaultOperation::ed25519_sign, "Crypto::sign_ed25519"); fault.has_value()) { return std::unexpected{std::move(*fault)}; } #if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL if (provider.prefer_builtin) { return std::unexpected{make_crypto_error( CryptoErrorCode::unsupported_algorithm, "Crypto::sign_ed25519 requires OpenSSL backend")}; } ERR_clear_error(); EvpMdCtxPtr context{EVP_MD_CTX_new(), &EVP_MD_CTX_free}; if (!context) { return std::unexpected{make_openssl_error( CryptoErrorCode::backend_error, "Crypto::sign_ed25519: EVP_MD_CTX_new failed")}; } if (EVP_DigestSignInit_ex(context.get(), nullptr, nullptr, nullptr, propq_or_null(provider), private_key.m_impl->pkey.get(), nullptr) != 1) { return std::unexpected{make_openssl_error( CryptoErrorCode::provider_error, "Crypto::sign_ed25519: initialization failed")}; } Ed25519Signature signature; std::size_t sig_len = signature.bytes.size(); if (EVP_DigestSign( context.get(), reinterpret_cast(signature.bytes.data()), &sig_len, non_null_bytes(message), message.size()) != 1 || sig_len != Ed25519SignatureSize) { secure_wipe(signature.bytes); return std::unexpected{make_openssl_error( CryptoErrorCode::backend_error, "Crypto::sign_ed25519 failed")}; } return signature; #else (void)provider; Ed25519Signature signature; Detail::Ed25519::sign( reinterpret_cast(private_key.m_impl->seed.data()), reinterpret_cast( private_key.m_impl->public_key.data()), message, reinterpret_cast(signature.bytes.data())); return signature; #endif } Void::Result::Result verifyEd25519(std::span message, std::span signature, std::span publicKey) { return verify_ed25519_impl(message, signature, publicKey, ProviderOptions{}); } Void::Result::Result verify_ed25519(std::span message, const Ed25519Signature& signature, const Ed25519PublicKey& public_key, const ProviderOptions& provider) { return verify_ed25519_impl(message, signature.view(), public_key.view(), provider); } Void::Result::Result ed25519_keypair(const ProviderOptions& provider) { auto private_key = Ed25519PrivateKey::generate(provider); if (!private_key) { return std::unexpected{std::move(private_key).error()}; } auto public_key = private_key->public_key(); if (!public_key) { return std::unexpected{std::move(public_key).error()}; } auto secret_key = private_key->export_raw_seed(); if (!secret_key) { return std::unexpected{std::move(secret_key).error()}; } return Ed25519KeyPair{std::move(*secret_key), std::move(*public_key)}; } Void::Result::Result ed25519_sign(std::span secret_key, std::span message, const ProviderOptions& provider) { auto private_key = Ed25519PrivateKey::from_raw_seed(secret_key, provider); if (!private_key) { return std::unexpected{std::move(private_key).error()}; } return sign_ed25519(message, *private_key, provider); } Void::Result::Result ed25519_verify(std::span public_key, std::span message, std::span signature, const ProviderOptions& provider) { auto parsed_public_key = Ed25519PublicKey::from_bytes(public_key); if (!parsed_public_key) { return std::unexpected{std::move(parsed_public_key).error()}; } auto parsed_signature = Ed25519Signature::from_bytes(signature); if (!parsed_signature) { return std::unexpected{std::move(parsed_signature).error()}; } return verify_ed25519(message, *parsed_signature, *parsed_public_key, 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) { 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::pbkdf2_hmac_sha256: iterations must be " "1..{}", CryptoLimits::kMaxPbkdf2Iterations))}; } 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::pbkdf2_hmac_sha256: output buffer overlaps input")}; } if (auto fault = maybe_inject_fault(FaultOperation::pbkdf2, "Crypto::pbkdf2_hmac_sha256"); fault.has_value()) { secure_wipe(output); return std::unexpected{std::move(*fault)}; } if (use_builtin_hash(HashAlgorithm::Sha256, provider)) { if (!provider.property_query.empty()) { secure_wipe(output); return std::unexpected{make_crypto_error( CryptoErrorCode::provider_error, "Crypto::pbkdf2_hmac_sha256: property_query unavailable on " "built-in backend")}; } Detail::builtin_pbkdf2_hmac_sha256(password, salt, iterations, output); return {}; } #if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL ERR_clear_error(); 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::pbkdf2_hmac_sha256: EVP_KDF_fetch failed")}; } 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::pbkdf2_hmac_sha256: EVP_KDF_CTX_new failed")}; } char digest_name[] = "SHA256"; 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_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::pbkdf2_hmac_sha256: EVP_KDF_derive failed")}; } return {}; #else secure_wipe(output); return std::unexpected{make_crypto_error( CryptoErrorCode::backend_error, "Crypto::pbkdf2_hmac_sha256: OpenSSL backend unavailable")}; #endif } Void::Result::Result pbkdf2_hmac_sha256(std::span password, std::span salt, std::uint32_t iterations, std::size_t output_length, const ProviderOptions& 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())}; } return out; } Void::Result::Result hkdf_sha256(std::span secret_input, std::span salt, std::span context, std::span secret_output, const ProviderOptions& provider) { if (secret_output.empty()) { return std::unexpected{make_crypto_error( CryptoErrorCode::invalid_argument, "Crypto::hkdf_sha256: output buffer must be non-empty")}; } if (secret_output.size() > CryptoLimits::kMaxHkdfOutputBytes) { return std::unexpected{make_crypto_error( CryptoErrorCode::output_too_large, std::format("Crypto::hkdf_sha256: output size exceeds {} byte " "cap", CryptoLimits::kMaxHkdfOutputBytes))}; } if (spans_overlap(secret_input, secret_output) || spans_overlap(salt, secret_output) || spans_overlap(context, secret_output)) { return std::unexpected{make_crypto_error( CryptoErrorCode::overlapping_buffers, "Crypto::hkdf_sha256: output buffer overlaps input")}; } if (auto fault = maybe_inject_fault(FaultOperation::hkdf, "Crypto::hkdf_sha256"); fault.has_value()) { secure_wipe(secret_output); return std::unexpected{std::move(*fault)}; } if (use_builtin_hash(HashAlgorithm::Sha256, provider)) { if (!provider.property_query.empty()) { secure_wipe(secret_output); return std::unexpected{make_crypto_error( CryptoErrorCode::provider_error, "Crypto::hkdf_sha256: property_query unavailable on " "built-in backend")}; } Detail::builtin_hkdf_sha256(secret_input, salt, context, secret_output); return {}; } #if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL ERR_clear_error(); EvpKdfPtr kdf{EVP_KDF_fetch(nullptr, "HKDF", propq_or_null(provider)), &EVP_KDF_free}; if (!kdf) { secure_wipe(secret_output); return std::unexpected{make_openssl_error( CryptoErrorCode::provider_error, "Crypto::hkdf_sha256: EVP_KDF_fetch failed")}; } EvpKdfCtxPtr ctx{EVP_KDF_CTX_new(kdf.get()), &EVP_KDF_CTX_free}; if (!ctx) { secure_wipe(secret_output); return std::unexpected{make_openssl_error( CryptoErrorCode::backend_error, "Crypto::hkdf_sha256: EVP_KDF_CTX_new failed")}; } char digest_name[] = "SHA256"; std::array params = { OSSL_PARAM_construct_utf8_string(OSSL_KDF_PARAM_DIGEST, digest_name, 0), OSSL_PARAM_construct_octet_string( OSSL_KDF_PARAM_KEY, const_cast(non_null_bytes(secret_input)), secret_input.size()), OSSL_PARAM_construct_octet_string( OSSL_KDF_PARAM_SALT, const_cast(non_null_bytes(salt)), salt.size()), OSSL_PARAM_construct_octet_string( OSSL_KDF_PARAM_INFO, const_cast(non_null_bytes(context)), context.size()), OSSL_PARAM_construct_end(), }; if (EVP_KDF_derive( ctx.get(), reinterpret_cast(secret_output.data()), secret_output.size(), params.data()) != 1) { secure_wipe(secret_output); return std::unexpected{make_openssl_error( CryptoErrorCode::backend_error, "Crypto::hkdf_sha256: EVP_KDF_derive failed")}; } return {}; #else secure_wipe(secret_output); return std::unexpected{make_crypto_error( CryptoErrorCode::backend_error, "Crypto::hkdf_sha256: OpenSSL backend unavailable")}; #endif } } // namespace Void::Crypto