Botan 3.6.1
Crypto and TLS for C&
keccak_helpers.cpp
Go to the documentation of this file.
1/*
2 * Helper functions to implement Keccak-derived functions from NIST SP.800-185
3 * (C) 2023 Jack Lloyd
4 * (C) 2023 René Meusel - Rohde & Schwarz Cybersecurity
5 *
6 * Botan is released under the Simplified BSD License (see license.txt)
7 */
8
9#include <botan/internal/keccak_helpers.h>
10
11#include <botan/internal/bit_ops.h>
12#include <botan/internal/loadstor.h>
13
14#include <limits>
15
16namespace Botan {
17
18namespace {
19
20size_t int_encoding_size(uint64_t x) {
21 BOTAN_ASSERT_NOMSG(x < std::numeric_limits<uint64_t>::max());
22 return ceil_tobytes(std::max(uint8_t(1), ceil_log2(x + 1)));
23}
24
25uint8_t encode(std::span<uint8_t> out, uint64_t x) {
26 const auto bytes_needed = int_encoding_size(x);
27 BOTAN_ASSERT_NOMSG(out.size() >= bytes_needed);
28
29 std::array<uint8_t, sizeof(x)> bigendian_x;
30 store_be(x, bigendian_x.data());
31
32 auto begin = bigendian_x.begin();
33 std::advance(begin, sizeof(x) - bytes_needed);
34 std::copy(begin, bigendian_x.end(), out.begin());
35
36 return static_cast<uint8_t>(bytes_needed);
37}
38
39} // namespace
40
41std::span<const uint8_t> keccak_int_left_encode(std::span<uint8_t> out, size_t x) {
42 BOTAN_ASSERT_NOMSG(!out.empty());
43 out[0] = encode(out.last(out.size() - 1), x);
44 return out.first(out[0] + 1 /* the length tag */);
45}
46
47std::span<const uint8_t> keccak_int_right_encode(std::span<uint8_t> out, size_t x) {
48 const auto bytes_needed = encode(out, x);
49 BOTAN_ASSERT_NOMSG(out.size() >= bytes_needed + size_t(1));
50 out[bytes_needed] = bytes_needed;
51 return out.first(bytes_needed + 1 /* the length tag */);
52}
53
54size_t keccak_int_encoding_size(size_t x) {
55 return int_encoding_size(x) + 1 /* the length tag */;
56}
57
58} // namespace Botan
#define BOTAN_ASSERT_NOMSG(expr)
Definition assert.h:59
std::string encode(const uint8_t der[], size_t length, std::string_view label, size_t width)
Definition pem.cpp:39
std::span< const uint8_t > keccak_int_left_encode(std::span< uint8_t > out, size_t x)
std::span< const uint8_t > keccak_int_right_encode(std::span< uint8_t > out, size_t x)
constexpr T ceil_tobytes(T bits)
Definition bit_ops.h:157
size_t keccak_int_encoding_size(size_t x)
constexpr auto store_be(ParamTs &&... params)
Definition loadstor.h:773
constexpr uint8_t ceil_log2(T x)
Definition bit_ops.h:122