Botan 3.4.0
Crypto and TLS for C&
trunc_hash.cpp
Go to the documentation of this file.
1/**
2 * Wrapper for truncated hashes
3 * (C) 2023 Jack Lloyd
4 * 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/trunc_hash.h>
10
11#include <botan/exceptn.h>
12#include <botan/internal/fmt.h>
13
14namespace Botan {
15
16void Truncated_Hash::add_data(std::span<const uint8_t> input) {
17 m_hash->update(input);
18}
19
20void Truncated_Hash::final_result(std::span<uint8_t> out) {
21 BOTAN_ASSERT_NOMSG(m_hash->output_length() * 8 >= m_output_bits);
22
23 m_hash->final(m_buffer);
24
25 // truncate output to a full number of bytes
26 const auto bytes = output_length();
27 std::copy_n(m_buffer.begin(), bytes, out.data());
28 zeroise(m_buffer);
29
30 // mask the unwanted bits in the final byte
31 const uint8_t bits_in_last_byte = ((m_output_bits - 1) % 8) + 1;
32 const uint8_t bitmask = ~((1 << (8 - bits_in_last_byte)) - 1);
33
34 out.back() &= bitmask;
35}
36
38 return (m_output_bits + 7) / 8;
39}
40
41std::string Truncated_Hash::name() const {
42 return fmt("Truncated({},{})", m_hash->name(), m_output_bits);
43}
44
45std::unique_ptr<HashFunction> Truncated_Hash::new_object() const {
46 return std::make_unique<Truncated_Hash>(m_hash->new_object(), m_output_bits);
47}
48
49std::unique_ptr<HashFunction> Truncated_Hash::copy_state() const {
50 return std::make_unique<Truncated_Hash>(m_hash->copy_state(), m_output_bits);
51}
52
54 m_hash->clear();
55}
56
57Truncated_Hash::Truncated_Hash(std::unique_ptr<HashFunction> hash, size_t bits) :
58 m_hash(std::move(hash)), m_output_bits(bits), m_buffer(m_hash->output_length()) {
60
61 if(m_output_bits == 0) {
62 throw Invalid_Argument("Truncating a hash to 0 does not make sense");
63 }
64
65 if(m_hash->output_length() * 8 < m_output_bits) {
66 throw Invalid_Argument("Underlying hash function does not produce enough bytes for truncation");
67 }
68}
69
70} // namespace Botan
#define BOTAN_ASSERT_NOMSG(expr)
Definition assert.h:59
#define BOTAN_ASSERT_NONNULL(ptr)
Definition assert.h:86
Truncated_Hash(std::unique_ptr< HashFunction > hash, size_t length)
size_t output_length() const override
std::string name() const override
std::unique_ptr< HashFunction > new_object() const override
std::unique_ptr< HashFunction > copy_state() const override
void clear() override
void zeroise(std::vector< T, Alloc > &vec)
Definition secmem.h:108
std::string fmt(std::string_view format, const T &... args)
Definition fmt.h:53