HashFunction.h 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. };
  20. template<size_t BlockS, size_t DigestS, typename DigestT = Digest<DigestS>>
  21. class HashFunction {
  22. public:
  23. static_assert(BlockS % 8 == 0);
  24. static constexpr auto BlockSize = BlockS / 8;
  25. static_assert(DigestS % 8 == 0);
  26. static constexpr auto DigestSize = DigestS / 8;
  27. using DigestType = DigestT;
  28. constexpr static size_t block_size() { return BlockSize; }
  29. constexpr static size_t digest_size() { return DigestSize; }
  30. virtual void update(const u8*, size_t) = 0;
  31. void update(Bytes buffer) { update(buffer.data(), buffer.size()); }
  32. void update(ReadonlyBytes buffer) { update(buffer.data(), buffer.size()); }
  33. void update(const ByteBuffer& buffer) { update(buffer.data(), buffer.size()); }
  34. void update(StringView string) { update((const u8*)string.characters_without_null_termination(), string.length()); }
  35. virtual DigestType peek() = 0;
  36. virtual DigestType digest() = 0;
  37. virtual void reset() = 0;
  38. virtual String class_name() const = 0;
  39. protected:
  40. virtual ~HashFunction() = default;
  41. };
  42. }
  43. }