MD5.h 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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 <AK/Types.h>
  9. #include <LibCrypto/Hash/HashFunction.h>
  10. namespace Crypto {
  11. namespace Hash {
  12. namespace MD5Constants {
  13. constexpr u32 init_A = 0x67452301;
  14. constexpr u32 init_B = 0xefcdab89;
  15. constexpr u32 init_C = 0x98badcfe;
  16. constexpr u32 init_D = 0x10325476;
  17. constexpr u32 S11 = 7;
  18. constexpr u32 S12 = 12;
  19. constexpr u32 S13 = 17;
  20. constexpr u32 S14 = 22;
  21. constexpr u32 S21 = 5;
  22. constexpr u32 S22 = 9;
  23. constexpr u32 S23 = 14;
  24. constexpr u32 S24 = 20;
  25. constexpr u32 S31 = 4;
  26. constexpr u32 S32 = 11;
  27. constexpr u32 S33 = 16;
  28. constexpr u32 S34 = 23;
  29. constexpr u32 S41 = 6;
  30. constexpr u32 S42 = 10;
  31. constexpr u32 S43 = 15;
  32. constexpr u32 S44 = 21;
  33. constexpr u8 PADDING[] = {
  34. 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  35. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  36. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  37. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  38. 0
  39. };
  40. }
  41. class MD5 final : public HashFunction<512, 128> {
  42. public:
  43. using HashFunction::update;
  44. virtual void update(const u8*, size_t) override;
  45. virtual DigestType digest() override;
  46. virtual DigestType peek() override;
  47. virtual String class_name() const override { return "MD5"; }
  48. inline static DigestType hash(const u8* data, size_t length)
  49. {
  50. MD5 md5;
  51. md5.update(data, length);
  52. return md5.digest();
  53. }
  54. inline static DigestType hash(const ByteBuffer& buffer) { return hash(buffer.data(), buffer.size()); }
  55. inline static DigestType hash(StringView buffer) { return hash((const u8*)buffer.characters_without_null_termination(), buffer.length()); }
  56. inline virtual void reset() override
  57. {
  58. m_A = MD5Constants::init_A;
  59. m_B = MD5Constants::init_B;
  60. m_C = MD5Constants::init_C;
  61. m_D = MD5Constants::init_D;
  62. m_count[0] = 0;
  63. m_count[1] = 0;
  64. __builtin_memset(m_data_buffer, 0, sizeof(m_data_buffer));
  65. }
  66. private:
  67. inline void transform(const u8*);
  68. static void encode(const u32* from, u8* to, size_t length);
  69. static void decode(const u8* from, u32* to, size_t length);
  70. u32 m_A { MD5Constants::init_A }, m_B { MD5Constants::init_B }, m_C { MD5Constants::init_C }, m_D { MD5Constants::init_D };
  71. u32 m_count[2] { 0, 0 };
  72. u8 m_data_buffer[64] {};
  73. };
  74. }
  75. }