HashFunction.h 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. };
  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(u8 const*, 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(ByteBuffer const& buffer) { update(buffer.data(), buffer.size()); }
  35. void update(StringView string) { update((u8 const*)string.characters_without_null_termination(), string.length()); }
  36. virtual DigestType peek() = 0;
  37. virtual DigestType digest() = 0;
  38. virtual void reset() = 0;
  39. #ifndef KERNEL
  40. virtual DeprecatedString class_name() const = 0;
  41. #endif
  42. protected:
  43. virtual ~HashFunction() = default;
  44. };
  45. }
  46. template<size_t DigestS>
  47. struct AK::Formatter<Crypto::Hash::Digest<DigestS>> : StandardFormatter {
  48. ErrorOr<void> format(FormatBuilder& builder, Crypto::Hash::Digest<DigestS> const& digest)
  49. {
  50. for (size_t i = 0; i < digest.Size; ++i) {
  51. if (i > 0 && i % 4 == 0)
  52. TRY(builder.put_padding('-', 1));
  53. TRY(builder.put_u64(digest.data[i], 16, false, false, true, FormatBuilder::Align::Right, 2));
  54. }
  55. return {};
  56. }
  57. };