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::Hash {
  11. template<size_t DigestS>
  12. struct Digest {
  13. static_assert(DigestS % 8 == 0);
  14. constexpr static size_t Size = DigestS / 8;
  15. u8 data[Size];
  16. [[nodiscard]] ALWAYS_INLINE u8 const* immutable_data() const { return data; }
  17. [[nodiscard]] ALWAYS_INLINE size_t data_length() const { return Size; }
  18. [[nodiscard]] ALWAYS_INLINE ReadonlyBytes bytes() const { return { immutable_data(), data_length() }; }
  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(u8 const*, 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(ByteBuffer const& buffer) { update(buffer.data(), buffer.size()); }
  34. void update(StringView string) { update((u8 const*)string.characters_without_null_termination(), string.length()); }
  35. virtual DigestType peek() = 0;
  36. virtual DigestType digest() = 0;
  37. virtual void reset() = 0;
  38. #ifndef KERNEL
  39. virtual DeprecatedString class_name() const = 0;
  40. #endif
  41. protected:
  42. virtual ~HashFunction() = default;
  43. };
  44. }