SHA1.h 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. template<size_t Bytes>
  21. struct SHA1Digest {
  22. u8 data[Bytes];
  23. constexpr static size_t Size = Bytes;
  24. const u8* immutable_data() const { return data; }
  25. size_t data_length() const { return Bytes; }
  26. };
  27. class SHA1 final : public HashFunction<512, SHA1Digest<160 / 8>> {
  28. public:
  29. using HashFunction::update;
  30. SHA1()
  31. {
  32. reset();
  33. }
  34. virtual void update(const u8*, size_t) override;
  35. virtual DigestType digest() override;
  36. virtual DigestType peek() override;
  37. inline static DigestType hash(const u8* data, size_t length)
  38. {
  39. SHA1 sha;
  40. sha.update(data, length);
  41. return sha.digest();
  42. }
  43. inline static DigestType hash(const ByteBuffer& buffer) { return hash(buffer.data(), buffer.size()); }
  44. inline static DigestType hash(const StringView& buffer) { return hash((const u8*)buffer.characters_without_null_termination(), buffer.length()); }
  45. virtual String class_name() const override
  46. {
  47. return "SHA1";
  48. };
  49. inline virtual void reset() override
  50. {
  51. m_data_length = 0;
  52. m_bit_length = 0;
  53. for (auto i = 0; i < 5; ++i)
  54. m_state[i] = SHA1Constants::InitializationHashes[i];
  55. }
  56. private:
  57. inline void transform(const u8*);
  58. u8 m_data_buffer[BlockSize] {};
  59. size_t m_data_length { 0 };
  60. u64 m_bit_length { 0 };
  61. u32 m_state[5];
  62. constexpr static auto FinalBlockDataSize = BlockSize - 8;
  63. constexpr static auto Rounds = 80;
  64. };
  65. }
  66. }