SHA1.h 1.7 KB

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