Botan 3.9.0
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(sizeof(x) >= bytes_needed);
28 BOTAN_ASSERT_NOMSG(out.size() >= bytes_needed);
29
30 const size_t leading_zeros = sizeof(x) - bytes_needed;
31
32 std::array<uint8_t, sizeof(x)> bigendian_x{};
33 store_be(x, bigendian_x.data());
34
35 std::copy(bigendian_x.begin() + leading_zeros, bigendian_x.end(), out.begin());
36
37 return static_cast<uint8_t>(bytes_needed);
38}
39
40} // namespace
41
42std::span<const uint8_t> keccak_int_left_encode(std::span<uint8_t> out, size_t x) {
43 BOTAN_ASSERT_NOMSG(!out.empty());
44 out[0] = encode(out.last(out.size() - 1), x);
45 return out.first(out[0] + 1 /* the length tag */);
46}
47
48std::span<const uint8_t> keccak_int_right_encode(std::span<uint8_t> out, size_t x) {
49 const auto bytes_needed = encode(out, x);
50 BOTAN_ASSERT_NOMSG(out.size() >= bytes_needed + size_t(1));
51 out[bytes_needed] = bytes_needed;
52 return out.first(bytes_needed + 1 /* the length tag */);
53}
54
55size_t keccak_int_encoding_size(size_t x) {
56 return int_encoding_size(x) + 1 /* the length tag */;
57}
58
59} // namespace Botan
#define BOTAN_ASSERT_NOMSG(expr)
Definition assert.h:75
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 uint8_t ceil_log2(T x)
Definition bit_ops.h:120
BOTAN_FORCE_INLINE constexpr T ceil_tobytes(T bits)
Definition bit_ops.h:155
size_t keccak_int_encoding_size(size_t x)
constexpr auto store_be(ParamTs &&... params)
Definition loadstor.h:745