feat(crypto): harden Crypto primitives and add optional CryptoAsync adapter

This commit is contained in:
faumaray committed 2026-11-25 06:28:50 +03:00
1 parent 8a1c15f9c0
commit eb42228604
14 files changed
+2448 -90

No files matched your search

+90
View File
@@ -0,0 +1,90 @@
#pragma once
#include <Void/Async/Executor.hpp>
#include <Void/Async/Operation.hpp>
#include <Void/Async/Task.hpp>
#include <Void/Crypto/Crypto.hpp>
#include <Void/IO/Driver.hpp>
#include <Void/IO/Stream.hpp>
#include <Void/Time/Clock.hpp>
#include <cstddef>
#include <cstdint>
#include <filesystem>
#include <memory>
namespace Void::CryptoAsync
{
struct StreamHashOptions {
std::size_t chunk_bytes{
Void::Crypto::CryptoLimits::kStreamChunkBytes};
Void::Crypto::ProviderOptions provider{};
};
/// Incrementally hash an IO::ByteStream using a Driver-owned BufferLease
/// (default 64 KiB). Checks stop/deadline between chunks and finalizes only
/// on clean EOF without cancellation.
[[nodiscard]] Void::Coro::Task<Void::Result::Result<Void::Crypto::Digest>>
hash_stream(Void::Crypto::HashAlgorithm algorithm,
Void::IO::Driver& driver, Void::IO::ByteStream& stream,
Void::Async::OperationOptions options = {},
StreamHashOptions hash_options = {});
struct FileHasherOptions {
std::size_t max_concurrent{
Void::Crypto::CryptoLimits::kDefaultMaxConcurrentFileHashes};
std::size_t max_waiting{
Void::Crypto::CryptoLimits::kDefaultMaxWaitingFileHashes};
std::size_t buffer_budget_bytes{
Void::Crypto::CryptoLimits::kDefaultAsyncBufferBudgetBytes};
std::size_t chunk_bytes{
Void::Crypto::CryptoLimits::kStreamChunkBytes};
Void::Crypto::ProviderOptions provider{};
};
struct FileHasherStats {
std::size_t active{0};
std::size_t waiting{0};
std::size_t reserved_buffer_bytes{0};
std::uint64_t completed{0};
std::uint64_t rejected{0};
bool closing{false};
};
/// Bounded asynchronous file-hashing service with concurrency, queue, and
/// owned buffer-budget limits plus explicit stop/join shutdown.
class AsyncFileHasher
{
public:
explicit AsyncFileHasher(
Void::Async::Executor& executor,
FileHasherOptions options = {},
const Void::Time::MonotonicClock& clock =
Void::Time::SystemMonotonicClock::instance());
~AsyncFileHasher();
AsyncFileHasher(const AsyncFileHasher&) = delete;
AsyncFileHasher& operator=(const AsyncFileHasher&) = delete;
AsyncFileHasher(AsyncFileHasher&&) = delete;
AsyncFileHasher& operator=(AsyncFileHasher&&) = delete;
[[nodiscard]] Void::Coro::Task<
Void::Result::Result<Void::Crypto::Digest>>
hash_file(Void::Crypto::HashAlgorithm algorithm,
std::filesystem::path path,
Void::Async::OperationOptions options = {});
void request_stop() noexcept;
[[nodiscard]] Void::Result::Result<void> close_and_join();
[[nodiscard]] FileHasherStats stats() const noexcept;
private:
struct State;
std::shared_ptr<State> m_state;
};
} // namespace Void::CryptoAsync
+92 -5
View File
@@ -1,5 +1,6 @@
#pragma once
#include <Void/Crypto/Types.hpp>
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
@@ -21,18 +22,23 @@ namespace Void::Crypto
[[nodiscard]] static Void::Result::Result<Hasher>
create(HashAlgorithm algorithm);
[[nodiscard]] static Void::Result::Result<Hasher>
create(HashAlgorithm algorithm,
const ProviderOptions& provider);
~Hasher();
Hasher(Hasher&&) noexcept;
Hasher& operator=(Hasher&&) noexcept;
Hasher(const Hasher&) = delete;
Hasher& operator=(const Hasher&) = delete;
[[nodiscard]] HasherState state() const noexcept;
[[nodiscard]] Void::Result::Result<void>
update(std::span<const std::byte> data);
[[nodiscard]] Void::Result::Result<void>
update(std::string_view data);
/// Finalize this hash. Calling finalize or update again is an
/// error.
/// error. Backend update/finalize failures poison the hasher.
[[nodiscard]] Void::Result::Result<Digest> finalize();
private:
@@ -44,10 +50,16 @@ namespace Void::Crypto
[[nodiscard]] Void::Result::Result<Digest>
hash(HashAlgorithm algorithm, std::span<const std::byte> data);
[[nodiscard]] Void::Result::Result<Digest>
hash(HashAlgorithm algorithm, std::span<const std::byte> data,
const ProviderOptions& provider);
[[nodiscard]] Void::Result::Result<Digest> hash(HashAlgorithm algorithm,
std::string_view data);
[[nodiscard]] Void::Result::Result<Digest>
hashFile(HashAlgorithm algorithm, const std::filesystem::path& path);
[[nodiscard]] Void::Result::Result<Digest>
hashFile(HashAlgorithm algorithm, const std::filesystem::path& path,
const ProviderOptions& provider);
[[nodiscard]] Void::Result::Result<Digest>
sha1(std::span<const std::byte> data);
@@ -65,14 +77,89 @@ namespace Void::Crypto
[[nodiscard]] Void::Result::Result<Digest>
sha512File(const std::filesystem::path& path);
inline constexpr std::size_t Ed25519PublicKeySize = 32;
inline constexpr std::size_t Ed25519SignatureSize = 64;
/// Move-only owning Ed25519 private key handle. Has no implicit copy,
/// string conversion, or secret formatting.
class Ed25519PrivateKey
{
public:
Ed25519PrivateKey() noexcept = default;
~Ed25519PrivateKey();
Ed25519PrivateKey(Ed25519PrivateKey&&) noexcept;
Ed25519PrivateKey& operator=(Ed25519PrivateKey&&) noexcept;
Ed25519PrivateKey(const Ed25519PrivateKey&) = delete;
Ed25519PrivateKey& operator=(const Ed25519PrivateKey&) = delete;
[[nodiscard]] static Void::Result::Result<Ed25519PrivateKey>
generate(const ProviderOptions& provider = {});
[[nodiscard]] static Void::Result::Result<Ed25519PrivateKey>
from_raw_seed(std::span<const std::byte> seed,
const ProviderOptions& provider = {});
[[nodiscard]] bool valid() const noexcept;
[[nodiscard]] Void::Result::Result<Ed25519PublicKey>
public_key() const;
/// Explicit secret export into a move-only self-wiping seed handle.
[[nodiscard]] Void::Result::Result<Ed25519Seed>
export_raw_seed() const;
private:
struct Impl;
std::unique_ptr<Impl> m_impl;
explicit Ed25519PrivateKey(std::unique_ptr<Impl> impl) noexcept;
friend Void::Result::Result<Ed25519Signature>
sign_ed25519(std::span<const std::byte> message,
const Ed25519PrivateKey& private_key,
const ProviderOptions& provider);
};
/// Sign exact message bytes (up to CryptoLimits::kMaxOneShotMessageBytes)
/// with an owning Ed25519 private key.
[[nodiscard]] Void::Result::Result<Ed25519Signature>
sign_ed25519(std::span<const std::byte> message,
const Ed25519PrivateKey& private_key,
const ProviderOptions& provider = {});
/// Verify an Ed25519 detached signature over the exact message bytes.
/// Invalid key/signature sizes are errors; a well-formed but invalid
/// signature returns false.
/// Invalid key/signature sizes or oversized messages are errors; a
/// well-formed but invalid signature returns false.
[[nodiscard]] Void::Result::Result<bool>
verifyEd25519(std::span<const std::byte> message,
std::span<const std::byte> signature,
std::span<const std::byte> publicKey);
[[nodiscard]] Void::Result::Result<bool>
verify_ed25519(std::span<const std::byte> message,
const Ed25519Signature& signature,
const Ed25519PublicKey& public_key,
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<void>
hmac_sha256_into(std::span<const std::byte> secret_key,
std::span<const std::byte> message,
std::span<std::byte> output,
const ProviderOptions& provider = {});
[[nodiscard]] Void::Result::Result<Digest>
hmac_sha256(std::span<const std::byte> secret_key,
std::span<const std::byte> message,
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.
[[nodiscard]] Void::Result::Result<void>
hkdf_sha256(std::span<const std::byte> secret_input,
std::span<const std::byte> salt,
std::span<const std::byte> context,
std::span<std::byte> secret_output,
const ProviderOptions& provider = {});
} // namespace Void::Crypto
+287
View File
@@ -0,0 +1,287 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <array>
#include <cstddef>
#include <cstdint>
#include <span>
#include <string>
#include <system_error>
#include <utility>
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 HmacSha256Size = 32;
struct CryptoLimits {
static constexpr std::size_t kMaxOneShotMessageBytes =
16ULL * 1024ULL * 1024ULL;
static constexpr std::size_t kMaxHkdfOutputBytes = 4ULL * 1024ULL;
static constexpr std::size_t kStreamChunkBytes = 64ULL * 1024ULL;
static constexpr std::size_t kDefaultMaxConcurrentFileHashes = 8;
static constexpr std::size_t kDefaultMaxWaitingFileHashes = 32;
static constexpr std::size_t kDefaultAsyncBufferBudgetBytes =
8ULL * 1024ULL * 1024ULL;
};
enum class CryptoErrorCode : std::int32_t {
none = 0,
invalid_argument = 1,
invalid_key_size = 2,
invalid_signature_size = 3,
message_too_large = 4,
output_too_large = 5,
overlapping_buffers = 6,
invalid_state = 7,
unsupported_algorithm = 8,
provider_error = 9,
backend_error = 10,
io_error = 11,
cancelled = 12,
timeout = 13,
overloaded = 14,
resource_exhausted = 15,
closed = 16
};
[[nodiscard]] inline Void::Result::Error
make_crypto_error(CryptoErrorCode code, std::string message = {},
std::error_code sys_err = {})
{
using Void::Result::Error;
using Void::Result::ErrorCode;
using Void::Result::ErrorKind;
ErrorKind kind = ErrorKind::internal;
switch (code) {
case CryptoErrorCode::none:
kind = ErrorKind::internal;
break;
case CryptoErrorCode::invalid_argument:
case CryptoErrorCode::invalid_key_size:
case CryptoErrorCode::invalid_signature_size:
case CryptoErrorCode::message_too_large:
case CryptoErrorCode::output_too_large:
case CryptoErrorCode::overlapping_buffers:
kind = ErrorKind::invalid_argument;
break;
case CryptoErrorCode::invalid_state:
kind = ErrorKind::conflict;
break;
case CryptoErrorCode::unsupported_algorithm:
kind = ErrorKind::unsupported;
break;
case CryptoErrorCode::provider_error:
case CryptoErrorCode::backend_error:
kind = ErrorKind::internal;
break;
case CryptoErrorCode::io_error:
kind = ErrorKind::io;
break;
case CryptoErrorCode::cancelled:
case CryptoErrorCode::closed:
kind = ErrorKind::cancelled;
break;
case CryptoErrorCode::timeout:
kind = ErrorKind::timeout;
break;
case CryptoErrorCode::overloaded:
kind = ErrorKind::overloaded;
break;
case CryptoErrorCode::resource_exhausted:
kind = ErrorKind::exhausted;
break;
}
const ErrorCode domain_code{Void::Result::kCryptoErrorDomain,
static_cast<std::int32_t>(code)};
return Error{kind, std::move(message), domain_code, sys_err};
}
enum class HasherState : std::uint8_t {
Ready = 0,
Updating,
Finalized,
Failed,
MovedFrom
};
/// Per-operation OpenSSL 3 provider selection. Never mutates process-wide
/// provider state.
struct ProviderOptions {
std::string property_query{};
};
struct Ed25519PublicKey {
std::array<std::byte, Ed25519PublicKeySize> bytes{};
[[nodiscard]] std::span<const std::byte> view() const noexcept
{
return bytes;
}
[[nodiscard]] static Void::Result::Result<Ed25519PublicKey>
from_bytes(std::span<const std::byte> raw)
{
if (raw.size() != Ed25519PublicKeySize) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::invalid_key_size,
"Ed25519PublicKey requires exactly 32 bytes")};
}
Ed25519PublicKey key;
for (std::size_t i = 0; i < Ed25519PublicKeySize; ++i) {
key.bytes[i] = raw[i];
}
return key;
}
[[nodiscard]] constexpr bool
operator==(const Ed25519PublicKey&) const noexcept = default;
};
struct Ed25519Signature {
std::array<std::byte, Ed25519SignatureSize> bytes{};
[[nodiscard]] std::span<const std::byte> view() const noexcept
{
return bytes;
}
[[nodiscard]] static Void::Result::Result<Ed25519Signature>
from_bytes(std::span<const std::byte> raw)
{
if (raw.size() != Ed25519SignatureSize) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::invalid_signature_size,
"Ed25519Signature requires exactly 64 bytes")};
}
Ed25519Signature sig;
for (std::size_t i = 0; i < Ed25519SignatureSize; ++i) {
sig.bytes[i] = raw[i];
}
return sig;
}
[[nodiscard]] constexpr bool
operator==(const Ed25519Signature&) const noexcept = default;
};
/// Securely wipe a mutable byte buffer using the crypto backend's
/// non-elidable cleanse routine.
void secure_wipe(std::span<std::byte> buffer) noexcept;
/// Constant-time equality comparison for equal-length digests/MACs.
[[nodiscard]] bool
constant_time_equal(std::span<const std::byte> lhs,
std::span<const std::byte> rhs) noexcept;
/// Move-only 32-byte Ed25519 raw seed cleared on release.
class Ed25519Seed
{
public:
Ed25519Seed() noexcept = default;
~Ed25519Seed() noexcept { clear(); }
Ed25519Seed(Ed25519Seed&& other) noexcept
: m_bytes(other.m_bytes), m_valid(other.m_valid)
{
other.clear();
}
Ed25519Seed& operator=(Ed25519Seed&& other) noexcept
{
if (this != &other) {
clear();
m_bytes = other.m_bytes;
m_valid = other.m_valid;
other.clear();
}
return *this;
}
Ed25519Seed(const Ed25519Seed&) = delete;
Ed25519Seed& operator=(const Ed25519Seed&) = delete;
[[nodiscard]] static Void::Result::Result<Ed25519Seed>
from_bytes(std::span<const std::byte> raw)
{
if (raw.size() != Ed25519SeedSize) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::invalid_key_size,
"Ed25519Seed requires exactly 32 bytes")};
}
Ed25519Seed seed;
for (std::size_t i = 0; i < Ed25519SeedSize; ++i) {
seed.m_bytes[i] = raw[i];
}
seed.m_valid = true;
return seed;
}
[[nodiscard]] bool valid() const noexcept { return m_valid; }
[[nodiscard]] std::span<const std::byte> view() const noexcept
{
return m_valid ? std::span<const std::byte>{m_bytes}
: std::span<const std::byte>{};
}
void clear() noexcept
{
secure_wipe(m_bytes);
m_valid = false;
}
private:
std::array<std::byte, Ed25519SeedSize> m_bytes{};
bool m_valid{false};
};
enum class FaultOperation : std::uint8_t {
none = 0,
any,
hash_create,
hash_update,
hash_finalize,
ed25519_keygen,
ed25519_import,
ed25519_sign,
ed25519_verify,
hmac,
hkdf
};
struct FaultConfig {
FaultOperation op{FaultOperation::none};
CryptoErrorCode code{CryptoErrorCode::provider_error};
std::size_t fail_after{0};
};
/// RAII thread-local backend fault injection guard for deterministic
/// provider/backend failure testing.
class ScopedFaultGuard
{
public:
explicit ScopedFaultGuard(FaultConfig config) noexcept;
~ScopedFaultGuard() noexcept;
ScopedFaultGuard(const ScopedFaultGuard&) = delete;
ScopedFaultGuard& operator=(const ScopedFaultGuard&) = delete;
ScopedFaultGuard(ScopedFaultGuard&&) = delete;
ScopedFaultGuard& operator=(ScopedFaultGuard&&) = delete;
private:
FaultConfig m_previous{};
std::size_t m_previous_hits{0};
};
} // namespace Void::Crypto
+658 -85
View File
@@ -1,48 +1,226 @@
#include <Void/Crypto/Crypto.hpp>
#include <array>
#include <cstdint>
#include <cstring>
#include <format>
#include <fstream>
#include <limits>
#include <utility>
#include <openssl/core_names.h>
#include <openssl/crypto.h>
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/kdf.h>
#include <openssl/params.h>
namespace Void::Crypto
{
namespace
{
[[nodiscard]] const EVP_MD*
algorithm_impl(HashAlgorithm algorithm) noexcept
thread_local FaultConfig g_fault_config{};
thread_local std::size_t g_fault_hits{0};
[[nodiscard]] std::optional<Void::Result::Error>
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]] const char*
algorithm_name(HashAlgorithm algorithm) noexcept
{
switch (algorithm) {
case HashAlgorithm::Sha1:
return EVP_sha1();
return "SHA1";
case HashAlgorithm::Sha256:
return EVP_sha256();
return "SHA256";
case HashAlgorithm::Sha512:
return EVP_sha512();
return "SHA512";
}
return nullptr;
}
[[nodiscard]] std::string openssl_error(std::string_view operation)
[[nodiscard]] const char*
propq_or_null(const ProviderOptions& provider) noexcept
{
const unsigned long code = ERR_get_error();
if (code == 0) {
return std::string{operation};
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<char, 256> buffer{};
ERR_error_string_n(code, buffer.data(), buffer.size());
return std::format("{}: {}", operation, buffer.data());
ERR_error_string_n(err_code, buffer.data(), buffer.size());
return make_crypto_error(
code, std::format("{}: {}", operation, buffer.data()));
}
[[nodiscard]] bool spans_overlap(std::span<const std::byte> a,
std::span<const std::byte> b) noexcept
{
if (a.empty() || b.empty()) {
return false;
}
const auto a_begin = reinterpret_cast<std::uintptr_t>(a.data());
const auto a_end = a_begin + a.size();
const auto b_begin = reinterpret_cast<std::uintptr_t>(b.data());
const auto b_end = b_begin + b.size();
return a_begin < b_end && b_begin < a_end;
}
using EvpMdPtr = std::unique_ptr<EVP_MD, decltype(&EVP_MD_free)>;
using EvpMdCtxPtr =
std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>;
using EvpPkeyPtr = std::unique_ptr<EVP_PKEY, decltype(&EVP_PKEY_free)>;
using EvpMacPtr = std::unique_ptr<EVP_MAC, decltype(&EVP_MAC_free)>;
using EvpMacCtxPtr =
std::unique_ptr<EVP_MAC_CTX, decltype(&EVP_MAC_CTX_free)>;
using EvpKdfPtr = std::unique_ptr<EVP_KDF, decltype(&EVP_KDF_free)>;
using EvpKdfCtxPtr =
std::unique_ptr<EVP_KDF_CTX, decltype(&EVP_KDF_CTX_free)>;
[[nodiscard]] const unsigned char*
non_null_bytes(std::span<const std::byte> span) noexcept
{
static constexpr unsigned char kEmptyByte = 0;
return span.empty()
? &kEmptyByte
: reinterpret_cast<const unsigned char*>(span.data());
}
[[nodiscard]] Void::Result::Result<bool>
verify_ed25519_impl(std::span<const std::byte> message,
std::span<const std::byte> signature,
std::span<const std::byte> 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)};
}
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;
}
} // namespace
void secure_wipe(std::span<std::byte> buffer) noexcept
{
if (!buffer.empty()) {
OPENSSL_cleanse(buffer.data(), buffer.size());
}
}
bool constant_time_equal(std::span<const std::byte> lhs,
std::span<const std::byte> rhs) noexcept
{
if (lhs.size() != rhs.size()) {
return false;
}
if (lhs.empty()) {
return true;
}
return CRYPTO_memcmp(lhs.data(), rhs.data(), lhs.size()) == 0;
}
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 {
EVP_MD_CTX* context{nullptr};
const EVP_MD* algorithm{nullptr};
bool finalized{false};
~Impl() { EVP_MD_CTX_free(context); }
EvpMdCtxPtr context{nullptr, &EVP_MD_CTX_free};
EvpMdPtr algorithm{nullptr, &EVP_MD_free};
HasherState state{HasherState::Ready};
};
Hasher::Hasher(std::unique_ptr<Impl> impl) noexcept
@@ -53,36 +231,85 @@ namespace Void::Crypto
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> Hasher::create(HashAlgorithm algorithm)
{
return create(algorithm, ProviderOptions{});
}
Void::Result::Result<Hasher>
Hasher::create(HashAlgorithm algorithm, const ProviderOptions& provider)
{
const char* md_name = algorithm_name(algorithm);
if (md_name == nullptr) {
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)};
}
ERR_clear_error();
auto impl = std::make_unique<Impl>();
impl->algorithm = algorithm_impl(algorithm);
if (impl->algorithm == nullptr) {
return Void::Result::fail("Crypto::Hasher: unsupported algorithm");
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 = EVP_MD_CTX_new();
if (impl->context == nullptr) {
return Void::Result::fail(
openssl_error("Crypto::Hasher: EVP_MD_CTX_new 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_ex(impl->context, impl->algorithm, nullptr) != 1) {
return Void::Result::fail(
openssl_error("Crypto::Hasher: digest initialization 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->state = HasherState::Ready;
return Hasher{std::move(impl)};
}
Void::Result::Result<void> Hasher::update(std::span<const std::byte> data)
{
if (!m_impl || m_impl->finalized) {
return Void::Result::fail(
"Crypto::Hasher::update: hasher is finalized or moved-from");
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 (!data.empty() &&
EVP_DigestUpdate(m_impl->context, data.data(), data.size()) != 1) {
return Void::Result::fail(
openssl_error("Crypto::Hasher::update failed"));
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 {};
}
@@ -93,24 +320,41 @@ namespace Void::Crypto
Void::Result::Result<Digest> Hasher::finalize()
{
if (!m_impl || m_impl->finalized) {
return Void::Result::fail(
"Crypto::Hasher::finalize: hasher is finalized or moved-from");
if (!m_impl) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::invalid_state,
"Crypto::Hasher::finalize: hasher is moved-from")};
}
const int digest_size = EVP_MD_get_size(m_impl->algorithm);
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)};
}
const int digest_size = EVP_MD_get_size(m_impl->algorithm.get());
if (digest_size <= 0) {
return Void::Result::fail(
"Crypto::Hasher::finalize: invalid digest size");
m_impl->state = HasherState::Failed;
return std::unexpected{make_crypto_error(
CryptoErrorCode::backend_error,
"Crypto::Hasher::finalize: invalid digest size")};
}
Digest digest(static_cast<std::size_t>(digest_size));
unsigned int written = 0;
if (EVP_DigestFinal_ex(m_impl->context,
if (EVP_DigestFinal_ex(m_impl->context.get(),
reinterpret_cast<unsigned char*>(digest.data()),
&written) != 1) {
return Void::Result::fail(
openssl_error("Crypto::Hasher::finalize failed"));
m_impl->state = HasherState::Failed;
return std::unexpected{make_openssl_error(
CryptoErrorCode::backend_error,
"Crypto::Hasher::finalize failed")};
}
m_impl->finalized = true;
m_impl->state = HasherState::Finalized;
digest.resize(written);
return digest;
}
@@ -118,7 +362,13 @@ namespace Void::Crypto
auto hash(HashAlgorithm algorithm, std::span<const std::byte> data)
-> Void::Result::Result<Digest>
{
auto hasher = Hasher::create(algorithm);
return hash(algorithm, data, ProviderOptions{});
}
auto hash(HashAlgorithm algorithm, std::span<const std::byte> data,
const ProviderOptions& provider) -> Void::Result::Result<Digest>
{
auto hasher = Hasher::create(algorithm, provider);
if (!hasher) {
return std::unexpected{hasher.error()};
}
@@ -137,17 +387,26 @@ namespace Void::Crypto
auto hashFile(HashAlgorithm algorithm, const std::filesystem::path& path)
-> Void::Result::Result<Digest>
{
return hashFile(algorithm, path, ProviderOptions{});
}
auto hashFile(HashAlgorithm algorithm, const std::filesystem::path& path,
const ProviderOptions& provider)
-> Void::Result::Result<Digest>
{
std::ifstream input{path, std::ios::binary};
if (!input.is_open()) {
return Void::Result::fail(std::format(
"Crypto::hashFile: cannot open '{}'", path.string()));
return std::unexpected{make_crypto_error(
CryptoErrorCode::io_error,
std::format("Crypto::hashFile: cannot open '{}'",
path.string()))};
}
auto hasher = Hasher::create(algorithm);
auto hasher = Hasher::create(algorithm, provider);
if (!hasher) {
return std::unexpected{hasher.error()};
}
std::array<char, 64 * 1024> buffer{};
std::array<char, CryptoLimits::kStreamChunkBytes> buffer{};
while (input) {
input.read(buffer.data(),
static_cast<std::streamsize>(buffer.size()));
@@ -160,9 +419,11 @@ namespace Void::Crypto
}
}
}
if (input.bad()) {
return Void::Result::fail(std::format(
"Crypto::hashFile: I/O error reading '{}'", path.string()));
if (input.bad() || (!input.eof() && input.fail())) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::io_error,
std::format("Crypto::hashFile: I/O error reading '{}'",
path.string()))};
}
return hasher->finalize();
}
@@ -204,54 +465,366 @@ namespace Void::Crypto
return hashFile(HashAlgorithm::Sha512, path);
}
struct Ed25519PrivateKey::Impl {
EvpPkeyPtr pkey{nullptr, &EVP_PKEY_free};
};
Ed25519PrivateKey::Ed25519PrivateKey(std::unique_ptr<Impl> 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
{
return m_impl != nullptr && m_impl->pkey != nullptr;
}
Void::Result::Result<Ed25519PrivateKey>
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)};
}
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>();
impl->pkey = std::move(key);
return Ed25519PrivateKey{std::move(impl)};
}
Void::Result::Result<Ed25519PrivateKey>
Ed25519PrivateKey::from_raw_seed(std::span<const std::byte> 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)};
}
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>();
impl->pkey = std::move(key);
return Ed25519PrivateKey{std::move(impl)};
}
Void::Result::Result<Ed25519PublicKey> Ed25519PrivateKey::public_key() const
{
if (!valid()) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::invalid_state,
"Crypto::Ed25519PrivateKey::public_key: invalid or moved-from "
"key")};
}
Ed25519PublicKey pub;
std::size_t len = pub.bytes.size();
if (EVP_PKEY_get_raw_public_key(
m_impl->pkey.get(),
reinterpret_cast<unsigned char*>(pub.bytes.data()),
&len) != 1 ||
len != Ed25519PublicKeySize) {
return std::unexpected{make_openssl_error(
CryptoErrorCode::backend_error,
"Crypto::Ed25519PrivateKey::public_key failed")};
}
return pub;
}
Void::Result::Result<Ed25519Seed> 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")};
}
std::array<std::byte, Ed25519SeedSize> raw{};
std::size_t len = raw.size();
if (EVP_PKEY_get_raw_private_key(
m_impl->pkey.get(),
reinterpret_cast<unsigned char*>(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;
}
Void::Result::Result<Ed25519Signature>
sign_ed25519(std::span<const std::byte> 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)};
}
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<unsigned char*>(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;
}
Void::Result::Result<bool> verifyEd25519(std::span<const std::byte> message,
std::span<const std::byte>
signature,
std::span<const std::byte>
publicKey)
{
if (signature.size() != Ed25519SignatureSize) {
return Void::Result::fail(
std::format("Crypto::verifyEd25519: signature must be {} bytes",
Ed25519SignatureSize));
return verify_ed25519_impl(message, signature, publicKey,
ProviderOptions{});
}
Void::Result::Result<bool>
verify_ed25519(std::span<const std::byte> 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<void>
hmac_sha256_into(std::span<const std::byte> secret_key,
std::span<const std::byte> message,
std::span<std::byte> output,
const ProviderOptions& provider)
{
if (output.size() != HmacSha256Size) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::invalid_argument,
std::format("Crypto::hmac_sha256_into: output must be {} bytes",
HmacSha256Size))};
}
if (publicKey.size() != Ed25519PublicKeySize) {
return Void::Result::fail(std::format(
"Crypto::verifyEd25519: public key must be {} bytes",
Ed25519PublicKeySize));
if (spans_overlap(secret_key, output) ||
spans_overlap(message, output)) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::overlapping_buffers,
"Crypto::hmac_sha256_into: output buffer overlaps input")};
}
if (auto fault = maybe_inject_fault(FaultOperation::hmac,
"Crypto::hmac_sha256_into");
fault.has_value()) {
secure_wipe(output);
return std::unexpected{std::move(*fault)};
}
using Key = std::unique_ptr<EVP_PKEY, decltype(&EVP_PKEY_free)>;
using Context = std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>;
Key key{EVP_PKEY_new_raw_public_key(
EVP_PKEY_ED25519, nullptr,
reinterpret_cast<const unsigned char*>(publicKey.data()),
publicKey.size()),
&EVP_PKEY_free};
if (!key) {
return Void::Result::fail(
openssl_error("Crypto::verifyEd25519: invalid public key"));
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,
"Crypto::hmac_sha256_into: EVP_MAC_fetch failed")};
}
Context context{EVP_MD_CTX_new(), &EVP_MD_CTX_free};
if (!context) {
return Void::Result::fail(
openssl_error("Crypto::verifyEd25519: EVP_MD_CTX_new failed"));
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,
"Crypto::hmac_sha256_into: EVP_MAC_CTX_new failed")};
}
if (EVP_DigestVerifyInit(context.get(), nullptr, nullptr, nullptr,
key.get()) != 1) {
return Void::Result::fail(
openssl_error("Crypto::verifyEd25519: initialization failed"));
char digest_name[] = "SHA256";
std::array<OSSL_PARAM, 2> params = {
OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST, digest_name,
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,
"Crypto::hmac_sha256_into: EVP_MAC_init failed")};
}
const int result = EVP_DigestVerify(
context.get(),
reinterpret_cast<const unsigned char*>(signature.data()),
signature.size(),
reinterpret_cast<const unsigned char*>(message.data()),
message.size());
if (result < 0) {
return Void::Result::fail(
openssl_error("Crypto::verifyEd25519 failed"));
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,
"Crypto::hmac_sha256_into: EVP_MAC_update failed")};
}
return result == 1;
std::size_t out_len = 0;
if (EVP_MAC_final(ctx.get(),
reinterpret_cast<unsigned char*>(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")};
}
return {};
}
Void::Result::Result<Digest> hmac_sha256(std::span<const std::byte> secret_key,
std::span<const std::byte> 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<void>
hkdf_sha256(std::span<const std::byte> secret_input,
std::span<const std::byte> salt,
std::span<const std::byte> context,
std::span<std::byte> 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)};
}
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<OSSL_PARAM, 5> params = {
OSSL_PARAM_construct_utf8_string(OSSL_KDF_PARAM_DIGEST, digest_name,
0),
OSSL_PARAM_construct_octet_string(
OSSL_KDF_PARAM_KEY,
const_cast<unsigned char*>(non_null_bytes(secret_input)),
secret_input.size()),
OSSL_PARAM_construct_octet_string(
OSSL_KDF_PARAM_SALT,
const_cast<unsigned char*>(non_null_bytes(salt)), salt.size()),
OSSL_PARAM_construct_octet_string(
OSSL_KDF_PARAM_INFO,
const_cast<unsigned char*>(non_null_bytes(context)),
context.size()),
OSSL_PARAM_construct_end(),
};
if (EVP_KDF_derive(
ctx.get(),
reinterpret_cast<unsigned char*>(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 {};
}
} // namespace Void::Crypto
+2
View File
@@ -1,4 +1,6 @@
void_add_module(Crypto
INTERNAL_DEPS Functional
EXTERNAL_DEPS OpenSSL::Crypto
EXCLUDE_HEADERS
Void/Crypto/AsyncHash.hpp
)
+522
View File
@@ -0,0 +1,522 @@
#include <Void/Crypto/AsyncHash.hpp>
#include <algorithm>
#include <condition_variable>
#include <deque>
#include <format>
#include <fstream>
#include <functional>
#include <mutex>
#include <stop_token>
#include <thread>
#include <vector>
namespace Void::CryptoAsync
{
namespace
{
[[nodiscard]] Void::Result::Error
map_io_error(const Void::Result::Error& err)
{
if (err.kind() == Void::Result::ErrorKind::cancelled) {
return Void::Crypto::make_crypto_error(
Void::Crypto::CryptoErrorCode::cancelled, err.message(),
err.system_code());
}
if (err.kind() == Void::Result::ErrorKind::timeout) {
return Void::Crypto::make_crypto_error(
Void::Crypto::CryptoErrorCode::timeout, err.message(),
err.system_code());
}
if (err.kind() == Void::Result::ErrorKind::exhausted) {
return Void::Crypto::make_crypto_error(
Void::Crypto::CryptoErrorCode::resource_exhausted,
err.message(), err.system_code());
}
return Void::Crypto::make_crypto_error(
Void::Crypto::CryptoErrorCode::io_error, err.message(),
err.system_code());
}
} // namespace
Void::Coro::Task<Void::Result::Result<Void::Crypto::Digest>>
hash_stream(Void::Crypto::HashAlgorithm algorithm,
Void::IO::Driver& driver, Void::IO::ByteStream& stream,
Void::Async::OperationOptions options,
StreamHashOptions hash_options)
{
using namespace Void::Crypto;
if (hash_options.chunk_bytes == 0 ||
hash_options.chunk_bytes > CryptoLimits::kStreamChunkBytes) {
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::invalid_argument,
"CryptoAsync::hash_stream: chunk_bytes must be in [1, 64 KiB]")};
}
if (!stream.valid()) {
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::closed,
"CryptoAsync::hash_stream: stream is invalid or closed")};
}
if (options.stop.stop_requested()) {
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::cancelled,
"CryptoAsync::hash_stream: operation stopped before start")};
}
if (Void::Async::is_deadline_expired(options, driver.clock())) {
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::timeout,
"CryptoAsync::hash_stream: deadline expired before start")};
}
auto hasher = Hasher::create(algorithm, hash_options.provider);
if (!hasher.has_value()) {
co_return std::unexpected{std::move(hasher.error())};
}
auto lease = driver.allocate_buffer(hash_options.chunk_bytes);
if (!lease.has_value()) {
co_return std::unexpected{map_io_error(lease.error())};
}
for (;;) {
if (options.stop.stop_requested()) {
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::cancelled,
"CryptoAsync::hash_stream: stopped between chunks")};
}
if (Void::Async::is_deadline_expired(options, driver.clock())) {
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::timeout,
"CryptoAsync::hash_stream: deadline expired between chunks")};
}
auto transfer = co_await stream.read_some_owned(*lease, options);
if (!transfer.has_value()) {
co_return std::unexpected{map_io_error(transfer.error())};
}
if (options.stop.stop_requested()) {
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::cancelled,
"CryptoAsync::hash_stream: stopped during stream read")};
}
if (Void::Async::is_deadline_expired(options, driver.clock())) {
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::timeout,
"CryptoAsync::hash_stream: deadline expired after read")};
}
if (transfer->bytes > 0) {
if (auto upd = hasher->update(lease->readable());
!upd.has_value()) {
co_return std::unexpected{std::move(upd.error())};
}
}
if (transfer->eof) {
break;
}
}
if (options.stop.stop_requested()) {
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::cancelled,
"CryptoAsync::hash_stream: stopped before finalize")};
}
co_return hasher->finalize();
}
struct AsyncFileHasher::State : std::enable_shared_from_this<State> {
struct Job {
Job(Void::Crypto::HashAlgorithm alg,
std::filesystem::path p,
std::shared_ptr<
Void::Async::OperationState<Void::Crypto::Digest>>
o)
: algorithm(alg), path(std::move(p)), op(std::move(o))
{
}
Void::Crypto::HashAlgorithm algorithm;
std::filesystem::path path;
std::shared_ptr<
Void::Async::OperationState<Void::Crypto::Digest>>
op;
std::optional<std::stop_callback<std::function<void()>>>
cancel_cb{};
};
State(Void::Async::Executor& exec, FileHasherOptions opts,
const Void::Time::MonotonicClock& clk)
: executor(exec), options(std::move(opts)), clock(clk)
{
}
void start_workers_locked()
{
if (workers_started || options.max_concurrent == 0) {
return;
}
workers_started = true;
const std::size_t count =
std::max<std::size_t>(1, options.max_concurrent);
workers.reserve(count);
auto self = shared_from_this();
for (std::size_t i = 0; i < count; ++i) {
workers.emplace_back([self] { self->worker_loop(); });
}
}
void worker_loop()
{
for (;;) {
std::shared_ptr<Job> job;
{
std::unique_lock lk{mu};
cv.wait(lk, [this] {
if (closing) {
return true;
}
if (queue.empty()) {
return false;
}
if (active < options.max_concurrent &&
reserved_bytes + options.chunk_bytes <=
options.buffer_budget_bytes) {
return true;
}
return std::any_of(
queue.begin(), queue.end(),
[this](const auto& j) {
return j->op->stop_requested() ||
j->op->is_deadline_expired(clock);
});
});
// Purge any already-cancelled or expired jobs in queue.
std::vector<std::pair<std::shared_ptr<Job>,
Void::Result::Error>>
dropped_jobs;
for (auto it = queue.begin(); it != queue.end();) {
auto& item = *it;
if (closing || item->op->stop_requested()) {
dropped_jobs.emplace_back(
std::move(item),
Void::Crypto::make_crypto_error(
closing
? Void::Crypto::CryptoErrorCode::closed
: Void::Crypto::CryptoErrorCode::cancelled,
"CryptoAsync::AsyncFileHasher: job cancelled while queued"));
it = queue.erase(it);
} else if (item->op->is_deadline_expired(clock)) {
dropped_jobs.emplace_back(
std::move(item),
Void::Crypto::make_crypto_error(
Void::Crypto::CryptoErrorCode::timeout,
"CryptoAsync::AsyncFileHasher: deadline expired while queued"));
it = queue.erase(it);
} else {
++it;
}
}
if (!dropped_jobs.empty()) {
lk.unlock();
for (auto& [dropped, err] : dropped_jobs) {
dropped->cancel_cb.reset();
const auto kind =
(err.kind() ==
Void::Result::ErrorKind::cancelled)
? Void::Async::DomainOutcomeKind::cancelled
: Void::Async::DomainOutcomeKind::failed;
auto ticket = dropped->op->try_commit_error(
std::move(err), kind);
if (ticket.has_value()) {
ticket->dispatch();
}
dropped->op->release_backend_ref_and_dispatch();
}
lk.lock();
}
if (closing && queue.empty()) {
return;
}
if (queue.empty() || active >= options.max_concurrent ||
reserved_bytes + options.chunk_bytes >
options.buffer_budget_bytes) {
continue;
}
job = std::move(queue.front());
queue.pop_front();
++active;
reserved_bytes += options.chunk_bytes;
in_flight.push_back(job->op);
}
job->cancel_cb.reset();
auto result = run_job(*job);
{
std::lock_guard lk{mu};
--active;
reserved_bytes -= options.chunk_bytes;
++completed;
std::erase_if(in_flight, [&](const auto& weak_op) {
auto sp = weak_op.lock();
return !sp || sp == job->op;
});
}
cv.notify_all();
std::optional<Void::Async::ResumeTicket> ticket;
if (result.has_value()) {
ticket = job->op->try_commit_value(std::move(*result));
} else {
const auto kind =
(result.error().kind() ==
Void::Result::ErrorKind::cancelled)
? Void::Async::DomainOutcomeKind::cancelled
: Void::Async::DomainOutcomeKind::failed;
ticket = job->op->try_commit_error(
std::move(result.error()), kind);
}
if (ticket.has_value()) {
ticket->dispatch();
}
job->op->release_backend_ref_and_dispatch();
}
}
[[nodiscard]] Void::Result::Result<Void::Crypto::Digest>
run_job(const Job& job) const
{
using namespace Void::Crypto;
if (job.op->stop_requested()) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::cancelled,
"CryptoAsync::AsyncFileHasher: cancelled before open")};
}
if (job.op->is_deadline_expired(clock)) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::timeout,
"CryptoAsync::AsyncFileHasher: deadline expired before open")};
}
std::ifstream input{job.path, std::ios::binary};
if (!input.is_open()) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::io_error,
std::format(
"CryptoAsync::AsyncFileHasher: cannot open '{}'",
job.path.string()))};
}
auto hasher = Hasher::create(job.algorithm, options.provider);
if (!hasher.has_value()) {
return std::unexpected{std::move(hasher.error())};
}
std::vector<char> buffer(options.chunk_bytes);
while (input) {
if (job.op->stop_requested()) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::cancelled,
"CryptoAsync::AsyncFileHasher: stopped during file read")};
}
if (job.op->is_deadline_expired(clock)) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::timeout,
"CryptoAsync::AsyncFileHasher: deadline expired during read")};
}
input.read(buffer.data(),
static_cast<std::streamsize>(buffer.size()));
const auto count = input.gcount();
if (count > 0) {
const auto bytes = std::as_bytes(std::span{
buffer.data(), static_cast<std::size_t>(count)});
if (auto upd = hasher->update(bytes);
!upd.has_value()) {
return std::unexpected{std::move(upd.error())};
}
}
}
if (input.bad() || (!input.eof() && input.fail())) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::io_error,
std::format(
"CryptoAsync::AsyncFileHasher: I/O error reading '{}'",
job.path.string()))};
}
if (job.op->stop_requested()) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::cancelled,
"CryptoAsync::AsyncFileHasher: stopped before finalize")};
}
if (job.op->is_deadline_expired(clock)) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::timeout,
"CryptoAsync::AsyncFileHasher: deadline expired before finalize")};
}
return hasher->finalize();
}
Void::Async::Executor& executor;
FileHasherOptions options;
const Void::Time::MonotonicClock& clock;
mutable std::mutex mu{};
std::condition_variable cv{};
std::deque<std::shared_ptr<Job>> queue{};
std::vector<std::weak_ptr<
Void::Async::OperationState<Void::Crypto::Digest>>>
in_flight{};
std::vector<std::thread> workers{};
bool workers_started{false};
bool closing{false};
bool joined{false};
std::size_t active{0};
std::size_t reserved_bytes{0};
std::uint64_t completed{0};
std::uint64_t rejected{0};
};
AsyncFileHasher::AsyncFileHasher(Void::Async::Executor& executor,
FileHasherOptions options,
const Void::Time::MonotonicClock& clock)
: m_state(std::make_shared<State>(executor, std::move(options), clock))
{
}
AsyncFileHasher::~AsyncFileHasher() { (void)close_and_join(); }
Void::Coro::Task<Void::Result::Result<Void::Crypto::Digest>>
AsyncFileHasher::hash_file(Void::Crypto::HashAlgorithm algorithm,
std::filesystem::path path,
Void::Async::OperationOptions options)
{
using namespace Void::Crypto;
auto state = m_state;
if (state->options.max_concurrent == 0 ||
state->options.chunk_bytes == 0 ||
state->options.chunk_bytes > CryptoLimits::kStreamChunkBytes) {
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::invalid_argument,
"CryptoAsync::AsyncFileHasher: invalid options")};
}
if (state->options.chunk_bytes > state->options.buffer_budget_bytes) {
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::resource_exhausted,
"CryptoAsync::AsyncFileHasher: chunk_bytes exceeds buffer budget")};
}
if (options.stop.stop_requested()) {
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::cancelled,
"CryptoAsync::AsyncFileHasher: stopped before admission")};
}
if (Void::Async::is_deadline_expired(options, state->clock)) {
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::timeout,
"CryptoAsync::AsyncFileHasher: deadline expired before admission")};
}
auto op = Void::Async::OperationState<Digest>::create(
options, &state->executor, Void::Async::StopBehavior::notify_only);
auto job = std::make_shared<State::Job>(algorithm, std::move(path), op);
{
std::lock_guard lk{state->mu};
if (state->closing) {
++state->rejected;
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::closed,
"CryptoAsync::AsyncFileHasher: service is closing")};
}
const std::size_t max_effective_concurrent = std::min(
state->options.max_concurrent,
state->options.buffer_budget_bytes / state->options.chunk_bytes);
const std::size_t capacity =
max_effective_concurrent + state->options.max_waiting;
if (state->active + state->queue.size() >= capacity) {
++state->rejected;
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::overloaded,
"CryptoAsync::AsyncFileHasher: wait queue is full")};
}
op->acquire_backend_ref();
state->start_workers_locked();
if (options.stop.stop_possible()) {
std::weak_ptr<State> weak_state = state;
job->cancel_cb.emplace(options.stop, [weak_state]() {
if (auto s = weak_state.lock()) {
s->cv.notify_all();
}
});
}
state->queue.push_back(std::move(job));
}
state->cv.notify_one();
co_return co_await op->awaitable(&state->executor);
}
void AsyncFileHasher::request_stop() noexcept
{
std::vector<
std::shared_ptr<Void::Async::OperationState<Void::Crypto::Digest>>>
ops;
{
std::lock_guard lk{m_state->mu};
m_state->closing = true;
for (const auto& j : m_state->queue) {
ops.push_back(j->op);
}
for (const auto& weak_op : m_state->in_flight) {
if (auto sp = weak_op.lock()) {
ops.push_back(std::move(sp));
}
}
}
for (auto& op : ops) {
op->request_stop();
}
m_state->cv.notify_all();
}
Void::Result::Result<void> AsyncFileHasher::close_and_join()
{
request_stop();
std::vector<std::thread> threads;
{
std::lock_guard lk{m_state->mu};
if (m_state->joined) {
return {};
}
m_state->joined = true;
threads.swap(m_state->workers);
}
for (auto& t : threads) {
if (t.joinable()) {
t.join();
}
}
return {};
}
FileHasherStats AsyncFileHasher::stats() const noexcept
{
std::lock_guard lk{m_state->mu};
return FileHasherStats{
.active = m_state->active,
.waiting = m_state->queue.size(),
.reserved_buffer_bytes = m_state->reserved_bytes,
.completed = m_state->completed,
.rejected = m_state->rejected,
.closing = m_state->closing,
};
}
} // namespace Void::CryptoAsync
+6
View File
@@ -0,0 +1,6 @@
void_add_module(CryptoAsync
INTERNAL_DEPS Crypto IO Async Time Functional
EXTERNAL_DEPS Threads::Threads
EXTRA_HEADERS
Void/Crypto/AsyncHash.hpp
)
@@ -0,0 +1,11 @@
cmake_minimum_required(VERSION 4.0)
project(VoidCryptoAsyncOnlyConsumer LANGUAGES CXX)
find_package(Void CONFIG REQUIRED COMPONENTS CryptoAsync)
add_executable(void_crypto_async_only_consumer main.cpp)
target_link_libraries(void_crypto_async_only_consumer PRIVATE Void::CryptoAsync)
target_compile_features(void_crypto_async_only_consumer PRIVATE cxx_std_26)
enable_testing()
add_test(NAME CryptoAsyncOnlyConsumer COMMAND void_crypto_async_only_consumer)
+19
View File
@@ -0,0 +1,19 @@
#include <Void/Async/Executor.hpp>
#include <Void/Crypto/AsyncHash.hpp>
#include <Void/IO/Driver.hpp>
int main()
{
Void::Async::ManualExecutor exec;
auto drv = Void::IO::Driver::create(exec);
if (!drv.has_value()) {
return 1;
}
Void::CryptoAsync::AsyncFileHasher hasher{exec};
if (hasher.stats().active != 0) {
return 2;
}
(void)hasher.close_and_join();
(void)(*drv)->shutdown_and_join();
return 0;
}
+11
View File
@@ -0,0 +1,11 @@
cmake_minimum_required(VERSION 4.0)
project(VoidCryptoOnlyConsumer LANGUAGES CXX)
find_package(Void CONFIG REQUIRED COMPONENTS Crypto)
add_executable(void_crypto_only_consumer main.cpp)
target_link_libraries(void_crypto_only_consumer PRIVATE Void::Crypto)
target_compile_features(void_crypto_only_consumer PRIVATE cxx_std_26)
enable_testing()
add_test(NAME CryptoOnlyConsumer COMMAND void_crypto_only_consumer)
+31
View File
@@ -0,0 +1,31 @@
#include <Void/Crypto/Crypto.hpp>
#include <array>
#include <span>
int main()
{
auto digest = Void::Crypto::sha256("abc");
if (!digest.has_value() || digest->size() != 32) {
return 1;
}
auto key = Void::Crypto::Ed25519PrivateKey::generate();
if (!key.has_value()) {
return 2;
}
auto pub = key->public_key();
if (!pub.has_value()) {
return 3;
}
const std::array<std::byte, 4> msg{std::byte{1}, std::byte{2}, std::byte{3},
std::byte{4}};
auto sig = Void::Crypto::sign_ed25519(msg, *key);
if (!sig.has_value()) {
return 4;
}
auto ok = Void::Crypto::verify_ed25519(msg, *sig, *pub);
if (!ok.has_value() || !*ok) {
return 5;
}
return 0;
}
+18
View File
@@ -161,6 +161,24 @@ if(_has_log)
run_consumer(LogOnly "${install_prefix}" "LogOnly" ${_no_external_deps})
endif()
has_modules(_has_crypto Crypto Functional)
if(_has_crypto)
run_consumer(CryptoOnly "${install_prefix}" "CryptoOnly"
-DCMAKE_DISABLE_FIND_PACKAGE_Boost=TRUE
-DCMAKE_DISABLE_FIND_PACKAGE_LibArchive=TRUE
-DCMAKE_DISABLE_FIND_PACKAGE_PkgConfig=TRUE
-DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE)
endif()
has_modules(_has_crypto_async CryptoAsync Crypto IO Async Time Functional)
if(_has_crypto_async)
run_consumer(CryptoAsyncOnly "${install_prefix}" "CryptoAsyncOnly"
-DCMAKE_DISABLE_FIND_PACKAGE_Boost=TRUE
-DCMAKE_DISABLE_FIND_PACKAGE_LibArchive=TRUE
-DCMAKE_DISABLE_FIND_PACKAGE_PkgConfig=TRUE
-DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE)
endif()
# Foundation consumer with Core-formatting bridge and zero external packages.
has_modules(_has_foundation Math Text Time Functional Binary FunctionalCoreFormatting Memory Core)
if(_has_foundation)
+368
View File
@@ -0,0 +1,368 @@
#include <Void/Crypto/Crypto.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <algorithm>
#include <array>
#include <cstddef>
#include <string>
#include <string_view>
#include <vector>
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<std::byte> from_hex(std::string_view hex)
{
Void::Testing::require(hex.size() % 2 == 0);
std::vector<std::byte> 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<std::byte>((hi << 4) | lo));
}
return out;
}
std::string to_hex(std::span<const std::byte> 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<unsigned char>(b);
out.push_back(kHex[v >> 4]);
out.push_back(kHex[v & 0x0F]);
}
return out;
}
std::span<const std::byte> as_bytes(std::string_view text)
{
return std::as_bytes(std::span{text.data(), text.size()});
}
} // namespace
Void::Testing::Test crypto_hasher_state_poisoning_and_provider_isolation()
{
using namespace Void::Crypto;
auto h = Hasher::create(HashAlgorithm::Sha256);
Void::Testing::require(h.has_value());
Void::Testing::expect_eq(static_cast<int>(h->state()),
static_cast<int>(HasherState::Ready));
Void::Testing::require(h->update("ab").has_value());
Void::Testing::expect_eq(static_cast<int>(h->state()),
static_cast<int>(HasherState::Updating));
// Inject mid-stream update failure -> hasher is permanently poisoned.
{
ScopedFaultGuard fault{FaultConfig{FaultOperation::hash_update,
CryptoErrorCode::backend_error, 0}};
auto bad = h->update("c");
Void::Testing::require(!bad.has_value());
Void::Testing::expect_eq(bad.error().code().domain,
Void::Result::kCryptoErrorDomain);
Void::Testing::expect_eq(
bad.error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::backend_error));
}
Void::Testing::expect_eq(static_cast<int>(h->state()),
static_cast<int>(HasherState::Failed));
auto retry_update = h->update("d");
Void::Testing::require(!retry_update.has_value());
Void::Testing::expect_eq(
retry_update.error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::invalid_state));
auto retry_finalize = h->finalize();
Void::Testing::require(!retry_finalize.has_value());
Void::Testing::expect_eq(
retry_finalize.error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::invalid_state));
// Moved-from state reports MovedFrom and fails cleanly.
Hasher moved = std::move(*h);
Void::Testing::expect_eq(static_cast<int>(h->state()),
static_cast<int>(HasherState::MovedFrom));
Void::Testing::expect(!h->update("x").has_value());
Void::Testing::expect(!moved.finalize().has_value());
// Per-context unavailable provider fails without breaking subsequent
// default-provider operations.
ProviderOptions bad_provider{.property_query = "provider=nonexistent_void"};
auto unavailable = Hasher::create(HashAlgorithm::Sha256, bad_provider);
Void::Testing::require(!unavailable.has_value());
Void::Testing::expect_eq(
unavailable.error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::provider_error));
auto good = sha256("abc");
Void::Testing::require(good.has_value());
Void::Testing::expect_eq(
to_hex(*good),
std::string{"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f"
"20015ad"});
}
Void::Testing::Test crypto_ed25519_signing_vectors_and_boundaries()
{
using namespace Void::Crypto;
struct Rfc8032Vector {
std::string_view seed_hex;
std::string_view pub_hex;
std::string_view msg_hex;
std::string_view sig_hex;
};
const std::array<Rfc8032Vector, 3> vectors = {{
{"9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60",
"d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a",
"",
"e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e06522490155"
"5fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b"},
{"4ccd089b28ff96da9db6c346ec114e0f5b8a319f35aba624da8cf6ed4fb8a6fb",
"3d4017c3e843895a92b70aa74d1b7ebc9c982ccf2ec4968cc0cd55f12af4660c",
"72",
"92a009a9f0d4cab8720e820b5f642540a2b27b5416503f8fb3762223ebdb69da"
"085ac1e43e15996e458f3613d0f11d8c387b2eaeb4302aeeb00d291612bb0c00"},
{"c5aa8df43f9f837bedb7442f31dcb7b166d38535076f094b85ce3a2e0b4458f7",
"fc51cd8e6218a1a38da47ed00230f0580816ed13ba3303ac5deb911548908025",
"af82",
"6291d657deec24024827e69c3abe01a30ce548a284743a445e3680d7db5ac3ac"
"18ff9b538d16f290ae67f760984dc6594a7c15e9716ed28dc027beceea1ec40a"},
}};
for (const auto& vec : vectors) {
const auto seed = from_hex(vec.seed_hex);
const auto expected_pub = from_hex(vec.pub_hex);
const auto msg = from_hex(vec.msg_hex);
const auto expected_sig = from_hex(vec.sig_hex);
auto key = Ed25519PrivateKey::from_raw_seed(seed);
Void::Testing::require(key.has_value());
auto pub = key->public_key();
Void::Testing::require(pub.has_value());
Void::Testing::expect_eq(to_hex(pub->view()), std::string{vec.pub_hex});
auto exported = key->export_raw_seed();
Void::Testing::require(exported.has_value());
Void::Testing::expect(constant_time_equal(exported->view(), seed));
exported->clear();
Void::Testing::expect(!exported->valid());
Void::Testing::expect(exported->view().empty());
auto sig = sign_ed25519(msg, *key);
Void::Testing::require(sig.has_value());
Void::Testing::expect_eq(to_hex(sig->view()), std::string{vec.sig_hex});
auto verified = verify_ed25519(msg, *sig, *pub);
Void::Testing::require(verified.has_value());
Void::Testing::expect(*verified);
// Flipping a single signature bit yields false, NOT an error.
auto tampered_sig = *sig;
tampered_sig.bytes[0] ^= std::byte{0x01};
auto bad_verify = verify_ed25519(msg, tampered_sig, *pub);
Void::Testing::require(bad_verify.has_value());
Void::Testing::expect(!*bad_verify);
}
// Key generation round-trip.
auto generated = Ed25519PrivateKey::generate();
Void::Testing::require(generated.has_value());
auto gen_pub = generated->public_key();
Void::Testing::require(gen_pub.has_value());
auto gen_sig = sign_ed25519(as_bytes("hello ed25519"), *generated);
Void::Testing::require(gen_sig.has_value());
auto gen_ok =
verify_ed25519(as_bytes("hello ed25519"), *gen_sig, *gen_pub);
Void::Testing::require(gen_ok.has_value());
Void::Testing::expect(*gen_ok);
// Invalid sizes near boundaries must fail with typed invalid_argument.
for (const std::size_t bad_key_len : {0U, 1U, 31U, 33U, 64U}) {
std::vector<std::byte> bad_key(bad_key_len, std::byte{0x11});
auto r = verifyEd25519({}, gen_sig->view(), bad_key);
Void::Testing::require(!r.has_value());
Void::Testing::expect_eq(
r.error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::invalid_key_size));
auto import_r = Ed25519PrivateKey::from_raw_seed(bad_key);
Void::Testing::require(!import_r.has_value());
Void::Testing::expect_eq(
import_r.error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::invalid_key_size));
}
for (const std::size_t bad_sig_len : {0U, 1U, 63U, 65U}) {
std::vector<std::byte> bad_sig(bad_sig_len, std::byte{0x22});
auto r = verifyEd25519({}, bad_sig, gen_pub->view());
Void::Testing::require(!r.has_value());
Void::Testing::expect_eq(
r.error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::invalid_signature_size));
}
// Oversized message (>16 MiB) rejected before OpenSSL call.
std::vector<std::byte> huge(CryptoLimits::kMaxOneShotMessageBytes + 1U,
std::byte{0});
auto huge_sign = sign_ed25519(huge, *generated);
Void::Testing::require(!huge_sign.has_value());
Void::Testing::expect_eq(
huge_sign.error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::message_too_large));
auto huge_verify = verify_ed25519(huge, *gen_sig, *gen_pub);
Void::Testing::require(!huge_verify.has_value());
Void::Testing::expect_eq(
huge_verify.error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::message_too_large));
// Provider fault returns error without leaking secret key material.
{
ScopedFaultGuard fault{FaultConfig{FaultOperation::ed25519_sign,
CryptoErrorCode::provider_error, 0}};
auto failed = sign_ed25519(as_bytes("secret-free"), *generated);
Void::Testing::require(!failed.has_value());
Void::Testing::expect_eq(
failed.error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::provider_error));
}
}
Void::Testing::Test crypto_hmac_sha256_and_hkdf_sha256_vectors_and_guards()
{
using namespace Void::Crypto;
// RFC 4231 Case 1
{
const std::vector<std::byte> key(20, std::byte{0x0b});
auto mac = hmac_sha256(key, as_bytes("Hi There"));
Void::Testing::require(mac.has_value());
Void::Testing::expect_eq(
to_hex(*mac),
std::string{"b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e93"
"76c2e32cff7"});
}
// RFC 4231 Case 2
{
auto mac = hmac_sha256(as_bytes("Jefe"),
as_bytes("what do ya want for nothing?"));
Void::Testing::require(mac.has_value());
Void::Testing::expect_eq(
to_hex(*mac),
std::string{"5bdcc146bf60754e6a042426089575c75a003f089d2739839dec5"
"8b964ec3843"});
}
// RFC 4231 Case 3
{
const std::vector<std::byte> key(20, std::byte{0xaa});
const std::vector<std::byte> msg(50, std::byte{0xdd});
auto mac = hmac_sha256(key, msg);
Void::Testing::require(mac.has_value());
Void::Testing::expect_eq(
to_hex(*mac),
std::string{"773ea91e36800e46854db8ebd09181a72959098b3ef8c122d9635"
"514ced565fe"});
}
// Empty key and empty message work cleanly.
{
auto mac = hmac_sha256({}, {});
Void::Testing::require(mac.has_value());
Void::Testing::expect_eq(mac->size(), HmacSha256Size);
}
// RFC 5869 Appendix A Case 1
{
const std::vector<std::byte> ikm(22, std::byte{0x0b});
const auto salt = from_hex("000102030405060708090a0b0c");
const auto info = from_hex("f0f1f2f3f4f5f6f7f8f9");
std::array<std::byte, 42> okm{};
auto r = hkdf_sha256(ikm, salt, info, okm);
Void::Testing::require(r.has_value());
Void::Testing::expect_eq(
to_hex(okm),
std::string{"3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02"
"d56ecc4c5bf34007208d5b887185865"});
}
// RFC 5869 Appendix A Case 3 (empty salt & info)
{
const std::vector<std::byte> ikm(22, std::byte{0x0b});
std::array<std::byte, 42> okm{};
auto r = hkdf_sha256(ikm, {}, {}, okm);
Void::Testing::require(r.has_value());
Void::Testing::expect_eq(
to_hex(okm),
std::string{"8da4e775a563c18f715f802a063c5a31b8a11f5c5ee1879ec3454"
"e5f3c738d2d9d201395faa4b61a96c8"});
}
// HKDF guards: empty output, oversized (>4 KiB) without mutating buffer,
// overlapping spans rejected, fault wipes destination.
{
const std::vector<std::byte> ikm(16, std::byte{0x42});
std::vector<std::byte> empty_out;
auto r_empty = hkdf_sha256(ikm, {}, {}, empty_out);
Void::Testing::require(!r_empty.has_value());
Void::Testing::expect_eq(
r_empty.error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::invalid_argument));
std::vector<std::byte> too_large(CryptoLimits::kMaxHkdfOutputBytes + 1U,
std::byte{0x7A});
auto r_large = hkdf_sha256(ikm, {}, {}, too_large);
Void::Testing::require(!r_large.has_value());
Void::Testing::expect_eq(
r_large.error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::output_too_large));
Void::Testing::expect(
std::all_of(too_large.begin(), too_large.end(),
[](std::byte b) { return b == std::byte{0x7A}; }));
std::array<std::byte, 64> shared{};
shared.fill(std::byte{0x55});
auto r_overlap =
hkdf_sha256(std::span{shared}.subspan(0, 32), {}, {},
std::span{shared}.subspan(16, 32));
Void::Testing::require(!r_overlap.has_value());
Void::Testing::expect_eq(
r_overlap.error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::overlapping_buffers));
std::array<std::byte, 32> wiped{};
wiped.fill(std::byte{0xCC});
{
ScopedFaultGuard fault{
FaultConfig{FaultOperation::hkdf,
CryptoErrorCode::provider_error, 0}};
auto r_fault = hkdf_sha256(ikm, {}, {}, wiped);
Void::Testing::require(!r_fault.has_value());
}
Void::Testing::expect(
std::all_of(wiped.begin(), wiped.end(),
[](std::byte b) { return b == std::byte{0x00}; }));
}
// constant_time_equal checks
const auto a = from_hex("01020304");
const auto b = from_hex("01020304");
const auto c = from_hex("01020305");
const auto d = from_hex("010203");
Void::Testing::expect(constant_time_equal(a, b));
Void::Testing::expect(!constant_time_equal(a, c));
Void::Testing::expect(!constant_time_equal(a, d));
}
@@ -0,0 +1,333 @@
#include <Void/Async/Executor.hpp>
#include <Void/Async/TaskScope.hpp>
#include <Void/Crypto/AsyncHash.hpp>
#include <Void/IO/Driver.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <Void/Time/Clock.hpp>
#include <array>
#include <atomic>
#include <chrono>
#include <filesystem>
#include <fstream>
#include <optional>
#include <stop_token>
#include <string>
#include <thread>
#include <vector>
namespace
{
std::span<const std::byte> as_bytes(std::string_view text)
{
return std::as_bytes(std::span{text.data(), text.size()});
}
struct ScopedTempDir {
std::filesystem::path path;
ScopedTempDir()
{
static std::atomic<std::uint64_t> seq{0};
const auto id = seq.fetch_add(1, std::memory_order_relaxed);
const auto ts =
std::chrono::steady_clock::now().time_since_epoch().count();
path = std::filesystem::temp_directory_path() /
("void_crypto_async_" + std::to_string(ts) + "_" +
std::to_string(id));
std::filesystem::create_directories(path);
}
~ScopedTempDir()
{
std::error_code ec;
std::filesystem::remove_all(path, ec);
}
};
Void::Coro::Task<void> run_hash_stream(
Void::Crypto::HashAlgorithm alg, Void::IO::Driver& driver,
Void::IO::ByteStream& stream, Void::Async::OperationOptions op,
Void::CryptoAsync::StreamHashOptions hash_opts,
std::optional<Void::Result::Result<Void::Crypto::Digest>>& out)
{
out = co_await Void::CryptoAsync::hash_stream(
alg, driver, stream, std::move(op), std::move(hash_opts));
}
Void::Coro::Task<void> run_hash_file(
Void::CryptoAsync::AsyncFileHasher& hasher,
Void::Crypto::HashAlgorithm alg, std::filesystem::path path,
Void::Async::OperationOptions op,
std::optional<Void::Result::Result<Void::Crypto::Digest>>& out,
std::atomic<int>* done_counter = nullptr)
{
out = co_await hasher.hash_file(alg, std::move(path), std::move(op));
if (done_counter != nullptr) {
done_counter->fetch_add(1, std::memory_order_release);
}
}
} // namespace
Void::Testing::Test crypto_async_hash_stream_eof_errors_and_cancellation()
{
using namespace Void::Crypto;
using namespace Void::CryptoAsync;
Void::Async::ManualExecutor exec;
Void::Time::ManualClock clock;
Void::IO::BackendOptions opts{};
opts.preference = Void::IO::BackendPreference::mock;
opts.limits.max_owned_buffer_bytes = 128 * 1024;
auto drv = Void::IO::Driver::create(exec, opts, clock);
Void::Testing::require(drv.has_value());
auto* mock = (*drv)->mock_controller();
Void::Testing::require(mock != nullptr);
// 1. Multi-chunk stream matches sha256("hello async world").
{
auto stream = (*drv)->create_mock_stream();
Void::Testing::require(stream.has_value());
std::optional<Void::Result::Result<Digest>> outcome;
Void::Async::TaskScope scope{exec};
auto handle = scope.spawn(
run_hash_stream(HashAlgorithm::Sha256, **drv, *stream, {},
StreamHashOptions{.chunk_bytes = 8}, outcome));
Void::Testing::require(handle.has_value());
(void)exec.drain();
Void::Testing::require(
mock->complete_read(*stream, as_bytes("hello "), false));
(void)exec.drain();
Void::Testing::require(
mock->complete_read(*stream, as_bytes("async "), false));
(void)exec.drain();
Void::Testing::require(
mock->complete_read(*stream, as_bytes("world"), true));
(void)exec.drain();
Void::Testing::require(scope.join_pumping(exec).has_value());
Void::Testing::require(outcome.has_value() && outcome->has_value());
auto expected = sha256("hello async world");
Void::Testing::require(expected.has_value());
Void::Testing::expect_eq(**outcome, *expected);
}
// 2. Partial read then error must never produce a digest.
{
auto stream = (*drv)->create_mock_stream();
Void::Testing::require(stream.has_value());
std::optional<Void::Result::Result<Digest>> outcome;
Void::Async::TaskScope scope{exec};
auto handle = scope.spawn(
run_hash_stream(HashAlgorithm::Sha256, **drv, *stream, {},
StreamHashOptions{.chunk_bytes = 16}, outcome));
Void::Testing::require(handle.has_value());
(void)exec.drain();
Void::Testing::require(
mock->complete_read(*stream, as_bytes("partial"), false));
(void)exec.drain();
Void::Testing::require(mock->fail_read(
*stream, Void::IO::make_io_error(Void::IO::IoErrorCode::os_error,
"injected read failure")));
(void)exec.drain();
Void::Testing::require(scope.join_pumping(exec).has_value());
Void::Testing::require(outcome.has_value() && !outcome->has_value());
Void::Testing::expect_eq(
outcome->error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::io_error));
}
// 3. Stop requested racing with EOF completion must not return a digest.
{
auto stream = (*drv)->create_mock_stream();
Void::Testing::require(stream.has_value());
std::stop_source stop_src;
std::optional<Void::Result::Result<Digest>> outcome;
Void::Async::TaskScope scope{exec};
auto handle = scope.spawn(run_hash_stream(
HashAlgorithm::Sha256, **drv, *stream,
Void::Async::OperationOptions{.stop = stop_src.get_token()},
StreamHashOptions{.chunk_bytes = 16}, outcome));
Void::Testing::require(handle.has_value());
(void)exec.drain();
auto tok = mock->try_acquire_read(*stream);
Void::Testing::require(tok.has_value());
stop_src.request_stop();
(void)mock->finish_read_data(*tok, as_bytes("done"), true);
(void)exec.drain();
Void::Testing::require(scope.join_pumping(exec).has_value());
Void::Testing::require(outcome.has_value() && !outcome->has_value());
Void::Testing::expect_eq(
outcome->error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::cancelled));
}
// 4. Deadline expiry between chunks returns timeout.
{
auto stream = (*drv)->create_mock_stream();
Void::Testing::require(stream.has_value());
const auto deadline = clock.now() + std::chrono::seconds{5};
std::optional<Void::Result::Result<Digest>> outcome;
Void::Async::TaskScope scope{exec};
auto handle = scope.spawn(run_hash_stream(
HashAlgorithm::Sha256, **drv, *stream,
Void::Async::OperationOptions{.deadline = deadline},
StreamHashOptions{.chunk_bytes = 16}, outcome));
Void::Testing::require(handle.has_value());
(void)exec.drain();
Void::Testing::require(
clock.advance(std::chrono::seconds{10}).has_value());
Void::Testing::require(
mock->complete_read(*stream, as_bytes("chunk1"), false));
(void)exec.drain();
Void::Testing::require(scope.join_pumping(exec).has_value());
Void::Testing::require(outcome.has_value() && !outcome->has_value());
Void::Testing::expect_eq(
outcome->error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::timeout));
}
// 5. Buffer budget exhaustion returns resource_exhausted before reading.
{
auto hold = (*drv)->allocate_buffer(128 * 1024);
Void::Testing::require(hold.has_value());
auto stream = (*drv)->create_mock_stream();
Void::Testing::require(stream.has_value());
std::optional<Void::Result::Result<Digest>> outcome;
Void::Async::TaskScope scope{exec};
auto handle = scope.spawn(
run_hash_stream(HashAlgorithm::Sha256, **drv, *stream, {},
StreamHashOptions{.chunk_bytes = 1024}, outcome));
Void::Testing::require(handle.has_value());
(void)exec.drain();
Void::Testing::require(scope.join_pumping(exec).has_value());
Void::Testing::require(outcome.has_value() && !outcome->has_value());
Void::Testing::expect_eq(
outcome->error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::resource_exhausted));
}
Void::Testing::require((*drv)->shutdown_and_join().has_value());
}
Void::Testing::Test crypto_async_file_hasher_bounds_and_shutdown()
{
using namespace Void::Crypto;
using namespace Void::CryptoAsync;
ScopedTempDir tmp;
const auto file_path = tmp.path / "sample.bin";
{
std::ofstream out{file_path, std::ios::binary};
std::string payload(200 * 1024, 'V');
out.write(payload.data(), static_cast<std::streamsize>(payload.size()));
}
auto sync_digest = sha256File(file_path);
Void::Testing::require(sync_digest.has_value());
Void::Async::ManualExecutor exec;
AsyncFileHasher hasher{
exec,
FileHasherOptions{.max_concurrent = 2,
.max_waiting = 4,
.buffer_budget_bytes = 256 * 1024,
.chunk_bytes = 16 * 1024}};
std::array<std::optional<Void::Result::Result<Digest>>, 4> results{};
std::atomic<int> done_count{0};
{
Void::Async::TaskScope scope{exec};
for (std::size_t i = 0; i < results.size(); ++i) {
auto h = scope.spawn(run_hash_file(hasher, HashAlgorithm::Sha256,
file_path, {}, results[i],
&done_count));
Void::Testing::require(h.has_value());
}
const auto deadline =
std::chrono::steady_clock::now() + std::chrono::seconds{10};
while (done_count.load(std::memory_order_acquire) < 4 &&
std::chrono::steady_clock::now() < deadline) {
if (exec.drain() == 0) {
std::this_thread::sleep_for(std::chrono::milliseconds{1});
}
}
Void::Testing::require(scope.join_pumping(exec).has_value());
}
for (const auto& r : results) {
Void::Testing::require(r.has_value() && r->has_value());
Void::Testing::expect_eq(**r, *sync_digest);
}
// Pre-cancelled admission returns cancelled without starting.
{
std::stop_source ss;
ss.request_stop();
std::optional<Void::Result::Result<Digest>> cancelled;
Void::Async::TaskScope scope{exec};
auto h = scope.spawn(run_hash_file(
hasher, HashAlgorithm::Sha256, file_path,
Void::Async::OperationOptions{.stop = ss.get_token()}, cancelled));
Void::Testing::require(h.has_value());
Void::Testing::require(scope.join_pumping(exec).has_value());
Void::Testing::require(cancelled.has_value() && !cancelled->has_value());
Void::Testing::expect_eq(
cancelled->error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::cancelled));
}
// Shutdown stops admission cleanly and leaves zero active/reserved budget.
Void::Testing::require(hasher.close_and_join().has_value());
const auto st = hasher.stats();
Void::Testing::expect(st.closing);
Void::Testing::expect_eq(st.active, 0U);
Void::Testing::expect_eq(st.reserved_buffer_bytes, 0U);
{
std::optional<Void::Result::Result<Digest>> after_close;
Void::Async::TaskScope scope{exec};
auto h = scope.spawn(run_hash_file(hasher, HashAlgorithm::Sha256,
file_path, {}, after_close));
Void::Testing::require(h.has_value());
Void::Testing::require(scope.join_pumping(exec).has_value());
Void::Testing::require(after_close.has_value() &&
!after_close->has_value());
Void::Testing::expect_eq(
after_close->error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::closed));
}
// Budget smaller than chunk_bytes fails with resource_exhausted.
AsyncFileHasher tiny{
exec,
FileHasherOptions{.max_concurrent = 1,
.max_waiting = 1,
.buffer_budget_bytes = 1024,
.chunk_bytes = 4096}};
{
std::optional<Void::Result::Result<Digest>> budget_err;
Void::Async::TaskScope scope{exec};
auto h = scope.spawn(run_hash_file(tiny, HashAlgorithm::Sha256,
file_path, {}, budget_err));
Void::Testing::require(h.has_value());
Void::Testing::require(scope.join_pumping(exec).has_value());
Void::Testing::require(budget_err.has_value() &&
!budget_err->has_value());
Void::Testing::expect_eq(
budget_err->error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::resource_exhausted));
}
Void::Testing::require(tiny.close_and_join().has_value());
}