ZXFoundation™ 26h2
Loading...
Searching...
No Matches
core.cxxm
1/// SPDX-License-Identifier: Apache 2.0
2/// @file crypto/sha256.cxxm
3/// @brief SHA-256 streaming hash implementation
4
5export module crypto.sha256.core;
6import zxfoundation.base.types;
7import lib.error;
8import std;
9
10export {
11
12namespace crypto::sha256 {
13
14 /// @brief Byte length of a SHA-256 message digest.
15 constexpr auto SHA256_DIGEST_SIZE = 32U;
16
17 /// @brief SHA-256 running computation context.
18 struct sha256_ctx {
19 u32 state[8]{}; ///< Current intermediate hash values (H0..H7).
20 u64 bit_count{}; ///< Total message bits processed so far.
21 u8 buf[64]{}; ///< Partial-block accumulation buffer.
22 u32 buf_len{}; ///< Number of valid bytes in buf (0..63).
23 bool finalized{}; ///< Set by sha256_final(); guards against double-finalize.
24 };
25
26 /// @brief Initialize a SHA-256 context to the FIPS 180-4 initial hash value.
27 /// @param[out] ctx Context to initialize.
28 auto sha256_init(sha256_ctx& ctx) -> void;
29
30 /// @brief Feed a span of bytes into a running SHA-256 computation.
31 /// @param[in,out] ctx Running SHA-256 context.
32 /// @param[in] data Input byte span.
33 /// @return std::expected<void, lib::kernel_error>
34 auto sha256_update(sha256_ctx& ctx, std::span<const u8> data)
35 -> std::expected<void, lib::kernel_error>;
36
37 /// @brief Finalize the hash and write the 32-byte digest.
38 /// @param[in,out] ctx Running SHA-256 context.
39 /// @param[out] out Exactly 32-byte output span.
40 /// @return std::expected<void, lib::kernel_error>
41 auto sha256_final(sha256_ctx& ctx, std::span<u8, SHA256_DIGEST_SIZE> out)
42 -> std::expected<void, lib::kernel_error>;
43
44 /// @brief One-shot SHA-256: hash @p data and write the 32-byte digest to @p out.
45 [[nodiscard]] auto sha256_hash(std::span<const u8> data, std::span<u8, SHA256_DIGEST_SIZE> out)
46 -> std::expected<void, lib::kernel_error>;
47
48 [[nodiscard]] auto sha256_verify(std::span<const u8> data,
49 std::span<const u8, SHA256_DIGEST_SIZE> expected)
50 -> std::expected<void, lib::kernel_error>;
51
52} // namespace crypto::sha256
53
54} // end export