SHA1.h 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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/String.h>
  8. #include <LibCrypto/Hash/HashFunction.h>
  9. namespace Crypto {
  10. namespace Hash {
  11. namespace SHA1Constants {
  12. constexpr static u32 InitializationHashes[5] { 0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0 };
  13. constexpr static u32 RoundConstants[4] {
  14. 0X5a827999,
  15. 0X6ed9eba1,
  16. 0X8f1bbcdc,
  17. 0Xca62c1d6,
  18. };
  19. }
  20. class SHA1 final : public HashFunction<512, 160> {
  21. public:
  22. using HashFunction::update;
  23. SHA1()
  24. {
  25. reset();
  26. }
  27. virtual void update(const u8*, size_t) override;
  28. virtual DigestType digest() override;
  29. virtual DigestType peek() override;
  30. inline static DigestType hash(const u8* data, size_t length)
  31. {
  32. SHA1 sha;
  33. sha.update(data, length);
  34. return sha.digest();
  35. }
  36. inline static DigestType hash(const ByteBuffer& buffer) { return hash(buffer.data(), buffer.size()); }
  37. inline static DigestType hash(StringView buffer) { return hash((const u8*)buffer.characters_without_null_termination(), buffer.length()); }
  38. virtual String class_name() const override
  39. {
  40. return "SHA1";
  41. }
  42. inline virtual void reset() override
  43. {
  44. m_data_length = 0;
  45. m_bit_length = 0;
  46. for (auto i = 0; i < 5; ++i)
  47. m_state[i] = SHA1Constants::InitializationHashes[i];
  48. }
  49. private:
  50. inline void transform(const u8*);
  51. u8 m_data_buffer[BlockSize] {};
  52. size_t m_data_length { 0 };
  53. u64 m_bit_length { 0 };
  54. u32 m_state[5];
  55. constexpr static auto FinalBlockDataSize = BlockSize - 8;
  56. constexpr static auto Rounds = 80;
  57. };
  58. }
  59. }