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