MD5.h 2.4 KB

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