HashFunction.h 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /*
  2. * Copyright (c) 2020, Ali Mohammad Pur <mpfard@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/ByteBuffer.h>
  8. #include <AK/StringView.h>
  9. #include <AK/Types.h>
  10. namespace Crypto {
  11. namespace Hash {
  12. template<size_t DigestS>
  13. struct Digest {
  14. static_assert(DigestS % 8 == 0);
  15. constexpr static size_t Size = DigestS / 8;
  16. u8 data[Size];
  17. [[nodiscard]] ALWAYS_INLINE const u8* immutable_data() const { return data; }
  18. [[nodiscard]] ALWAYS_INLINE size_t data_length() const { return Size; }
  19. [[nodiscard]] ALWAYS_INLINE ReadonlyBytes bytes() const { return { immutable_data(), data_length() }; }
  20. };
  21. template<size_t BlockS, size_t DigestS, typename DigestT = Digest<DigestS>>
  22. class HashFunction {
  23. public:
  24. static_assert(BlockS % 8 == 0);
  25. static constexpr auto BlockSize = BlockS / 8;
  26. static_assert(DigestS % 8 == 0);
  27. static constexpr auto DigestSize = DigestS / 8;
  28. using DigestType = DigestT;
  29. constexpr static size_t block_size() { return BlockSize; }
  30. constexpr static size_t digest_size() { return DigestSize; }
  31. virtual void update(const u8*, size_t) = 0;
  32. void update(Bytes buffer) { update(buffer.data(), buffer.size()); }
  33. void update(ReadonlyBytes buffer) { update(buffer.data(), buffer.size()); }
  34. void update(const ByteBuffer& buffer) { update(buffer.data(), buffer.size()); }
  35. void update(StringView string) { update((const u8*)string.characters_without_null_termination(), string.length()); }
  36. virtual DigestType peek() = 0;
  37. virtual DigestType digest() = 0;
  38. virtual void reset() = 0;
  39. virtual String class_name() const = 0;
  40. protected:
  41. virtual ~HashFunction() = default;
  42. };
  43. }
  44. }