Coverage Report

Created: 2024-11-29 06:10

/src/botan/src/lib/permutations/keccak_perm/keccak_helpers.cpp
Line
Count
Source (jump to first uncovered line)
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
16
namespace Botan {
17
18
namespace {
19
20
0
size_t int_encoding_size(uint64_t x) {
21
0
   BOTAN_ASSERT_NOMSG(x < std::numeric_limits<uint64_t>::max());
22
0
   return ceil_tobytes(std::max(uint8_t(1), ceil_log2(x + 1)));
23
0
}
24
25
0
uint8_t encode(std::span<uint8_t> out, uint64_t x) {
26
0
   const auto bytes_needed = int_encoding_size(x);
27
0
   BOTAN_ASSERT_NOMSG(out.size() >= bytes_needed);
28
29
0
   std::array<uint8_t, sizeof(x)> bigendian_x;
30
0
   store_be(x, bigendian_x.data());
31
32
0
   auto begin = bigendian_x.begin();
33
0
   std::advance(begin, sizeof(x) - bytes_needed);
34
0
   std::copy(begin, bigendian_x.end(), out.begin());
35
36
0
   return static_cast<uint8_t>(bytes_needed);
37
0
}
38
39
}  // namespace
40
41
0
std::span<const uint8_t> keccak_int_left_encode(std::span<uint8_t> out, size_t x) {
42
0
   BOTAN_ASSERT_NOMSG(!out.empty());
43
0
   out[0] = encode(out.last(out.size() - 1), x);
44
0
   return out.first(out[0] + 1 /* the length tag */);
45
0
}
46
47
0
std::span<const uint8_t> keccak_int_right_encode(std::span<uint8_t> out, size_t x) {
48
0
   const auto bytes_needed = encode(out, x);
49
0
   BOTAN_ASSERT_NOMSG(out.size() >= bytes_needed + size_t(1));
50
0
   out[bytes_needed] = bytes_needed;
51
0
   return out.first(bytes_needed + 1 /* the length tag */);
52
0
}
53
54
0
size_t keccak_int_encoding_size(size_t x) {
55
0
   return int_encoding_size(x) + 1 /* the length tag */;
56
0
}
57
58
}  // namespace Botan