Crypto: Hasher state export/import for the built-in backend (closes #53)

This commit is contained in:
faumaray committed 2026-12-04 00:27:26 +03:00
1 parent 217b20e37a
commit 7d6834979e
5 files changed
+325

No files matched your search

+10
View File
@@ -47,6 +47,16 @@ namespace Void::Crypto
/// error. Backend update/finalize failures poison the hasher.
[[nodiscard]] Void::Result::Result<Digest> finalize();
/// Serialize the in-progress state for resumable hashing. Available
/// on the built-in backend; the OpenSSL provider has no portable
/// state export and returns unsupported_algorithm.
[[nodiscard]] Void::Result::Result<std::vector<std::byte>>
export_state() const;
/// Restore a state produced by export_state() on this hasher.
[[nodiscard]] Void::Result::Result<void>
import_state(std::span<const std::byte> state);
private:
struct Impl;
+210
View File
@@ -789,6 +789,216 @@ namespace Void::Crypto::Detail
return out;
}
namespace
{
constexpr std::array<std::byte, 4> kHasherStateMagic{
std::byte{'V'}, std::byte{'H'}, std::byte{'S'}, std::byte{'1'}};
constexpr std::size_t kMaxHasherStateBytes = 512;
void append_u32(std::vector<std::byte>& out, std::uint32_t value)
{
for (int shift = 24; shift >= 0; shift -= 8) {
out.push_back(static_cast<std::byte>((value >> shift) & 0xFFU));
}
}
void append_u64(std::vector<std::byte>& out, std::uint64_t value)
{
for (int shift = 56; shift >= 0; shift -= 8) {
out.push_back(static_cast<std::byte>((value >> shift) & 0xFFU));
}
}
[[nodiscard]] bool read_u32(std::span<const std::byte> in,
std::size_t& pos,
std::uint32_t& value) noexcept
{
if (pos + 4 > in.size()) {
return false;
}
value = 0;
for (int i = 0; i < 4; ++i) {
value = (value << 8) |
std::to_integer<std::uint32_t>(in[pos + i]);
}
pos += 4;
return true;
}
[[nodiscard]] bool read_u64(std::span<const std::byte> in,
std::size_t& pos,
std::uint64_t& value) noexcept
{
if (pos + 8 > in.size()) {
return false;
}
value = 0;
for (int i = 0; i < 8; ++i) {
value = (value << 8) |
std::to_integer<std::uint64_t>(in[pos + i]);
}
pos += 8;
return true;
}
} // namespace
bool BuiltinHasher::export_state(std::vector<std::byte>& out) const noexcept
{
out.clear();
if (m_state == nullptr) {
return false;
}
out.assign(kHasherStateMagic.begin(), kHasherStateMagic.end());
if (const auto* st = std::get_if<Sha1State>(&m_state->impl)) {
out.push_back(std::byte{1});
for (const auto value : st->h) {
append_u32(out, value);
}
append_u64(out, st->buf_len);
append_u64(out, st->total_bytes);
out.insert(out.end(), st->buf.begin(), st->buf.end());
return true;
}
if (const auto* st = std::get_if<Sha256State>(&m_state->impl)) {
out.push_back(std::byte{2});
for (const auto value : st->h) {
append_u32(out, value);
}
append_u64(out, st->buf_len);
append_u64(out, st->total_bytes);
out.insert(out.end(), st->buf.begin(), st->buf.end());
return true;
}
if (const auto* st = std::get_if<Sha512State>(&m_state->impl)) {
out.push_back(std::byte{3});
for (const auto value : st->h) {
append_u64(out, value);
}
append_u64(out, st->buf_len);
append_u64(out, st->total_bytes);
out.insert(out.end(), st->buf.begin(), st->buf.end());
return true;
}
if (const auto* st = std::get_if<Blake2bState>(&m_state->impl)) {
out.push_back(std::byte{4});
for (const auto value : st->h) {
append_u64(out, value);
}
append_u64(out, st->t[0]);
append_u64(out, st->t[1]);
append_u64(out, st->buf_len);
append_u64(out, st->out_len);
out.insert(out.end(), st->buf.begin(), st->buf.end());
return true;
}
out.clear();
return false;
}
bool BuiltinHasher::import_state(std::span<const std::byte> in) noexcept
{
if (in.size() < kHasherStateMagic.size() + 1 ||
in.size() > kMaxHasherStateBytes ||
!std::equal(kHasherStateMagic.begin(), kHasherStateMagic.end(),
in.begin())) {
return false;
}
if (m_state == nullptr) {
m_state = new (std::nothrow) State();
if (m_state == nullptr) {
return false;
}
}
const unsigned tag = std::to_integer<unsigned>(in[4]);
std::size_t pos = kHasherStateMagic.size() + 1;
if (tag == 1 || tag == 2) {
constexpr std::size_t kBlock = 64;
std::array<std::uint32_t, 8> h{};
std::size_t limbs = tag == 1 ? 5 : 8;
for (std::size_t i = 0; i < limbs; ++i) {
if (!read_u32(in, pos, h[i])) {
return false;
}
}
std::uint64_t buf_len = 0;
std::uint64_t total = 0;
if (!read_u64(in, pos, buf_len) || !read_u64(in, pos, total) ||
buf_len > kBlock || pos + kBlock != in.size()) {
return false;
}
if (tag == 1) {
Sha1State st;
for (std::size_t i = 0; i < 5; ++i) {
st.h[i] = h[i];
}
st.buf_len = buf_len;
st.total_bytes = total;
std::copy_n(in.begin() + static_cast<std::ptrdiff_t>(pos), kBlock,
st.buf.begin());
m_state->wipe();
m_state->impl.emplace<Sha1State>(std::move(st));
} else {
Sha256State st;
st.h = h;
st.buf_len = buf_len;
st.total_bytes = total;
std::copy_n(in.begin() + static_cast<std::ptrdiff_t>(pos), kBlock,
st.buf.begin());
m_state->wipe();
m_state->impl.emplace<Sha256State>(std::move(st));
}
return true;
}
if (tag == 3) {
constexpr std::size_t kBlock = 128;
Sha512State st;
for (auto& value : st.h) {
if (!read_u64(in, pos, value)) {
return false;
}
}
std::uint64_t buf_len = 0;
std::uint64_t total = 0;
if (!read_u64(in, pos, buf_len) || !read_u64(in, pos, total) ||
buf_len > kBlock || pos + kBlock != in.size()) {
return false;
}
st.buf_len = buf_len;
st.total_bytes = total;
std::copy_n(in.begin() + static_cast<std::ptrdiff_t>(pos), kBlock,
st.buf.begin());
m_state->wipe();
m_state->impl.emplace<Sha512State>(std::move(st));
return true;
}
if (tag == 4) {
constexpr std::size_t kBlock = 128;
Blake2bState st;
for (auto& value : st.h) {
if (!read_u64(in, pos, value)) {
return false;
}
}
std::uint64_t buf_len = 0;
std::uint64_t out_len = 0;
if (!read_u64(in, pos, st.t[0]) || !read_u64(in, pos, st.t[1]) ||
!read_u64(in, pos, buf_len) || !read_u64(in, pos, out_len) ||
buf_len > kBlock || (out_len != 32 && out_len != 64) ||
pos + kBlock != in.size()) {
return false;
}
st.buf_len = buf_len;
st.out_len = out_len;
std::copy_n(in.begin() + static_cast<std::ptrdiff_t>(pos), kBlock,
st.buf.begin());
m_state->wipe();
m_state->impl.emplace<Blake2bState>(std::move(st));
return true;
}
return false;
}
void builtin_hmac_sha1(std::span<const std::byte> secret_key,
std::span<const std::byte> message,
std::span<std::byte> output_20) noexcept
+9
View File
@@ -6,6 +6,7 @@
#include <cstddef>
#include <cstdint>
#include <span>
#include <vector>
namespace Void::Crypto::Detail
{
@@ -31,6 +32,14 @@ namespace Void::Crypto::Detail
void update(std::span<const std::byte> data) noexcept;
[[nodiscard]] Digest finalize();
/// Serialize the in-progress hash state (versioned, self-describing).
[[nodiscard]] bool
export_state(std::vector<std::byte>& out) const noexcept;
/// Restore a state produced by export_state(). The destination is
/// wiped on any failure.
[[nodiscard]] bool
import_state(std::span<const std::byte> in) noexcept;
private:
struct State;
+58
View File
@@ -613,6 +613,64 @@ namespace Void::Crypto
#endif
}
Void::Result::Result<std::vector<std::byte>> Hasher::export_state() const
{
if (!m_impl) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::invalid_state,
"Crypto::Hasher::export_state: hasher is moved-from")};
}
if (m_impl->state != HasherState::Ready &&
m_impl->state != HasherState::Updating) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::invalid_state,
"Crypto::Hasher::export_state: hasher is not in progress")};
}
if (!m_impl->using_builtin) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::unsupported_algorithm,
"Crypto::Hasher::export_state: state export requires the "
"built-in backend")};
}
std::vector<std::byte> state;
if (!m_impl->builtin.export_state(state)) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::backend_error,
"Crypto::Hasher::export_state: state export failed")};
}
return state;
}
Void::Result::Result<void>
Hasher::import_state(std::span<const std::byte> state)
{
if (!m_impl) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::invalid_state,
"Crypto::Hasher::import_state: hasher is moved-from")};
}
if (m_impl->state != HasherState::Ready &&
m_impl->state != HasherState::Updating) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::invalid_state,
"Crypto::Hasher::import_state: hasher is not in progress")};
}
if (!m_impl->using_builtin) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::unsupported_algorithm,
"Crypto::Hasher::import_state: state import requires the "
"built-in backend")};
}
if (!m_impl->builtin.import_state(state)) {
m_impl->state = HasherState::Failed;
return std::unexpected{make_crypto_error(
CryptoErrorCode::invalid_argument,
"Crypto::Hasher::import_state: malformed or incompatible "
"state")};
}
return {};
}
auto hash(HashAlgorithm algorithm, std::span<const std::byte> data)
-> Void::Result::Result<Digest>
{
@@ -465,3 +465,41 @@ Void::Testing::Test crypto_hmac_sha256_and_hkdf_sha256_vectors_and_guards()
Void::Testing::expect(!constant_time_equal(a, c));
Void::Testing::expect(!constant_time_equal(a, d));
}
Void::Testing::Test crypto_hasher_state_export_import_round_trips()
{
using namespace Void::Crypto;
const ProviderOptions builtin{.prefer_builtin = true};
const std::string prefix{"hello "};
const std::string suffix{"world"};
const std::string whole = prefix + suffix;
for (const auto algorithm :
{HashAlgorithm::Sha1, HashAlgorithm::Sha256, HashAlgorithm::Sha512,
HashAlgorithm::Blake2b256, HashAlgorithm::Blake2b512}) {
auto hasher = Hasher::create(algorithm, builtin);
Void::Testing::require(hasher.has_value());
Void::Testing::require(hasher->update(prefix).has_value());
auto state = hasher->export_state();
Void::Testing::require(state.has_value());
auto resumed = Hasher::create(algorithm, builtin);
Void::Testing::require(resumed.has_value());
Void::Testing::require(resumed->import_state(*state).has_value());
Void::Testing::require(resumed->update(suffix).has_value());
auto resumed_digest = resumed->finalize();
Void::Testing::require(resumed_digest.has_value());
auto expected = hash(algorithm, as_bytes(whole), builtin);
Void::Testing::require(expected.has_value());
Void::Testing::expect_eq(to_hex(*resumed_digest), to_hex(*expected));
}
// Malformed state is rejected and the hasher fails closed.
auto hasher = Hasher::create(HashAlgorithm::Sha256, builtin);
Void::Testing::require(hasher.has_value());
const std::array<std::byte, 8> garbage{};
Void::Testing::expect(!hasher->import_state(garbage).has_value());
Void::Testing::expect(hasher->state() == HasherState::Failed);
}