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