summaryrefslogtreecommitdiff
path: root/src/buildtool/crypto/hasher.hpp
blob: a926fab1d52e31e730465727fd8d411bfc342126 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
// Copyright 2022 Huawei Cloud Computing Technology Co., Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef INCLUDED_SRC_BUILDTOOL_CRYPTO_HASHER_HPP
#define INCLUDED_SRC_BUILDTOOL_CRYPTO_HASHER_HPP

#include <cstddef>
#include <cstdint>
#include <limits>
#include <memory>
#include <optional>
#include <string>
#include <utility>  // std::move

#include "src/buildtool/logging/log_level.hpp"
#include "src/buildtool/logging/logger.hpp"
#include "src/utils/cpp/hex_string.hpp"

/// \brief Incremental hasher.
class Hasher {
  public:
    /// \brief Types of hash implementations supported by generator.
    enum class HashType : std::uint8_t { SHA1, SHA256, SHA512 };

    /// \brief The universal hash digest.
    /// The type of hash and the digest length depends on the hash
    /// implementation used to generated this digest.
    class HashDigest {
        friend Hasher;

      public:
        /// \brief Get pointer to raw bytes of digest.
        /// Length can be obtained using \ref Length.
        [[nodiscard]] auto Bytes() const& -> std::string const& {
            return bytes_;
        }

        [[nodiscard]] auto Bytes() && -> std::string {
            return std::move(bytes_);
        }

        /// \brief Get hexadecimal string of digest.
        /// Length is twice the length of raw bytes (\ref Length).
        [[nodiscard]] auto HexString() const -> std::string {
            return ToHexString(bytes_);
        }

        /// \brief Get digest length in raw bytes.
        [[nodiscard]] auto Length() const -> std::size_t {
            return bytes_.size();
        }

      private:
        std::string bytes_{};

        explicit HashDigest(std::string bytes) : bytes_{std::move(bytes)} {}
    };

    /// \brief Interface for hash implementations
    class IHashImpl {
      public:
        static constexpr size_t kCharsPerNumber =
            std::numeric_limits<std::uint8_t>::max() /
            std::numeric_limits<signed char>::max();

        IHashImpl() noexcept = default;
        IHashImpl(IHashImpl const&) = delete;
        IHashImpl(IHashImpl&&) = default;
        auto operator=(IHashImpl const&) -> IHashImpl& = delete;
        auto operator=(IHashImpl&&) -> IHashImpl& = default;
        virtual ~IHashImpl() = default;

        /// \brief Feed data to the incremental hashing.
        [[nodiscard]] virtual auto Update(std::string const& data) noexcept
            -> bool = 0;

        /// \brief Finalize the hashing and return hash as string of raw bytes.
        [[nodiscard]] virtual auto Finalize() && noexcept
            -> std::optional<std::string> = 0;

        /// \brief Compute the hash of data and return it as string of raw
        /// bytes.
        [[nodiscard]] virtual auto Compute(std::string const& data) && noexcept
            -> std::string = 0;

        /// \brief Obtain length of the resulting hash string.
        [[nodiscard]] virtual auto GetHashLength() const noexcept -> size_t = 0;

        static auto FatalError() noexcept -> void {
            Logger::Log(LogLevel::Error, "Failed to compute hash.");
            std::terminate();
        }
    };

    explicit Hasher(HashType type) : impl_{CreateHashImpl(type)} {}

    /// \brief Feed data to the hasher.
    auto Update(std::string const& data) noexcept -> bool {
        return impl_->Update(data);
    }

    /// \brief Finalize hash.
    [[nodiscard]] auto Finalize() && noexcept -> HashDigest {
        if (auto hash = std::move(*impl_).Finalize()) {
            return HashDigest{std::move(*hash)};
        }
        IHashImpl::FatalError();
        return HashDigest{{}};
    }

    /// \brief Obtain length of the resulting hash string.
    [[nodiscard]] auto GetHashLength() const noexcept -> size_t {
        return impl_->GetHashLength();
    }

  private:
    std::unique_ptr<IHashImpl> impl_;

    [[nodiscard]] static auto CreateHashImpl(HashType type) noexcept
        -> std::unique_ptr<IHashImpl>;
};

#endif  // INCLUDED_SRC_BUILDTOOL_CRYPTO_HASHER_HPP