Botan 3.14.1
Crypto and TLS for C&
sponge_processing.h
Go to the documentation of this file.
1/*
2* Byte-oriented Sponge processing helpers
3* (C) 2025 Jack Lloyd
4* 2025 René Meusel
5*
6* Botan is released under the Simplified BSD License (see license.txt)
7*/
8
9#ifndef BOTAN_SPONGE_PROCESSING_H_
10#define BOTAN_SPONGE_PROCESSING_H_
11
12#include <botan/internal/buffer_slicer.h>
13#include <botan/internal/buffer_stuffer.h>
14#include <botan/internal/loadstor.h>
15#include <array>
16#include <functional>
17#include <span>
18
19namespace Botan {
20
21namespace detail {
22
23template <typename T>
24concept SpongeLike = std::unsigned_integral<decltype(T::word_bytes)> && requires(T a) {
25 typename T::word_t;
26 typename T::state_t;
27 { a.state() } -> std::same_as<typename T::state_t&>;
28 { a._cursor() } -> std::same_as<size_t&>;
29 { a.byte_rate() } -> std::same_as<size_t>;
30};
31
32template <typename T>
33concept SpongeLikeWithTrivialPermute = SpongeLike<T> && requires(T a) {
34 { a.permute() } -> std::same_as<void>;
35};
36
37/**
38* Represents the bounds of partial byte-oriented data within a word of
39* the sponge state. Downstream algorithms can use this to conveniently
40* modify the passed in partial state word with data written or read
41* from an input or output byte buffer.
42*/
43template <SpongeLike SpongeT>
44class PartialWordBounds final {
45 public:
46 size_t offset; // NOLINT(*-non-private-member-*)
47 size_t length; // NOLINT(*-non-private-member-*)
48
49 private:
50 using word_t = typename SpongeT::word_t;
51 constexpr static auto word_bytes = SpongeT::word_bytes;
52
53 public:
54 /**
55 * Reads '.length' bytes from the provided slicer and places them
56 * within a word at the specified '.offset' in little-endian order.
57 */
58 word_t read_from(BufferSlicer& slicer) const {
59 std::array<uint8_t, word_bytes> partial_word_bytes{};
60 slicer.copy_into(std::span{partial_word_bytes}.subspan(offset, length));
61 return load_le(partial_word_bytes);
62 }
63
64 /**
65 * Writes '.length' bytes from the provided word at the specified
66 * '.offset' into the provided stuffer in little-endian order.
67 */
68 void write_into(BufferStuffer& stuffer, word_t partial_word) const {
69 const auto partial_word_bytes = store_le(partial_word);
70 stuffer.append(std::span{partial_word_bytes}.subspan(offset, length));
71 }
72
73 /**
74 * Assigns the bits in 'partial_input_word' to their corresponding
75 * bits in 'state_word' at the specified '.offset' and '.length'
76 * while leaving all other bits in 'state_word' unchanged.
77 */
78 word_t masked_assignment(word_t state_word, word_t partial_input_word) const {
80 const auto mask = ((word_t(0) - 1) >> ((word_bytes - length) * 8)) << (offset * 8);
81 return (state_word & ~mask) | (partial_input_word & mask);
82 }
83};
84
85/**
86* A drop-in replacement for `PartialWordBounds` that is optimized for
87* handling full words where no masking or offsetting is necessary.
88*/
89template <SpongeLike SpongeT>
90class FullWordBounds final {
91 private:
92 using word_t = typename SpongeT::word_t;
93 constexpr static auto word_bytes = SpongeT::word_bytes;
94
95 public:
96 word_t read_from(BufferSlicer& slicer) const { return load_le(slicer.take<word_bytes>()); }
97
98 void write_into(BufferStuffer& stuffer, word_t full_word) const { stuffer.append(store_le(full_word)); }
99
100 word_t masked_assignment(word_t /*unused*/, word_t full_input_word) const { return full_input_word; }
101};
102
103template <typename T>
104concept PermutationFn = std::invocable<T> || std::same_as<T, void()>;
105
106template <typename T, typename SpongeT, typename ModifierT>
107concept BaseModifierFn = requires(T fn, typename SpongeT::word_t word, ModifierT bounds) {
108 { std::invoke(fn, word, bounds) } -> std::same_as<typename SpongeT::word_t>;
109};
110
111template <typename T, typename SpongeT>
112concept ModifierFn =
114
115} // namespace detail
116
117/**
118* Performs the core processing loop for ingesting or extracting data into/from
119* the sponge state in a byte-oriented manner for the given number of
120* @p bytes_to_process. The provided @p word_modifier_fn is called for each
121* (partial) word of the sponge state that needs to be modified or read.
122*
123* The processing loop ensures efficient handling of unaligned input and output
124* data. For that, it calls the provided permutation function either with an
125* instance of `PartialWordBounds` or `FullWordBounds`. Hence @p word_modifier_fn
126* must be able to handle both types of bounds and should use their respective
127* methods to read from or write into input or output buffers.
128*
129* @param sponge the sponge instance to process data into or from
130* @param bytes_to_process the number of sponge state bytes to traverse
131* @param permutation_fn a function that performs the sponge's permutation
132* @param modifier_fn a function that modifies the sponge state words
133*/
134template <detail::SpongeLike SpongeT>
136 size_t bytes_to_process,
137 const detail::PermutationFn auto& permutation_fn,
138 const detail::ModifierFn<SpongeT> auto& modifier_fn) {
139 if(bytes_to_process == 0) {
140 return;
141 }
142
143 constexpr auto word_bytes = SpongeT::word_bytes;
144 const auto byte_rate = sponge.byte_rate();
145 auto& S = sponge.state();
146 auto& cursor = sponge._cursor();
147
148 // If necessary, try to get aligned with the sponge state's words array
149 const auto bytes_out_of_word_alignment = static_cast<size_t>(cursor % word_bytes);
150 if(bytes_out_of_word_alignment > 0) {
151 const auto bytes_until_word_alignment = word_bytes - bytes_out_of_word_alignment;
152 const auto bytes_from_input = std::min(bytes_to_process, bytes_until_word_alignment);
153 BOTAN_DEBUG_ASSERT(bytes_from_input < word_bytes);
154
155 S[cursor / word_bytes] = modifier_fn(S[cursor / word_bytes],
157 .offset = bytes_out_of_word_alignment,
158 .length = bytes_from_input,
159 });
160 cursor += bytes_from_input;
161 bytes_to_process -= bytes_from_input;
162
163 if(cursor == byte_rate) {
164 permutation_fn();
165 cursor = 0;
166 }
167 }
168
169 // If we didn't exhaust the bytes to process for this invocation, we should
170 // be word-aligned with the sponge state now
171 BOTAN_DEBUG_ASSERT(bytes_to_process == 0 || cursor % word_bytes == 0);
172
173 // Block-wise incorporation of the input data into the sponge state until
174 // all input bytes are processed
175 while(bytes_to_process >= word_bytes) {
176 // Process full words until we either run out of data or reach the
177 // end of the current sponge state block
178 while(bytes_to_process >= word_bytes && cursor < byte_rate) {
179 S[cursor / word_bytes] = modifier_fn(S[cursor / word_bytes], detail::FullWordBounds<SpongeT>{});
180 cursor += word_bytes;
181 bytes_to_process -= word_bytes;
182 }
183
184 if(cursor == byte_rate) {
185 permutation_fn();
186 cursor = 0;
187 }
188 }
189
190 // Process the remaining bytes that don't fill an entire word.
191 // Therefore, leaving the sponge state in an unaligned state that won't
192 // need another permutation until the next call to process().
193 BOTAN_DEBUG_ASSERT(bytes_to_process < word_bytes && cursor < byte_rate);
194 if(bytes_to_process > 0) {
195 S[cursor / word_bytes] = modifier_fn(S[cursor / word_bytes],
197 .offset = 0,
198 .length = bytes_to_process,
199 });
200 cursor += bytes_to_process;
201 }
202}
203
204template <detail::SpongeLikeWithTrivialPermute SpongeT>
205inline void process_bytes_in_sponge(SpongeT& sponge,
206 size_t bytes_to_process,
207 const detail::ModifierFn<SpongeT> auto& modifier_fn) {
209 sponge, bytes_to_process, [&sponge] { sponge.permute(); }, modifier_fn);
210}
211
212/**
213* Absorbs @p input data into the @p sponge state.
214*
215* @param sponge The sponge state to absorb data into.
216* @param input The input data to absorb.
217* @param permutation_fn The function to call for the sponge's permutation.
218*/
219template <detail::SpongeLike SpongeT>
220inline void absorb_into_sponge(SpongeT& sponge,
221 std::span<const uint8_t> input,
222 const detail::PermutationFn auto& permutation_fn) {
223 using word_t = typename SpongeT::word_t;
224
225 BufferSlicer input_slicer(input);
226 process_bytes_in_sponge(sponge, input.size(), permutation_fn, [&](word_t state_word, auto bounds) {
227 return state_word ^ bounds.read_from(input_slicer);
228 });
229 BOTAN_ASSERT_NOMSG(input_slicer.empty());
230}
231
232inline void absorb_into_sponge(detail::SpongeLikeWithTrivialPermute auto& sponge, std::span<const uint8_t> input) {
233 absorb_into_sponge(sponge, input, [&sponge] { sponge.permute(); });
234}
235
236/**
237* Squeezes @p output data from the @p sponge state.
238*
239* @param sponge The sponge state to squeeze data from.
240* @param output The output buffer to write the squeezed data into.
241* @param permutation_fn The function to call for the sponge's permutation.
242*/
243template <detail::SpongeLike SpongeT>
244inline void squeeze_from_sponge(SpongeT& sponge,
245 std::span<uint8_t> output,
246 const detail::PermutationFn auto& permutation_fn) {
247 using word_t = typename SpongeT::word_t;
248
249 BufferStuffer output_stuffer(output);
250 process_bytes_in_sponge(sponge, output.size(), permutation_fn, [&](word_t state_word, auto bounds) {
251 bounds.write_into(output_stuffer, state_word);
252 return state_word;
253 });
254 BOTAN_ASSERT_NOMSG(output_stuffer.full());
255}
256
257inline void squeeze_from_sponge(detail::SpongeLikeWithTrivialPermute auto& sponge, std::span<uint8_t> output) {
258 squeeze_from_sponge(sponge, output, [&sponge] { sponge.permute(); });
259}
260
261} // namespace Botan
262
263#endif
#define BOTAN_ASSERT_NOMSG(expr)
Definition assert.h:82
#define BOTAN_DEBUG_ASSERT(expr)
Definition assert.h:136
void copy_into(std::span< uint8_t > sink)
std::span< const uint8_t > take(const size_t count)
Helper class to ease in-place marshalling of concatenated fixed-length values.
constexpr void append(std::span< const uint8_t > buffer)
constexpr bool full() const
word_t masked_assignment(word_t, word_t full_input_word) const
word_t read_from(BufferSlicer &slicer) const
void write_into(BufferStuffer &stuffer, word_t full_word) const
word_t masked_assignment(word_t state_word, word_t partial_input_word) const
void write_into(BufferStuffer &stuffer, word_t partial_word) const
word_t read_from(BufferSlicer &slicer) const
#define BOTAN_FORCE_INLINE
Definition compiler.h:86
BOTAN_FORCE_INLINE void process_bytes_in_sponge(SpongeT &sponge, size_t bytes_to_process, const detail::PermutationFn auto &permutation_fn, const detail::ModifierFn< SpongeT > auto &modifier_fn)
void squeeze_from_sponge(SpongeT &sponge, std::span< uint8_t > output, const detail::PermutationFn auto &permutation_fn)
constexpr auto store_le(ParamTs &&... params)
Definition loadstor.h:736
constexpr auto load_le(ParamTs &&... params)
Definition loadstor.h:495
void absorb_into_sponge(SpongeT &sponge, std::span< const uint8_t > input, const detail::PermutationFn auto &permutation_fn)
std::conditional_t< HasNative64BitRegisters, std::uint64_t, uint32_t > word
The native machine word, used as the limb type for multiprecision integers.
Definition types.h:131