HashFunction.h 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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/Format.h>
  9. #include <AK/StringView.h>
  10. #include <AK/Types.h>
  11. namespace Crypto::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 u8 const* 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. [[nodiscard]] bool operator==(Digest const& other) const = default;
  21. [[nodiscard]] bool operator!=(Digest const& other) const = default;
  22. };
  23. template<size_t BlockS, size_t DigestS, typename DigestT = Digest<DigestS>>
  24. class HashFunction {
  25. public:
  26. static_assert(BlockS % 8 == 0);
  27. static constexpr auto BlockSize = BlockS / 8;
  28. static_assert(DigestS % 8 == 0);
  29. static constexpr auto DigestSize = DigestS / 8;
  30. using DigestType = DigestT;
  31. constexpr static size_t block_size() { return BlockSize; }
  32. constexpr static size_t digest_size() { return DigestSize; }
  33. virtual void update(u8 const*, size_t) = 0;
  34. void update(Bytes buffer) { update(buffer.data(), buffer.size()); }
  35. void update(ReadonlyBytes buffer) { update(buffer.data(), buffer.size()); }
  36. void update(ByteBuffer const& buffer) { update(buffer.data(), buffer.size()); }
  37. void update(StringView string) { update((u8 const*)string.characters_without_null_termination(), string.length()); }
  38. virtual DigestType peek() = 0;
  39. virtual DigestType digest() = 0;
  40. virtual void reset() = 0;
  41. #ifndef KERNEL
  42. virtual ByteString class_name() const = 0;
  43. #endif
  44. protected:
  45. virtual ~HashFunction() = default;
  46. };
  47. }
  48. template<size_t DigestS>
  49. struct AK::Formatter<Crypto::Hash::Digest<DigestS>> : StandardFormatter {
  50. ErrorOr<void> format(FormatBuilder& builder, Crypto::Hash::Digest<DigestS> const& digest)
  51. {
  52. for (size_t i = 0; i < digest.Size; ++i) {
  53. if (i > 0 && i % 4 == 0)
  54. TRY(builder.put_padding('-', 1));
  55. TRY(builder.put_u64(digest.data[i], 16, false, false, true, false, FormatBuilder::Align::Right, 2));
  56. }
  57. return {};
  58. }
  59. };